@mlightcad/cad-simple-viewer 1.5.1 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/index.js +22465 -22159
- package/dist/index.umd.cjs +585 -604
- package/dist/mtext-renderer-worker.js +1877 -1878
- package/lib/app/AcApDocManager.d.ts +13 -3
- package/lib/app/AcApDocManager.d.ts.map +1 -1
- package/lib/app/AcApDocManager.js +63 -29
- package/lib/app/AcApDocManager.js.map +1 -1
- package/lib/app/index.d.ts +1 -0
- package/lib/app/index.d.ts.map +1 -1
- package/lib/app/index.js +1 -0
- package/lib/app/index.js.map +1 -1
- package/lib/app/openFileProgress.d.ts +10 -0
- package/lib/app/openFileProgress.d.ts.map +1 -0
- package/lib/app/openFileProgress.js +20 -0
- package/lib/app/openFileProgress.js.map +1 -0
- package/lib/command/AcApSwitchBgCmd.d.ts +3 -0
- package/lib/command/AcApSwitchBgCmd.d.ts.map +1 -1
- package/lib/command/AcApSwitchBgCmd.js +14 -7
- package/lib/command/AcApSwitchBgCmd.js.map +1 -1
- package/lib/command/AcApZoomCmd.d.ts.map +1 -1
- package/lib/command/AcApZoomCmd.js.map +1 -1
- package/lib/command/convert/index.d.ts +0 -4
- package/lib/command/convert/index.d.ts.map +1 -1
- package/lib/command/convert/index.js +0 -4
- package/lib/command/convert/index.js.map +1 -1
- package/lib/command/draw/AcApArcCmd.d.ts.map +1 -1
- package/lib/command/draw/AcApArcCmd.js +2 -1
- package/lib/command/draw/AcApArcCmd.js.map +1 -1
- package/lib/command/draw/AcApCircleCmd.d.ts.map +1 -1
- package/lib/command/draw/AcApCircleCmd.js.map +1 -1
- package/lib/command/draw/AcApEllipseCmd.d.ts.map +1 -1
- package/lib/command/draw/AcApEllipseCmd.js.map +1 -1
- package/lib/command/draw/AcApPolylineCmd.d.ts.map +1 -1
- package/lib/command/draw/AcApPolylineCmd.js.map +1 -1
- package/lib/command/draw/AcApRayCmd.d.ts.map +1 -1
- package/lib/command/draw/AcApRayCmd.js.map +1 -1
- package/lib/command/draw/AcApRectCmd.d.ts.map +1 -1
- package/lib/command/draw/AcApRectCmd.js +2 -1
- package/lib/command/draw/AcApRectCmd.js.map +1 -1
- package/lib/command/draw/AcApXLineCmd.d.ts.map +1 -1
- package/lib/command/draw/AcApXLineCmd.js.map +1 -1
- package/lib/command/modify/AcApOffsetCmd.d.ts.map +1 -1
- package/lib/command/modify/AcApOffsetCmd.js +2 -1
- package/lib/command/modify/AcApOffsetCmd.js.map +1 -1
- package/lib/editor/global/AcEdUiColor.d.ts +183 -0
- package/lib/editor/global/AcEdUiColor.d.ts.map +1 -0
- package/lib/editor/global/AcEdUiColor.js +224 -0
- package/lib/editor/global/AcEdUiColor.js.map +1 -0
- package/lib/editor/global/AcEdUiTheme.d.ts +0 -1
- package/lib/editor/global/AcEdUiTheme.d.ts.map +1 -1
- package/lib/editor/global/AcEdUiTheme.js +0 -5
- package/lib/editor/global/AcEdUiTheme.js.map +1 -1
- package/lib/editor/global/eventBus.d.ts +3 -0
- package/lib/editor/global/eventBus.d.ts.map +1 -1
- package/lib/editor/global/eventBus.js.map +1 -1
- package/lib/editor/global/index.d.ts +1 -0
- package/lib/editor/global/index.d.ts.map +1 -1
- package/lib/editor/global/index.js +1 -0
- package/lib/editor/global/index.js.map +1 -1
- package/lib/editor/input/AcEdCursorManager.d.ts +4 -0
- package/lib/editor/input/AcEdCursorManager.d.ts.map +1 -1
- package/lib/editor/input/AcEdCursorManager.js +11 -8
- package/lib/editor/input/AcEdCursorManager.js.map +1 -1
- package/lib/editor/input/AcEdOrthoMode.d.ts +11 -0
- package/lib/editor/input/AcEdOrthoMode.d.ts.map +1 -0
- package/lib/editor/input/AcEdOrthoMode.js +22 -0
- package/lib/editor/input/AcEdOrthoMode.js.map +1 -0
- package/lib/editor/input/AcEdPolarTracking.d.ts +107 -0
- package/lib/editor/input/AcEdPolarTracking.d.ts.map +1 -0
- package/lib/editor/input/AcEdPolarTracking.js +398 -0
- package/lib/editor/input/AcEdPolarTracking.js.map +1 -0
- package/lib/editor/input/AcEditor.d.ts +4 -0
- package/lib/editor/input/AcEditor.d.ts.map +1 -1
- package/lib/editor/input/AcEditor.js +6 -0
- package/lib/editor/input/AcEditor.js.map +1 -1
- package/lib/editor/input/index.d.ts +2 -0
- package/lib/editor/input/index.d.ts.map +1 -1
- package/lib/editor/input/index.js +2 -0
- package/lib/editor/input/index.js.map +1 -1
- package/lib/editor/input/marker/AcEdMarker.d.ts.map +1 -1
- package/lib/editor/input/marker/AcEdMarker.js +3 -2
- package/lib/editor/input/marker/AcEdMarker.js.map +1 -1
- package/lib/editor/input/marker/AcEdOSnapMarkerManager.d.ts +4 -0
- package/lib/editor/input/marker/AcEdOSnapMarkerManager.d.ts.map +1 -1
- package/lib/editor/input/marker/AcEdOSnapMarkerManager.js +11 -0
- package/lib/editor/input/marker/AcEdOSnapMarkerManager.js.map +1 -1
- package/lib/editor/input/ui/AcEdCommandLine.d.ts.map +1 -1
- package/lib/editor/input/ui/AcEdCommandLine.js +1 -1
- package/lib/editor/input/ui/AcEdCommandLine.js.map +1 -1
- package/lib/editor/input/ui/AcEdFloatingInput.d.ts +4 -0
- package/lib/editor/input/ui/AcEdFloatingInput.d.ts.map +1 -1
- package/lib/editor/input/ui/AcEdFloatingInput.js +27 -0
- package/lib/editor/input/ui/AcEdFloatingInput.js.map +1 -1
- package/lib/editor/input/ui/AcEdFloatingInputTypes.d.ts +5 -0
- package/lib/editor/input/ui/AcEdFloatingInputTypes.d.ts.map +1 -1
- package/lib/editor/input/ui/AcEdFloatingMessage.js +1 -1
- package/lib/editor/input/ui/AcEdFloatingMessage.js.map +1 -1
- package/lib/editor/input/ui/AcEdInputManager.d.ts.map +1 -1
- package/lib/editor/input/ui/AcEdInputManager.js +47 -26
- package/lib/editor/input/ui/AcEdInputManager.js.map +1 -1
- package/lib/editor/input/ui/AcEdMTextEditor.d.ts.map +1 -1
- package/lib/editor/input/ui/AcEdMTextEditor.js +3 -2
- package/lib/editor/input/ui/AcEdMTextEditor.js.map +1 -1
- package/lib/editor/input/ui/AcEdRubberBand.d.ts +8 -0
- package/lib/editor/input/ui/AcEdRubberBand.d.ts.map +1 -1
- package/lib/editor/input/ui/AcEdRubberBand.js +46 -29
- package/lib/editor/input/ui/AcEdRubberBand.js.map +1 -1
- package/lib/i18n/en/command.d.ts +7 -1
- package/lib/i18n/en/command.d.ts.map +1 -1
- package/lib/i18n/en/command.js +7 -1
- package/lib/i18n/en/command.js.map +1 -1
- package/lib/i18n/zh/command.d.ts +7 -1
- package/lib/i18n/zh/command.d.ts.map +1 -1
- package/lib/i18n/zh/command.js +7 -1
- package/lib/i18n/zh/command.js.map +1 -1
- package/lib/plugin/AcApLazyPluginRegistration.d.ts +28 -0
- package/lib/plugin/AcApLazyPluginRegistration.d.ts.map +1 -0
- package/lib/plugin/AcApLazyPluginRegistration.js +2 -0
- package/lib/plugin/AcApLazyPluginRegistration.js.map +1 -0
- package/lib/plugin/AcApPluginManager.d.ts +38 -0
- package/lib/plugin/AcApPluginManager.d.ts.map +1 -1
- package/lib/plugin/AcApPluginManager.js +147 -22
- package/lib/plugin/AcApPluginManager.js.map +1 -1
- package/lib/plugin/index.d.ts +1 -0
- package/lib/plugin/index.d.ts.map +1 -1
- package/lib/plugin/index.js +1 -0
- package/lib/plugin/index.js.map +1 -1
- package/lib/util/AcApExportFileNameUtil.d.ts +22 -0
- package/lib/util/AcApExportFileNameUtil.d.ts.map +1 -0
- package/lib/util/AcApExportFileNameUtil.js +49 -0
- package/lib/util/AcApExportFileNameUtil.js.map +1 -0
- package/lib/util/AcApFontUtil.d.ts +10 -0
- package/lib/util/AcApFontUtil.d.ts.map +1 -1
- package/lib/util/AcApFontUtil.js +12 -0
- package/lib/util/AcApFontUtil.js.map +1 -1
- package/lib/util/index.d.ts +1 -0
- package/lib/util/index.d.ts.map +1 -1
- package/lib/util/index.js +1 -0
- package/lib/util/index.js.map +1 -1
- package/lib/view/AcTrLayoutView.d.ts +1 -1
- package/lib/view/AcTrLayoutView.d.ts.map +1 -1
- package/lib/view/AcTrLayoutView.js +2 -1
- package/lib/view/AcTrLayoutView.js.map +1 -1
- package/lib/view/AcTrLayoutViewManager.d.ts +3 -1
- package/lib/view/AcTrLayoutViewManager.d.ts.map +1 -1
- package/lib/view/AcTrLayoutViewManager.js +4 -2
- package/lib/view/AcTrLayoutViewManager.js.map +1 -1
- package/lib/view/AcTrView2d.d.ts +18 -1
- package/lib/view/AcTrView2d.d.ts.map +1 -1
- package/lib/view/AcTrView2d.js +72 -52
- package/lib/view/AcTrView2d.js.map +1 -1
- package/lib/view/index.d.ts +1 -0
- package/lib/view/index.d.ts.map +1 -1
- package/lib/view/index.js +1 -0
- package/lib/view/index.js.map +1 -1
- package/package.json +9 -12
- package/dist/viewer-runtime.iife.js +0 -3879
- package/lib/command/convert/AcApConvertToSvgCmd.d.ts +0 -32
- package/lib/command/convert/AcApConvertToSvgCmd.d.ts.map +0 -1
- package/lib/command/convert/AcApConvertToSvgCmd.js +0 -98
- package/lib/command/convert/AcApConvertToSvgCmd.js.map +0 -1
- package/lib/command/convert/AcApExportHtmlCmd.d.ts +0 -22
- package/lib/command/convert/AcApExportHtmlCmd.d.ts.map +0 -1
- package/lib/command/convert/AcApExportHtmlCmd.js +0 -93
- package/lib/command/convert/AcApExportHtmlCmd.js.map +0 -1
- package/lib/command/convert/AcApHtmlConvertor.d.ts +0 -61
- package/lib/command/convert/AcApHtmlConvertor.d.ts.map +0 -1
- package/lib/command/convert/AcApHtmlConvertor.js +0 -223
- package/lib/command/convert/AcApHtmlConvertor.js.map +0 -1
- package/lib/command/convert/AcApHtmlSnapshotBuilder.d.ts +0 -65
- package/lib/command/convert/AcApHtmlSnapshotBuilder.d.ts.map +0 -1
- package/lib/command/convert/AcApHtmlSnapshotBuilder.js +0 -301
- package/lib/command/convert/AcApHtmlSnapshotBuilder.js.map +0 -1
- package/lib/command/convert/AcApSvgConvertor.d.ts +0 -53
- package/lib/command/convert/AcApSvgConvertor.d.ts.map +0 -1
- package/lib/command/convert/AcApSvgConvertor.js +0 -103
- package/lib/command/convert/AcApSvgConvertor.js.map +0 -1
package/dist/index.umd.cjs
CHANGED
|
@@ -1,607 +1,113 @@
|
|
|
1
|
-
(function(P,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("@mlightcad/data-model"),require("lodash-es"),require("three"),require("three/examples/jsm/lines/LineSegments2.js"),require("three/examples/jsm/lines/LineSegmentsGeometry.js"),require("@mlightcad/mtext-renderer"),require("three/examples/jsm/lines/LineMaterial.js"),require("three/examples/jsm/utils/BufferGeometryUtils.js"),require("three/examples/jsm/renderers/CSS2DRenderer.js"),require("three/examples/jsm/controls/OrbitControls"),require("@mlightcad/cad-html-exporter"),require("three/examples/jsm/lines/Line2.js"),require("three/examples/jsm/lines/LineGeometry.js"),require("three/examples/jsm/libs/stats.module")):typeof define=="function"&&define.amd?define(["exports","@mlightcad/data-model","lodash-es","three","three/examples/jsm/lines/LineSegments2.js","three/examples/jsm/lines/LineSegmentsGeometry.js","@mlightcad/mtext-renderer","three/examples/jsm/lines/LineMaterial.js","three/examples/jsm/utils/BufferGeometryUtils.js","three/examples/jsm/renderers/CSS2DRenderer.js","three/examples/jsm/controls/OrbitControls","@mlightcad/cad-html-exporter","three/examples/jsm/lines/Line2.js","three/examples/jsm/lines/LineGeometry.js","three/examples/jsm/libs/stats.module"],u):(P=typeof globalThis<"u"?globalThis:P||self,u(P["cad-simple-viewer"]={},P.dataModel,P.lodashEs,P.c,P.LineSegments2_js,P.LineSegmentsGeometry_js,P.mtextRenderer,P.LineMaterial_js,P.BufferGeometryUtils_js,P.CSS2DRenderer_js,P.OrbitControls,P.cadHtmlExporter,P.Line2_js,P.LineGeometry_js,P.Stats))})(this,function(P,u,Ue,va,We,Fe,B,bt,Sa,os,Aa,fe,Ca,_a,Pa){"use strict";var gu=Object.defineProperty;var mu=(P,u,Ue)=>u in P?gu(P,u,{enumerable:!0,configurable:!0,writable:!0,value:Ue}):P[u]=Ue;var I=(P,u,Ue)=>mu(P,typeof u!="symbol"?u+"":u,Ue);function La(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const t in a)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>a[t]})}}return e.default=a,Object.freeze(e)}const f=La(va),Qi=class Qi{constructor(e){this._database=e}getAnnotationLayer(){const e="$revision_",t=u.MLIGHTCAD_APPID,i=this._database.tables.layerTable;for(const c of i.newIterator())if(this.hasAnnotationXData(c))return c.name;let n=1,s=`${e}${n}`;for(;i.has(s);)n++,s=`${e}${n}`;const r=new u.AcDbLayerTableRecord({name:s,isOff:!1,color:new u.AcCmColor(u.AcCmColorMethod.ByACI,1),isPlottable:!0}),o=new u.AcDbResultBuffer([{code:u.AcDbDxfCode.ExtendedDataRegAppName,value:t},{code:u.AcDbDxfCode.ExtendedDataAsciiString,value:t}]);return r.setXData(o),i.add(r),s}filterAnnotationEntities(e){const t=this.getAnnotationLayer();return e.filter(i=>{const n=this._database.tables.blockTable.getEntityById(i);return n&&n.layer==t})}hasAnnotationXData(e){const t=u.MLIGHTCAD_APPID,i=e.getXData(t);if(!i)return!1;for(const n of i)if(n.code===u.AcDbDxfCode.ExtendedDataAsciiString&&n.value===t)return!0;return!1}};Qi.DEFAULT_ANNOTATION_COLOR=new u.AcCmColor(u.AcCmColorMethod.ByACI,1),Qi.DEFAULT_ANNOTATION_LINE_WEIGHT=u.AcGiLineWeight.LineWeight100;let we=Qi;class as{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.entityErased.addEventListener(i=>{this.view.removeEntity(i.entity)}),t.database.events.layerAppended.addEventListener(i=>{this._view.addLayer(i.layer)}),t.database.events.layerModified.addEventListener(i=>{this._view.updateLayer(i.layer,i.changes)}),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(i=>{if(i.name==u.AcDbSystemVariables.PDMODE.toLowerCase())this._view.rerenderPoints(i.database.pdmode);else if(i.name==u.AcDbSystemVariables.LWDISPLAY.toLowerCase()){const n=this._view,s=!!i.database.lwdisplay;n.renderer.showLineWeight!==s&&(n.renderer.showLineWeight=s,n.clear(),i.database.regen())}}),t.database.events.dictObjetSet.addEventListener(i=>{i.object instanceof u.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}}var be=(a=>(a[a.NoSpecialCursor=-1]="NoSpecialCursor",a[a.Crosshair=0]="Crosshair",a[a.RectCursor=1]="RectCursor",a[a.RubberBand=2]="RubberBand",a[a.NotRotated=3]="NotRotated",a[a.TargetBox=4]="TargetBox",a[a.RotatedCrosshair=5]="RotatedCrosshair",a[a.CrosshairNoRotate=6]="CrosshairNoRotate",a[a.Invisible=7]="Invisible",a[a.EntitySelect=8]="EntitySelect",a[a.Parallelogram=9]="Parallelogram",a[a.EntitySelectNoPersp=10]="EntitySelectNoPersp",a[a.PkfirstOrGrips=11]="PkfirstOrGrips",a[a.CrosshairDashed=12]="CrosshairDashed",a[a.Grab=13]="Grab",a))(be||{});class cs{constructor(e){this._backgroundColor=0,this._totalLength=20,this._view=e,this._cursorMap=new Map,this.setCursorColor(this._backgroundColor===0?"white":"black"),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(t=>{if(t.name===u.AcDbSystemVariables.PICKBOX.toLowerCase()){let i=t.newVal;i=i>=0?i:0,this._cursorMap.set(0,this.createRectCrossIcon(i,this._totalLength-i,this._backgroundColor===0?"white":"black")),this.setCursor(this._currentCursor)}else if(t.name===u.AcDbSystemVariables.WHITEBKCOLOR.toLowerCase()){const i=t.newVal;this._backgroundColor=i?16777215:0,this.setCursorColor(this._backgroundColor===0?"white":"black")}}),this.setCursor(0)}get currentCursor(){return this._currentCursor}setCursor(e){const t=this._view.canvas;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)}this._currentCursor=e}setCursorColor(e){const i=this.createRectCrossIcon(10,this._totalLength-10,e);this._cursorMap.set(0,i),this._currentCursor===0&&(this._view.canvas.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
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
<line x1="${e+t}" y1="${n+t}" x2="${e+2*t}" y2="${n+t}" stroke="${i}" />
|
|
6
|
-
<line x1="${n+t}" y1="${e+t}" x2="${n+t}" y2="${e+2*t}" stroke="${i}" />
|
|
7
|
-
<line x1="0" y1="${n+t}" x2="${t}" y2="${n+t}" stroke="${i}" />
|
|
8
|
-
</svg>
|
|
9
|
-
`;return this.encodeSvgToCursor(r,n+t,n+t)}}class ei{constructor(e=[]){this.events={selectionAdded:new u.AcCmEventManager,selectionRemoved:new u.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})}}}class sn{constructor(e,t,i,n=!0,s=!1,r=!0){this._displayName=e,this._globalName=t??e,this._localName=i??this._globalName,this._enabled=n,this._isReadOnly=s,this._visible=r}get displayName(){return this._displayName}set displayName(e){this._isReadOnly||(this._displayName=e)}get enabled(){return this._enabled}set enabled(e){this._isReadOnly||(this._enabled=e)}get globalName(){return this._globalName}set globalName(e){this._isReadOnly||(this._globalName=e)}get isReadOnly(){return this._isReadOnly}get localName(){return this._localName}set localName(e){this._isReadOnly||(this._localName=e)}get visible(){return this._visible}set visible(e){this._isReadOnly||(this._visible=e)}get alias(){return this._globalName.replace(/[^A-Z]/g,"")}}class ls{constructor(e){if(this._keywords=[],!e)return;const t=e.trim().split(/\s+/),i=[],n=[];let s=!1;for(const o of t){if(o==="_"){s=!0;continue}(s?n:i).push(o)}const r=Math.max(i.length,n.length);for(let o=0;o<r;o++){const c=i[o],l=n[o],h=x=>{if(!x)return;const A=x.indexOf(",");return A>=0?x.substring(0,A):x},d=h(l),g=h(c),m=d!==void 0,y=g!==void 0,w=m?d:"",C=y?g:void 0,b=new sn(w||C||"",w,C,!0,!1,!0);this._keywords.push(b)}}add(e,t,i,n=!0,s=!0){let r,o,c;t===void 0?(r=e,o=e,c=e):i===void 0?(r=t,o=e,c=t):(r=e,o=t,c=i);const l=new sn(r,o,c,n,!1,s);return this._keywords.push(l),l}clear(){this._keywords=[],this._defaultKeyword=void 0}toArray(){return this._keywords.slice()}get default(){return this._defaultKeyword}set default(e){if(e&&!this._keywords.includes(e))throw new Error("Default keyword must be one of the collection's keywords");this._defaultKeyword=e}getDisplayString(e=!1){return this._keywords.filter(i=>i.visible&&i.enabled).map(i=>(!e&&this._defaultKeyword===i,i.displayName)).join("/")}getPromptFormat(){const e=this._keywords.filter(s=>s.visible).map(s=>s.displayName),t=this._defaultKeyword&&this._defaultKeyword.visible?this._defaultKeyword.displayName:void 0,i=`[${e.join("/")}]`,n=t?` <${t}>`:"";return{visibleKeywords:e,defaultKeyword:t,formattedTail:`${i}${n}:`}}[Symbol.iterator](){let e=0;const t=this._keywords;return{next(){return e<t.length?{done:!1,value:t[e++]}:{done:!0,value:void 0}}}}findByDisplayName(e){return this._keywords.find(t=>t.displayName.toLowerCase()===e.toLowerCase())}findByGlobalName(e){return this._keywords.find(t=>t.globalName.toLowerCase()===e.toLowerCase())}findByName(e){if(!e)return;let t=e.trim();if(!t)return;const i=t.startsWith("_");i&&(t=t.substring(1));const n=t.toLowerCase();return this._keywords.find(s=>s.enabled?s.globalName.toLowerCase()===n?!0:i?!1:!!(s.localName&&s.localName.toLowerCase()===n||s.alias&&s.alias.toLowerCase()===n||s.displayName.toLowerCase()===n):!1)}get count(){return this._keywords.length}}class Pe{constructor(e,t){this._message="",this._appendKeywordsToMessage=!0,this._isReadOnly=!1,this._keywords=new ls,t!==void 0?this.setMessageAndKeywords(e,t):this._message=e}get jig(){return this._jig}set jig(e){this._isReadOnly||(this._jig=e)}get message(){return this._message}set message(e){this._isReadOnly||(this._message=e)}get appendKeywordsToMessage(){return this._appendKeywordsToMessage}set appendKeywordsToMessage(e){this._isReadOnly||(this._appendKeywordsToMessage=e)}get isReadOnly(){return this._isReadOnly}get keywords(){return this._keywords}getKeywordPromptFormat(){return this._keywords.getPromptFormat()}setMessageAndKeywords(e,t){if(this._isReadOnly)return this;const i=e.match(/^(.*?)\s*\[(.*?)\](.*)?$/);if(i){const[,n,s]=i;if(this._message=n.trim(),s!==void 0){const r=s.split("/").map(o=>o.trim()).filter(o=>o.length>0);this._keywords.clear();for(const o of r){let l=t.split(/\s+/).find(h=>h.toLowerCase()===o.toLowerCase());l||(l=o),this._keywords.add(o,l)}}}return this}}class xe extends Pe{constructor(e,t){super(e,t),this._useBasePoint=!0,this._useDashedLine=!0,this._useAngleBase=!1,this._defaultValue=0,this._useDefaultValue=!1,this._allowZero=!0,this._allowNegative=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get baseAngle(){return this._baseAngle??0}set baseAngle(e){this.isReadOnly||(this._baseAngle=e)}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get useAngleBase(){return this._useAngleBase}set useAngleBase(e){this.isReadOnly||(this._useAngleBase=e)}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}get allowZero(){return this._allowZero}set allowZero(e){this.isReadOnly||(this._allowZero=e)}get allowNegative(){return this._allowNegative}set allowNegative(e){this.isReadOnly||(this._allowNegative=e)}}class ti extends Pe{constructor(e,t){super(e),this._useBasePoint=!1,this._useDashedLine=!1,this._disableOSnap=!1,this._secondCornerMessage=t}get firstCornerMessage(){return this.message}set firstCornerMessage(e){this.isReadOnly||(this.message=e)}get secondCornerMessage(){return this._secondCornerMessage}set secondCornerMessage(e){this.isReadOnly||(this._secondCornerMessage=e)}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get disableOSnap(){return this._disableOSnap}set disableOSnap(e){this.isReadOnly||(this._disableOSnap=e)}}class ae{constructor(e,t){this.status=e,this.stringResult=t}}class ii extends ae{constructor(e,t,i){super(e,i),this.value=t}}class ni extends Pe{constructor(e,t){super(e,t),this._defaultValue=0,this._useDefaultValue=!1,this._allowNone=!1,this._allowArbitraryInput=!1,this._allowNegative=!1,this._allowZero=!0}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowArbitraryInput(){return this._allowArbitraryInput}set allowArbitraryInput(e){this.isReadOnly||(this._allowArbitraryInput=e)}get allowNegative(){return this._allowNegative}set allowNegative(e){this.isReadOnly||(this._allowNegative=e)}get allowZero(){return this._allowZero}set allowZero(e){this.isReadOnly||(this._allowZero=e)}}class he extends ni{constructor(e){super(e),this._useBasePoint=!1,this._useDashedLine=!0,this._only2d=!0,this.allowNegative=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get only2d(){return this._only2d}set only2d(e){this.isReadOnly||(this._only2d=e)}}class X extends ni{}class rn extends ae{constructor(e,t){super(e,void 0),this.value=t}}class ie extends rn{constructor(e,t){super(e,t)}}class Le extends Pe{constructor(e,t){super(e,t),this._allowNone=!1,this._allowObjectOnLockedLayer=!1,this._rejectMessage="Invalid object selected.",this._allowedClasses=new Set}normalizeClassName(e){const t=e.trim();return t.startsWith("AcDb")?t.slice(4):t}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowObjectOnLockedLayer(){return this._allowObjectOnLockedLayer}set allowObjectOnLockedLayer(e){this.isReadOnly||(this._allowObjectOnLockedLayer=e)}get rejectMessage(){return this._rejectMessage}setRejectMessage(e){return this.isReadOnly||(this._rejectMessage=e),this}addAllowedClass(e){if(!this.isReadOnly){const t=this.normalizeClassName(e);t&&this._allowedClasses.add(t)}return this}removeAllowedClass(e){if(!this.isReadOnly){const t=this.normalizeClassName(e);t&&this._allowedClasses.delete(t)}return this}clearAllowedClasses(){return this.isReadOnly||this._allowedClasses.clear(),this}isClassAllowed(e){const t=this.normalizeClassName(e);return this._allowedClasses.size===0||this._allowedClasses.has(t)}}class si extends ae{constructor(e,t,i){super(e),this.objectId=t,this.pickedPoint=i}}class on extends ni{constructor(e,t,i){super(e),typeof t=="number"&&(this._lowerLimit=Math.floor(t)),typeof i=="number"&&(this._upperLimit=Math.ceil(i))}get lowerLimit(){return this._lowerLimit}set lowerLimit(e){this.isReadOnly||(this._lowerLimit=typeof e=="number"?Math.floor(e):void 0)}get upperLimit(){return this._upperLimit}set upperLimit(e){this.isReadOnly||(this._upperLimit=typeof e=="number"?Math.floor(e):void 0)}}class ri extends rn{constructor(e,t){super(e,t)}}class Y extends Pe{constructor(e,t){super(e,t),this._allowNone=!1,this._allowArbitraryInput=!1}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowArbitraryInput(){return this._allowArbitraryInput}set allowArbitraryInput(e){this.isReadOnly||(this._allowArbitraryInput=e)}}class D extends Pe{constructor(e,t){super(e,t),this._useBasePoint=!1,this._useDashedLine=!1,this._allowNone=!1,this._disableOSnap=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get disableOSnap(){return this._disableOSnap}set disableOSnap(e){this.isReadOnly||(this._disableOSnap=e)}}class oi extends ae{constructor(e,t){super(e,void 0),this.value=t}}class je extends Pe{constructor(e,t){super(e,t),this._singleOnly=!1}get singleOnly(){return this._singleOnly}set singleOnly(e){this._singleOnly=e}}class xt extends ae{constructor(e,t,i){super(e,i),this.value=t}}class ce extends Pe{constructor(e,t){super(e,t),this._allowSpaces=!0,this._allowEmpty=!1,this._defaultValue="",this._useDefaultValue=!1}get allowSpaces(){return this._allowSpaces}set allowSpaces(e){this.isReadOnly||(this._allowSpaces=e)}get allowEmpty(){return this._allowEmpty}set allowEmpty(e){this.isReadOnly||(this._allowEmpty=e)}get maxLength(){return this._maxLength}set maxLength(e){this.isReadOnly||(this._maxLength=e)}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}}var v=(a=>(a[a.Cancel=-5002]="Cancel",a[a.Error=-5001]="Error",a[a.Keyword=-5005]="Keyword",a[a.Modeless=5027]="Modeless",a[a.None=5e3]="None",a[a.OK=5100]="OK",a[a.Other=5028]="Other",a))(v||{});const Me=class Me{static get messages(){return this._messages}static getLocaleMessage(e){return this._messages[e]}static mergeLocaleMessage(e,t){hs(this._messages[e],t)}static registerMessage(e,t){this.mergeLocaleMessage(e,t)}static setCurrentLocale(e){const t=this._currentLocale;this._currentLocale=e,this.events.localeChanged.dispatch({old:t,new:this._currentLocale})}static get currentLocale(){return this._currentLocale}static t(e,t){const i=this._currentLocale,n=this._messages[i],s=e.split(".");let r=n;for(const o of s){if(!r||typeof r!="object")return(t==null?void 0:t.fallback)??e;r=r[o]}return typeof r=="string"?r:(t==null?void 0:t.fallback)??e}static cmdDescription(e,t){const i=`command.${e}.${t.toLowerCase()}.description`;return this.t(i)}static cmdPrompt(e,t){const i=`command.${e}.${t.toLowerCase()}.prompt`;return this.t(i)}static sysCmdDescription(e){return this.cmdDescription(le.SYSTEMT_COMMAND_GROUP_NAME,e)}static sysCmdPrompt(e){return this.cmdPrompt(le.SYSTEMT_COMMAND_GROUP_NAME,e)}};Me._messages={en:{},zh:{}},Me._currentLocale="en",Me.events={localeChanged:new u.AcCmEventManager},Me.userCmdDescription=e=>Me.cmdDescription(le.DEFAUT_COMMAND_GROUP_NAME,e),Me.userCmdPrompt=e=>Me.cmdPrompt(le.DEFAUT_COMMAND_GROUP_NAME,e);let p=Me;function hs(a,e){for(const t of Object.keys(e)){const i=e[t],n=a[t];us(n)&&us(i)?hs(n,i):a[t]=i}}function us(a){return typeof a=="object"&&a!==null}const Ta={ACAD:{"-hatch":{description:"Creates hatch fills through command-line options without the ribbon UI"},"-layer":{description:"Manages layers through command-line options"},angbase:{description:"Sets the base angle 0 direction with respect to the current UCS"},angdir:{description:"Sets whether positive angles are measured clockwise or counterclockwise"},arc:{description:"Creates an arc"},aunits:{description:"Sets the display format for angles"},auprec:{description:"Sets the display precision for angles, used together with AUNITS"},cdxf:{description:"Exports current drawing to DXF"},cecolor:{description:"Sets the current default color for newly created objects"},celtscale:{description:"Controls the linetype scale factor for newly created objects"},celtype:{description:"Sets the linetype for newly created objects"},celweight:{description:"Sets the default lineweight for newly created objects"},cetranparency:{description:"Sets the transparency for newly created objects"},circle:{description:"Creates one circle by center and radius"},clayer:{description:"Sets the current layer for new objects and editing operations"},cmleaderstyle:{description:"Sets the name of the current multileader style"},cmlscale:{description:"Controls the overall width of a multiline"},cmlstyle:{description:"Sets the name of the current multiline style"},colortheme:{description:"Controls the color theme of the user interface (dark or light)"},copy:{description:"Copies selected entities by cloning them to new positions",prompt:"Select entities"},csvg:{description:"Converts current drawing to SVG"},chtml:{description:"Exports current drawing to a standalone offline HTML file"},dimlinear:{description:"Creates linear dimensions"},dynmode:{description:"Controls Dynamic Input settings at the cursor"},dynprompt:{description:"Controls display of prompts in Dynamic Input tooltips"},ellipse:{description:"Creates an ellipse or elliptical arc by axis endpoints or center"},erase:{description:"Deletes selected entities from the drawing",prompt:"Select entities"},hatch:{description:"Fills an enclosed area or selected objects with a hatch pattern"},hpang:{description:"Sets the default angle, in radians, for newly created hatch patterns"},hpassoc:{description:"Controls whether newly created hatches are associative"},hpbackgroundcolor:{description:"Sets the default background color for newly created hatch patterns"},hpcolor:{description:"Sets the default color for newly created hatches"},hpdouble:{description:"Controls whether user-defined hatch patterns are doubled"},hpislanddetection:{description:"Controls how islands within newly created hatch boundaries are treated"},hplayer:{description:"Sets the default layer for newly created hatches and fills"},hpname:{description:"Sets the default pattern name for newly created hatches in this session"},hpscale:{description:"Sets the default scale factor for newly created hatch patterns"},hpseparate:{description:"Controls whether one or separate hatch objects are created for multiple boundaries"},hptransparency:{description:"Sets the default transparency for newly created hatches and fills"},insunits:{description:"Specifies drawing units for automatic scaling of inserted blocks, images, or xrefs"},laycur:{description:"Changes the layer property of selected objects to the current layer",prompt:"Select objects to be changed to the current layer"},laydel:{description:"Deletes a layer and all objects on that layer"},layerclose:{description:"Closes the Layer Properties Manager"},layerp:{description:"Undoes the last change or set of changes made to layer settings"},layfrz:{description:"Freezes the layer of selected objects",prompt:"Select object on layer to freeze"},layiso:{description:"Isolates the layers of selected objects",prompt:"Select objects on layers to isolate"},laylck:{description:"Locks the layer of selected objects",prompt:"Select object on layer to lock"},layoff:{description:"Turns off the layer of selected objects",prompt:"Select object on layer to turn off"},layon:{description:"Turns on all layers in the drawing"},laythw:{description:"Thaws all frozen layers in the drawing"},layulk:{description:"Unlocks the layer of selected objects",prompt:"Select object on layer to unlock"},layuniso:{description:"Restores layers hidden or locked by LAYISO"},line:{description:"Draws straight line segments between points"},log:{description:"Logs debug information in console"},lunits:{description:"Sets the display format for coordinates and distances"},luprec:{description:"Sets the display precision for linear units, used together with LUNITS"},lwdisplay:{description:"Controls whether lineweights are displayed in the drawing"},measurearea:{description:"Calculates the area and perimeter of selected objects or points"},measureangle:{description:"Measures the angle between two lines or three points"},measurearc:{description:"Measures the length of an arc segment"},measuredistance:{description:"Measures the distance and delta values between two points"},measurement:{description:"Sets whether the drawing uses English (imperial) or metric units"},measurementcolor:{description:"Sets the color used for measurement overlays"},mline:{description:"Creates multiple parallel lines as one multiline object"},move:{description:"Moves selected entities by a displacement vector",prompt:"Select entities"},offset:{description:"Creates parallel curves, polylines, or circles at a specified distance"},mtext:{description:"Creates one mtext entity"},open:{description:"Opens an existing drawing file"},osmode:{description:"Sets running Object Snap modes using a bitcode value"},pan:{description:"Shifts the view without changing the viewing direction or magnification"},pickbox:{description:"Sets the size (in pixels) of the selection box used to pick objects"},pline:{description:"Creates a polyline by specifying multiple points"},pngout:{description:"Exports to PNG"},point:{description:"Creates points"},polygon:{description:"Creates a regular polygon by center/radius or by one polygon edge"},qnew:{description:"Starts a new drawing"},ray:{description:"Creates a ray that starts at a point and extends to infinity"},rectang:{description:"Creates a rectangle by specifying two opposite corners"},regen:{description:"Redraws the current drawing"},revcloud:{description:"Creates a revision cloud (cloud line) in rectangular shape"},rotate:{description:"Rotates selected entities around a base point",prompt:"Select entities"},select:{description:"Selects entities"},shortcutmenu:{description:"Controls the availability of shortcut menus in the drawing area"},sketch:{description:"Creates a sketch line using polyline that tracks mouse movement"},spline:{description:"Creates a smooth spline curve by specifying control points"},textstyle:{description:"Sets the name of the current text style"},unitmode:{description:"Controls fractional display of coordinates when LUNITS is Architectural or Fractional"},whitebkcolor:{description:"Toggles the drawing area background between white and black"},xline:{description:"Creates a construction line that extends infinitely in both directions"},zoom:{description:"Zooms to display the maximum extents of all entities"}},USER:{}},Ia={arc:{startPointOrCenter:"Specify start point of arc or",secondPointOrOptions:"Specify second point of arc or",secondPoint:"Specify second point of arc:",startPoint:"Specify start point of arc:",centerPoint:"Specify center point of arc:",endPoint:"Specify end point of arc:",endPointOrOptions:"Specify end point of arc or",centerPointOrOptions:"Specify center point of arc",includedAngle:"Specify included angle:",chordLength:"Specify chord length:",tangentDirection:"Specify tangent direction for start point of arc:",radius:"Specify radius of arc:",keywords:{center:{display:"Center(C)",local:"Center",global:"Center"},end:{display:"End(E)",local:"End",global:"End"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},chordLength:{display:"chord Length(L)",local:"Chord Length",global:"ChordLength"},direction:{display:"Direction(D)",local:"Direction",global:"Direction"},radius:{display:"Radius(R)",local:"Radius",global:"Radius"}},invalid:{threePoint:"Invalid 3-point arc: points are collinear or cannot define an arc.",center:"Invalid center input: start and end points must lie on the same circle.",angle:"Invalid angle input: included angle must be greater than 0 and less than 360 degrees.",chordLength:"Invalid chord length: value is out of range for the current radius.",direction:"Invalid direction: cannot construct an arc from this tangent direction.",radius:"Invalid radius: the specified radius cannot connect start and end points."}},circle:{center:"Specify the center of circle:",centerOrOptions:"Specify center point of circle or",radius:"Specify the radius of circle:",radiusOrDiameter:"Specify radius of circle or",diameter:"Specify diameter of circle:",twoPointFirst:"Specify first endpoint of circle diameter:",twoPointSecond:"Specify second endpoint of circle diameter:",threePointFirst:"Specify first point on circle:",threePointSecond:"Specify second point on circle:",threePointThird:"Specify third point on circle:",keywords:{threeP:{display:"3P(3P)",local:"3P",global:"3P"},twoP:{display:"2P(2P)",local:"2P",global:"2P"},diameter:{display:"Diameter(D)",local:"Diameter",global:"Diameter"}}},copy:{basePointOrOptions:"Specify base point or",displacementOrArray:"Specify displacement or",secondPointOrArray:"Specify second point or",modePrompt:"Enter copy mode option",arrayItemCount:"Enter the number of items in the array including the original:",arraySecondPointOrFit:"Specify second point or",arrayFitSecondPoint:"Specify second point:",keywords:{displacement:{display:"Displacement(D)",local:"Displacement",global:"Displacement"},mode:{display:"Mode(O)",local:"Mode",global:"Mode"},multiple:{display:"Multiple(M)",local:"Multiple",global:"Multiple"},single:{display:"Single(S)",local:"Single",global:"Single"},array:{display:"Array(A)",local:"Array",global:"Array"},fit:{display:"Fit(F)",local:"Fit",global:"Fit"}}},dimlinear:{xLine1Point:"Specify the first extension line origin:",xLine2Point:"Specify the second extension line origin:",dimLinePoint:"Specify dimension line location:"},ellipse:{axisEndpointOrOptions:"Specify axis endpoint of ellipse or",arcAxisEndpointOrCenter:"Specify axis endpoint of elliptical arc or",center:"Specify center of ellipse:",firstAxisEndpoint:"Specify endpoint of axis:",secondAxisEndpoint:"Specify other endpoint of axis:",otherAxisOrRotation:"Specify distance to other axis or",rotationAngle:"Specify rotation angle around major axis:",arcStartAngle:"Specify start angle of elliptical arc:",arcEndAngle:"Specify end angle of elliptical arc:",keywords:{arc:{display:"Arc(A)",local:"Arc",global:"Arc"},center:{display:"Center(C)",local:"Center",global:"Center"},rotation:{display:"Rotation(R)",local:"Rotation",global:"Rotation"}},invalid:{axis:"Invalid axis input: axis length must be greater than 0.",otherAxis:"Invalid other-axis input: distance must be greater than 0.",rotation:"Invalid rotation input: resulting minor axis must be greater than 0."}},hatch:{prompt:"Select boundary object or",pickPoint:"Specify internal point (or press Enter to finish):",select:"Select objects to hatch:",patternName:"Enter hatch pattern name:",scale:"Specify hatch pattern scale:",angle:"Specify hatch pattern angle:",style:"Enter hatch style",associative:"Specify associativity",invalidBoundary:"Selected objects do not form a closed boundary.",keywords:{pick:{display:"Pick points(P)",local:"Pick points",global:"PickPoints"},select:{display:"Select objects(S)",local:"Select objects",global:"SelectObjects"},cancel:{display:"Cancel(C)",local:"Cancel",global:"Cancel"},pattern:{display:"Pattern(P)",local:"Pattern",global:"Pattern"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},style:{display:"Style(T)",local:"Style",global:"HatchStyle"},associative:{display:"Associative(AS)",local:"Associative",global:"AssociativeMode"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},outer:{display:"Outer(O)",local:"Outer",global:"Outer"},ignore:{display:"Ignore(I)",local:"Ignore",global:"Ignore"},yes:{display:"Yes(Y)",local:"Yes",global:"Yes"},no:{display:"No(N)",local:"No",global:"No"}}},layer:{main:"Enter option",listSummary:"Layer list was printed to browser console",emptyInput:"No layer name was entered.",newPrompt:"Enter name for new layer(s):",makePrompt:"Enter name of layer to make current:",setPrompt:"Enter name of layer to set current:",onPrompt:"Enter layer name(s) to turn on:",offPrompt:"Enter layer name(s) to turn off:",freezePrompt:"Enter layer name(s) to freeze:",thawPrompt:"Enter layer name(s) to thaw:",lockPrompt:"Enter layer name(s) to lock:",unlockPrompt:"Enter layer name(s) to unlock:",colorLayerPrompt:"Enter layer name(s) to change color:",colorValuePrompt:"Enter color (ACI 1-255, RGB like 255,0,0, or CSS color name):",invalidColor:"Invalid color input.",descriptionLayerPrompt:"Enter layer name to edit description:",descriptionValuePrompt:"Enter new layer description:",created:"Created layer count",alreadyExists:"Layer already exists",notFound:"Layer not found",cannotChangeCurrent:"Cannot turn off or freeze the current layer.",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"Make(M)",local:"Make",global:"Make"},set:{display:"Set(S)",local:"Set",global:"Set"},new:{display:"New(N)",local:"New",global:"New"},on:{display:"On(ON)",local:"On",global:"On"},off:{display:"Off(OF)",local:"Off",global:"Off"},color:{display:"Color(C)",local:"Color",global:"Color"},freeze:{display:"Freeze(F)",local:"Freeze",global:"Freeze"},thaw:{display:"Thaw(T)",local:"Thaw",global:"Thaw"},lock:{display:"Lock(L)",local:"Lock",global:"Lock"},unlock:{display:"Unlock(U)",local:"Unlock",global:"Unlock"},description:{display:"Description(D)",local:"Description",global:"Description"}}},layon:{alreadyOn:"All layers are already on.",turnedOn:"Turned on layers"},laycur:{prompt:"Select objects to be changed to the current layer",currentLayerNotFound:"Current layer not found.",noObjects:"No valid objects were selected.",alreadyCurrent:"Selected objects are already on the current layer.",changed:"Changed objects to current layer"},layfrz:{prompt:"Select object on layer to freeze or",invalidSelection:"Invalid object selected.",settingsPrompt:"Enter LAYFRZ setting to change",viewportPrompt:"Specify viewport freeze behavior",blockSelectionPrompt:"Specify nested block selection behavior",vpfreezeFallback:"Current viewer does not support per-viewport layer freeze; using Freeze behavior instead.",nestedSelectionLimited:"Nested block selection settings are stored, but current picking still resolves the top-level entity layer.",layerNotFound:"Layer not found",cannotFreezeCurrent:"Cannot freeze the current layer.",alreadyFrozen:"Layer is already frozen",frozen:"Frozen layer",restored:"Restored layer",nothingToUndo:"There is no LAYFRZ action to undo.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},viewports:{display:"Viewports(V)",local:"Viewports",global:"Viewports"},blockSelection:{display:"Block selection(B)",local:"Block selection",global:"BlockSelection"},freeze:{display:"Freeze(F)",local:"Freeze",global:"Freeze"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"},block:{display:"Block(B)",local:"Block",global:"Block"},entity:{display:"Entity(E)",local:"Entity",global:"Entity"},none:{display:"None(N)",local:"None",global:"None"}}},layiso:{prompt:"Select objects on the layer(s) to be isolated or",settingsPrompt:"Enter setting for layers not isolated",offModePrompt:"Enter off behavior for layers not isolated",noLayers:"No valid layers were selected.",layerNotFound:"Layer not found",isolated:"Isolated layer(s)",affectedLayers:"affected layers",vpfreezeFallback:"Current viewer does not support per-viewport layer freeze; using Off behavior instead.",lockFadeFallback:"Current viewer does not support layer fade display; non-isolated layers will be locked without fade.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},off:{display:"Off(O)",local:"Off",global:"Off"},lockAndFade:{display:"Lock and fade(L)",local:"Lock and fade",global:"LockAndFade"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"}}},layuniso:{noPrevious:"No previous LAYISO layer state to restore.",layerNotFound:"Layer not found",nothingRestored:"No LAYISO layer changes were restored.",restored:"Restored layers"},laythw:{alreadyThawed:"All layers are already thawed.",thawed:"Thawed layers"},laylck:{prompt:"Select an object on the layer to be locked",invalidSelection:"Invalid object selected.",layerNotFound:"Layer not found",alreadyLocked:"Layer is already locked",locked:"Locked layer"},layulk:{prompt:"Select an object on the layer to be unlocked",invalidSelection:"Invalid object selected.",layerNotFound:"Layer not found",alreadyUnlocked:"Layer is already unlocked",unlocked:"Unlocked layer"},layoff:{prompt:"Select object on layer to turn off or",invalidSelection:"Invalid object selected.",settingsPrompt:"Enter LAYOFF setting to change",viewportPrompt:"Specify viewport behavior",blockSelectionPrompt:"Specify nested block selection behavior",vpfreezeFallback:"Current viewer does not support per-viewport layer off; using Off behavior instead.",nestedSelectionLimited:"Nested block selection settings are stored, but current picking still resolves the top-level entity layer.",layerNotFound:"Layer not found",cannotTurnOffCurrent:"Cannot turn off the current layer.",alreadyOff:"Layer is already off",turnedOff:"Turned off layer",restored:"Restored layer",nothingToUndo:"There is no LAYOFF action to undo.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},viewports:{display:"Viewports(V)",local:"Viewports",global:"Viewports"},blockSelection:{display:"Block selection(B)",local:"Block selection",global:"BlockSelection"},off:{display:"Off(O)",local:"Off",global:"Off"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"},block:{display:"Block(B)",local:"Block",global:"Block"},entity:{display:"Entity(E)",local:"Entity",global:"Entity"},none:{display:"None(N)",local:"None",global:"None"}}},layerp:{restored:"Restored previous layer state.",noPreviousState:"There is no previous layer state to restore."},line:{firstPoint:"Specify the first point:",firstPointOrContinue:"Specify first point or",nextPoint:"Specify the next point:",nextPointWithOptions:"Specify next point or",keywords:{continue:{display:"Continue(C)",local:"Continue",global:"Continue"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"}}},xline:{firstPointOrOptions:"Specify a point or",secondPoint:"Specify second point:",throughPoint:"Specify through point:",angle:"Enter angle of xline:",invalidDirection:"Invalid direction for XLINE.",keywords:{hor:{display:"Hor(H)",local:"Hor",global:"Hor"},ver:{display:"Ver(V)",local:"Ver",global:"Ver"},ang:{display:"Ang(A)",local:"Ang",global:"Ang"}}},ray:{startPoint:"Specify start point:",throughPoint:"Specify through point:"},mline:{startPointWithOptions:"Specify start point or",nextPointWithOptions:"Specify next point or",justificationPrompt:"Enter justification type",scalePrompt:"Specify mline scale:",stylePrompt:"Enter mline style name or [?] for list:",styleNotFound:"Mline style not found",styleListHeader:"Loaded mline styles:",styleListEmpty:"No mline style is loaded in current drawing.",keywords:{justification:{display:"Justification(J)",local:"Justification",global:"Justification"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},style:{display:"Style(ST)",local:"Style",global:"Style"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},top:{display:"Top(T)",local:"Top",global:"Top"},zero:{display:"Zero(Z)",local:"Zero",global:"Zero"},bottom:{display:"Bottom(B)",local:"Bottom",global:"Bottom"}}},measureAngle:{vertex:"Specify vertex point:",arm1:"Specify point on first arm:",arm2:"Specify point on second arm:"},measureArc:{startPoint:"Specify arc start point:",throughPoint:"Specify a point on the arc:",endPoint:"Specify arc end point:"},measureArea:{firstPoint:"Specify first point:",nextPoint:"Specify next point (or press Enter to finish):"},measureDistance:{firstPoint:"Specify first point:",secondPoint:"Specify second point:"},move:{basePointOrDisplacement:"Specify base point or",secondPointOrDisplacement:"Specify second point or",displacement:"Specify displacement:",keywords:{displacement:{display:"Displacement(D)",local:"Displacement",global:"Displacement"}}},offset:{distance:"Specify offset distance:",selectObject:"Select object to offset or press Enter to finish:",sidePoint:"Specify point on side to offset:",invalidDistance:"Offset distance must be greater than 0.",invalidSelection:"Selected object cannot be offset.",offsetFailed:"Unable to create an offset curve for the specified side."},mtext:{point:"Specify mtext insertion point:"},pngout:{boundsFirstCorner:"Specify first corner of bounds",boundsSecondCorner:"Specify opposite corner",longSidePrompt:"Enter long side size in pixels"},point:{point:"Specify a point"},polygon:{numberOfSides:"Enter number of sides:",centerOrEdge:"Specify center of polygon or",radiusOrType:"Enter options",edgeStart:"Specify first endpoint of edge:",edgeEnd:"Specify second endpoint of edge:",keywords:{edge:{display:"Edge(E)",local:"Edge",global:"Edge"},inscribed:{display:"Inscribed in circle(I)",local:"Inscribed in circle",global:"Inscribed"},circumscribed:{display:"Circumscribed about circle(C)",local:"Circumscribed about circle",global:"Circumscribed"}},invalid:{sides:"Invalid number of sides. Enter an integer between 3 and 1024.",radius:"Invalid radius. Radius must be greater than 0.",edge:"Invalid edge. The edge length must be greater than 0."}},polyline:{firstPoint:"Specify the first point:",nextPoint:"Specify the next point (or press Enter to finish):",nextPointWithOptions:"Specify next point or",nextPointWithArcOptions:"Specify next point or",keywords:{arc:{display:"Arc(A)",local:"Arc",global:"Arc"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},line:{display:"Line(L)",local:"Line",global:"Line"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},center:{display:"Center(C)",local:"Center",global:"Center"},secondPoint:{display:"Second point(P)",local:"Second point",global:"SecondPoint"},radius:{display:"Radius(R)",local:"Radius",global:"Radius"}},arcAngle:"Specify arc angle:",arcCenter:"Specify center point:",arcSecondPoint:"Specify second point on arc:",arcEndPoint:"Specify arc end point:",arcRadius:"Specify arc radius:"},rect:{firstPoint:"Specify first corner point:",nextPoint:"Specify other corner point:",firstPointWithOptions:"Specify first corner point or",otherCornerWithOptions:"Specify other corner point or",chamferFirst:"Specify first chamfer distance:",chamferSecond:"Specify second chamfer distance:",filletRadius:"Specify fillet radius:",segmentWidth:"Specify rectangle line width:",elevationValue:"Specify elevation:",thicknessValue:"Specify thickness:",rotationAngle:"Specify rectangle rotation angle:",dimensionLength:"Specify rectangle length:",dimensionWidth:"Specify rectangle width:",areaValue:"Specify rectangle area:",areaLengthOrWidth:"Specify rectangle length",areaSpecifyWidth:"Specify rectangle width:",invalidPositive:"Invalid input. Please enter a value greater than 0.",invalidRect:"Unable to create rectangle. Please specify valid corners or dimensions.",thicknessNotSupported:"Rectangle thickness is currently not written to entity data. The thickness setting is ignored.",keywords:{chamfer:{display:"Chamfer(C)",local:"Chamfer",global:"Chamfer"},elevation:{display:"Elevation(E)",local:"Elevation",global:"Elevation"},fillet:{display:"Fillet(F)",local:"Fillet",global:"Fillet"},thickness:{display:"Thickness(T)",local:"Thickness",global:"Thickness"},width:{display:"Width(W)",local:"Width",global:"Width"},area:{display:"Area(A)",local:"Area",global:"Area"},dimensions:{display:"Dimensions(D)",local:"Dimensions",global:"Dimensions"},rotation:{display:"Rotation(R)",local:"Rotation",global:"Rotation"},length:{display:"Length(L)",local:"Length",global:"Length"},rectWidth:{display:"Width(W)",local:"Width",global:"Width"}}},rotate:{basePoint:"Specify base point:",rotationAngleOrOptions:"Specify rotation angle or",referenceAngleOrPoints:"Specify reference angle or",firstReferencePoint:"Specify first point of reference angle:",secondReferencePoint:"Specify second point:",newAngle:"Specify new angle:",keywords:{copy:{display:"Copy(C)",local:"Copy",global:"Copy"},reference:{display:"Reference(R)",local:"Reference",global:"Reference"},points:{display:"Points(P)",local:"Points",global:"Points"}},invalid:{referencePoints:"Invalid reference points: points must be different."}},sketch:{firstPoint:"Specify the first point:",nextPoint:"Specify the end point:"},spline:{firstPoint:"Specify the first point:",nextPoint:"Specify the next point (or press Enter to finish):",firstPointWithOptions:"Specify first point or",nextPointWithFitOptions:"Specify next point or",nextPointWithCvOptions:"Specify next control vertex or",methodPrompt:"Enter spline creation method",knotsPrompt:"Enter knot parameterization",degreePrompt:"Specify spline degree:",keywords:{method:{display:"Method(M)",local:"Method",global:"Method"},fit:{display:"Fit(F)",local:"Fit",global:"Fit"},cv:{display:"CV(C)",local:"CV",global:"CV"},knots:{display:"Knots(K)",local:"Knots",global:"Knots"},degree:{display:"Degree(D)",local:"Degree",global:"Degree"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},chord:{display:"Chord(C)",local:"Chord",global:"Chord"},sqrtChord:{display:"Sqrt chord(S)",local:"Sqrt chord",global:"SqrtChord"},uniform:{display:"Uniform(U)",local:"Uniform",global:"Uniform"}}},sysvar:{prompt:"Please input new value:"},zoom:{mainPrompt:"Specify corner of window or",firstCorner:"Specify first corner:",secondCorner:"Specify opposite corner:",centerPoint:"Specify center point:",heightOrScale:"Enter height or scale factor (nX or nXP):",scaleFactor:"Enter scale factor (nX or nXP):",keywords:{all:{display:"All(A)",local:"All",global:"All"},center:{display:"Center(C)",local:"Center",global:"Center"},extents:{display:"Extents(E)",local:"Extents",global:"Extents"},previous:{display:"Previous(P)",local:"Previous",global:"Previous"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},window:{display:"Window(W)",local:"Window",global:"Window"}}}},Ea={commandLine:{noLast:"(no last command)",unknownCommand:"Unknown command",executed:"Executed command",showHistory:"Show command history",placeholder:"Type command",showMessages:"Show message history",canceled:"*Canceled*",noHistory:"(no history)",close:"Close command line"},inputManager:{firstCorner:"Specify the first corner or",secondCorner:"Specify the second corner or"},message:{fetchingDrawingFile:"Fetching file ..."},progress:{start:"Start parsing file ...",parse:"Parsing file ...",font:"Downloading fonts needed by this drawing ...",ltype:"Parsing line types ...",style:"Parsing text syltes ...",dimstyle:"Parsing dimension styles ...",layer:"Parsing layers ...",vport:"Parsing viewports ...",blockrecord:"Parsing block record ...",header:"Parsing header ...",block:"Parsing blocks ...",entity:"Parsing entities ...",object:"Parsing named dictionaries ...",end:"Finished!"}},ka={ACAD:{"-hatch":{description:"通过命令行选项创建填充,不显示 Ribbon 界面"},"-layer":{description:"通过命令行选项管理图层"},angbase:{description:"设置当前 UCS 中 0 度的基准角方向"},angdir:{description:"设置正角度的方向为顺时针或逆时针"},arc:{description:"创建圆弧"},aunits:{description:"设置角度显示格式"},auprec:{description:"设置角度显示精度(小数位数),与 AUNITS 配合使用"},cdxf:{description:"导出当前图纸为DXF格式"},cecolor:{description:"设置新创建对象的当前默认颜色"},celtscale:{description:"控制新创建对象的线型比例系数"},celtype:{description:"设置新创建对象的线型"},celweight:{description:"设置新创建对象的默认线宽"},cetranparency:{description:"设置新创建对象的透明度"},circle:{description:"使用圆心和半径创建圆"},clayer:{description:"设置新建对象和编辑操作所使用的当前图层"},cmleaderstyle:{description:"设置当前多重引线样式名称"},cmlscale:{description:"控制多线的整体宽度"},cmlstyle:{description:"设置当前多线样式名称"},colortheme:{description:"控制用户界面的颜色主题(深色或浅色)"},copy:{description:"通过克隆将所选图元复制到新位置",prompt:"选择对象"},csvg:{description:"转换当前图纸为SVG格式"},chtml:{description:"将当前图纸导出为可离线打开的 HTML 文件"},dimlinear:{description:"创建线性尺寸标注"},dynmode:{description:"控制光标处的动态输入设置"},dynprompt:{description:"控制动态输入工具提示中提示的显示"},ellipse:{description:"通过轴端点或中心点创建椭圆或椭圆弧"},erase:{description:"从图纸中删除所选对象",prompt:"选择对象"},hatch:{description:"用填充图案填充封闭区域或所选对象"},hpang:{description:"设置新创建填充图案的默认角度(弧度)"},hpassoc:{description:"控制新创建的填充是否具有关联性"},hpbackgroundcolor:{description:"设置新创建填充图案的默认背景颜色"},hpcolor:{description:"设置新创建填充的默认颜色"},hpdouble:{description:"控制用户定义的填充图案是否加倍"},hpislanddetection:{description:"控制新创建填充边界内孤岛的处理方式"},hplayer:{description:"设置新创建填充和填充区域的默认图层"},hpname:{description:"设置当前会话中新创建填充的默认图案名称"},hpscale:{description:"设置新创建填充图案的默认比例系数"},hpseparate:{description:"控制为多个边界创建单个还是独立的填充对象"},hptransparency:{description:"设置新创建填充和填充区域的默认透明度"},insunits:{description:"指定插入块、图像或外部参照时用于自动缩放的图形单位"},laycur:{description:"将所选对象的图层属性更改为当前图层",prompt:"选择要更改到当前图层的对象"},laydel:{description:"删除图层及该图层上的所有对象"},layerclose:{description:"关闭图层属性管理器"},layerp:{description:"撤销对图层设置的最后一次更改或一组更改"},layfrz:{description:"冻结所选对象所在的图层",prompt:"选择要冻结其图层的对象"},layiso:{description:"隔离所选对象所在的图层",prompt:"选择要隔离其图层的对象"},laylck:{description:"锁定所选对象所在的图层",prompt:"选择要锁定其图层的对象"},layoff:{description:"关闭所选对象所在的图层",prompt:"选择要关闭其图层的对象"},layon:{description:"打开图纸中的所有图层"},laythw:{description:"解冻图纸中的所有冻结图层"},layulk:{description:"解锁所选对象所在的图层",prompt:"选择要解锁其图层的对象"},layuniso:{description:"恢复由 LAYISO 隐藏或锁定的图层"},line:{description:"在指定点之间绘制直线段"},log:{description:"在控制台输出调试信息"},lunits:{description:"设置坐标和距离的显示格式"},luprec:{description:"设置线性单位的显示精度(小数位数),与 LUNITS 配合使用"},lwdisplay:{description:"用于控制是否在图纸中显示线宽效果"},measurearea:{description:"计算所选对象或点定义区域的面积和周长"},measureangle:{description:"测量两条线或三个点之间的夹角"},measurearc:{description:"测量圆弧段的弧长"},measuredistance:{description:"测量两点之间的距离及坐标增量"},measurement:{description:"设置图形使用英制或公制单位"},measurementcolor:{description:"设置测量标注覆盖图形使用的颜色"},mline:{description:"创建由多条平行线组成的多线对象"},move:{description:"通过位移向量移动所选图元",prompt:"选择对象"},offset:{description:"按指定距离创建平行曲线、多段线或圆"},mtext:{description:"创建多行文本"},open:{description:"打开图纸"},osmode:{description:"使用位码设置运行中的对象捕捉模式"},pan:{description:"平移视图"},pickbox:{description:"控制用于选择对象的拾取框大小(像素)"},pline:{description:"通过指定多个点创建多段线"},pngout:{description:"导出为 PNG 图片"},point:{description:"连续创建点"},polygon:{description:"通过中心和半径或指定一条边创建正多边形"},qnew:{description:"创建新图纸"},ray:{description:"创建从起点向单一方向无限延伸的射线"},rectang:{description:"通过指定两个对角点创建矩形"},regen:{description:"重绘图纸"},revcloud:{description:"创建矩形修订云线"},rotate:{description:"绕基点旋转所选图元",prompt:"选择对象"},select:{description:"选择图元"},shortcutmenu:{description:"控制图形区域中快捷菜单的可用性"},sketch:{description:"使用多段线创建手绘线,跟踪鼠标移动"},spline:{description:"通过指定控制点创建平滑的样条曲线"},textstyle:{description:"设置当前文字样式的名称"},unitmode:{description:"当 LUNITS 为建筑或分数格式时,控制坐标的分数显示格式"},whitebkcolor:{description:"切换绘图区域背景颜色,在白色和黑色背景之间切换"},xline:{description:"创建在两个方向上无限延伸的构造线"},zoom:{description:"缩放以显示所有对象"}},USER:{}},Ba={arc:{startPointOrCenter:"指定圆弧的起点或",secondPointOrOptions:"指定圆弧上的第二点或",secondPoint:"指定圆弧上的第二点:",startPoint:"指定圆弧的起点:",centerPoint:"指定圆弧的圆心:",endPoint:"指定圆弧的端点:",endPointOrOptions:"指定圆弧的端点或",centerPointOrOptions:"指定圆弧的圆心或",includedAngle:"指定圆弧的夹角:",chordLength:"指定圆弧的弦长:",tangentDirection:"指定圆弧起点的切线方向:",radius:"指定圆弧的半径:",keywords:{center:{display:"圆心(C)",local:"圆心",global:"Center"},end:{display:"端点(E)",local:"端点",global:"End"},angle:{display:"角度(A)",local:"角度",global:"Angle"},chordLength:{display:"弦长(L)",local:"弦长",global:"ChordLength"},direction:{display:"方向(D)",local:"方向",global:"Direction"},radius:{display:"半径(R)",local:"半径",global:"Radius"}},invalid:{threePoint:"三点圆弧无效:三点共线或无法确定圆弧。",center:"圆心输入无效:起点与终点必须在同一圆上。",angle:"角度输入无效:夹角必须大于 0 且小于 360 度。",chordLength:"弦长输入无效:该值超出当前半径可用范围。",direction:"方向输入无效:无法根据该切线方向构造圆弧。",radius:"半径输入无效:指定半径无法连接起点与终点。"}},circle:{center:"指定圆的圆心:",centerOrOptions:"指定圆的圆心或",radius:"指定圆的半径:",radiusOrDiameter:"指定圆的半径或",diameter:"指定圆的直径:",twoPointFirst:"指定圆直径的第一个端点:",twoPointSecond:"指定圆直径的第二个端点:",threePointFirst:"指定圆上的第一个点:",threePointSecond:"指定圆上的第二个点:",threePointThird:"指定圆上的第三个点:",keywords:{threeP:{display:"三点(3P)",local:"三点",global:"3P"},twoP:{display:"两点(2P)",local:"两点",global:"2P"},diameter:{display:"直径(D)",local:"直径",global:"Diameter"}}},copy:{basePointOrOptions:"指定基点或",displacementOrArray:"指定位移或",secondPointOrArray:"指定第二个点或",modePrompt:"输入复制模式选项",arrayItemCount:"输入阵列中的项目数(包括原对象):",arraySecondPointOrFit:"指定第二个点或",arrayFitSecondPoint:"指定第二个点:",keywords:{displacement:{display:"位移(D)",local:"位移",global:"Displacement"},mode:{display:"模式(O)",local:"模式",global:"Mode"},multiple:{display:"多个(M)",local:"多个",global:"Multiple"},single:{display:"单个(S)",local:"单个",global:"Single"},array:{display:"阵列(A)",local:"阵列",global:"Array"},fit:{display:"布满(F)",local:"布满",global:"Fit"}}},dimlinear:{xLine1Point:"指定第一条尺寸界限原点:",xLine2Point:"指定第二条尺寸界限原点:",dimLinePoint:"指定尺寸线位置:"},ellipse:{axisEndpointOrOptions:"指定椭圆的轴端点或",arcAxisEndpointOrCenter:"指定椭圆弧的轴端点或",center:"指定椭圆中心点:",firstAxisEndpoint:"指定轴的端点:",secondAxisEndpoint:"指定轴的另一个端点:",otherAxisOrRotation:"指定到另一轴的距离或",rotationAngle:"指定绕长轴的旋转角度:",arcStartAngle:"指定椭圆弧起始角:",arcEndAngle:"指定椭圆弧终止角:",keywords:{arc:{display:"圆弧(A)",local:"圆弧",global:"Arc"},center:{display:"中心点(C)",local:"中心点",global:"Center"},rotation:{display:"旋转(R)",local:"旋转",global:"Rotation"}},invalid:{axis:"轴输入无效:轴长必须大于 0。",otherAxis:"另一轴输入无效:距离必须大于 0。",rotation:"旋转输入无效:计算得到的短轴必须大于 0。"}},hatch:{prompt:"选择边界对象或",pickPoint:"指定内部点(或按 Enter 结束):",select:"选择要填充的对象:",patternName:"输入填充图案名称:",scale:"指定填充图案比例:",angle:"指定填充图案角度:",style:"输入填充样式",associative:"指定关联性",invalidBoundary:"所选对象无法构成闭合边界。",keywords:{pick:{display:"拾取点(P)",local:"拾取点",global:"PickPoints"},select:{display:"选择对象(S)",local:"选择对象",global:"SelectObjects"},cancel:{display:"放弃(C)",local:"放弃",global:"Cancel"},pattern:{display:"图案(P)",local:"图案",global:"Pattern"},scale:{display:"比例(S)",local:"比例",global:"Scale"},angle:{display:"角度(A)",local:"角度",global:"Angle"},style:{display:"样式(T)",local:"样式",global:"HatchStyle"},associative:{display:"关联(AS)",local:"关联",global:"AssociativeMode"},normal:{display:"普通(N)",local:"普通",global:"Normal"},outer:{display:"外部(O)",local:"外部",global:"Outer"},ignore:{display:"忽略(I)",local:"忽略",global:"Ignore"},yes:{display:"是(Y)",local:"是",global:"Yes"},no:{display:"否(N)",local:"否",global:"No"}}},layer:{main:"输入选项",listSummary:"图层列表已输出到浏览器控制台",emptyInput:"未输入图层名。",newPrompt:"输入新建图层名称(可用逗号分隔多个):",makePrompt:"输入要创建并设为当前的图层名:",setPrompt:"输入要设为当前的图层名:",onPrompt:"输入要打开的图层名:",offPrompt:"输入要关闭的图层名:",freezePrompt:"输入要冻结的图层名:",thawPrompt:"输入要解冻的图层名:",lockPrompt:"输入要锁定的图层名:",unlockPrompt:"输入要解锁的图层名:",colorLayerPrompt:"输入要修改颜色的图层名:",colorValuePrompt:"输入颜色(ACI 1-255、RGB 如 255,0,0 或颜色名):",invalidColor:"颜色输入无效。",descriptionLayerPrompt:"输入要修改说明的图层名:",descriptionValuePrompt:"输入新的图层说明:",created:"已创建图层数量",alreadyExists:"图层已存在",notFound:"未找到图层",cannotChangeCurrent:"不能关闭或冻结当前图层。",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"创建并置为当前(M)",local:"创建并置为当前",global:"Make"},set:{display:"置为当前(S)",local:"置为当前",global:"Set"},new:{display:"新建(N)",local:"新建",global:"New"},on:{display:"打开(ON)",local:"打开",global:"On"},off:{display:"关闭(OF)",local:"关闭",global:"Off"},color:{display:"颜色(C)",local:"颜色",global:"Color"},freeze:{display:"冻结(F)",local:"冻结",global:"Freeze"},thaw:{display:"解冻(T)",local:"解冻",global:"Thaw"},lock:{display:"锁定(L)",local:"锁定",global:"Lock"},unlock:{display:"解锁(U)",local:"解锁",global:"Unlock"},description:{display:"说明(D)",local:"说明",global:"Description"}}},layon:{alreadyOn:"所有图层都已经打开。",turnedOn:"已打开图层数量"},laycur:{prompt:"选择要更改到当前图层的对象",currentLayerNotFound:"未找到当前图层。",noObjects:"没有选择有效对象。",alreadyCurrent:"所选对象已位于当前图层。",changed:"已将对象更改到当前图层"},layfrz:{prompt:"选择要冻结其图层的对象或",invalidSelection:"所选对象无效。",settingsPrompt:"输入要修改的 LAYFRZ 设置",viewportPrompt:"指定视口冻结行为",blockSelectionPrompt:"指定嵌套块选择行为",vpfreezeFallback:"当前 viewer 不支持按视口冻结图层,已退化为普通 Freeze 行为。",nestedSelectionLimited:"嵌套块选择设置会被保存,但当前拾取仍只能解析顶层对象所在图层。",layerNotFound:"未找到图层",cannotFreezeCurrent:"不能冻结当前图层。",alreadyFrozen:"图层已处于冻结状态",frozen:"已冻结图层",restored:"已恢复图层",nothingToUndo:"当前没有可撤销的 LAYFRZ 操作。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},viewports:{display:"视口(V)",local:"视口",global:"Viewports"},blockSelection:{display:"块选择(B)",local:"块选择",global:"BlockSelection"},freeze:{display:"冻结(F)",local:"冻结",global:"Freeze"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"},block:{display:"块(B)",local:"块",global:"Block"},entity:{display:"对象(E)",local:"对象",global:"Entity"},none:{display:"无(N)",local:"无",global:"None"}}},layiso:{prompt:"选择要隔离其图层的对象或",settingsPrompt:"输入未隔离图层的处理设置",offModePrompt:"输入未隔离图层的关闭行为",noLayers:"未选择有效图层。",layerNotFound:"未找到图层",isolated:"已隔离图层",affectedLayers:"受影响图层数",vpfreezeFallback:"当前 viewer 不支持按视口冻结图层,已退化为普通 Off 行为。",lockFadeFallback:"当前 viewer 不支持图层淡显显示,未隔离图层将仅被锁定。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},off:{display:"关闭(O)",local:"关闭",global:"Off"},lockAndFade:{display:"锁定并淡显(L)",local:"锁定并淡显",global:"LockAndFade"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"}}},laythw:{alreadyThawed:"所有图层都已经解冻。",thawed:"已解冻图层数量"},layuniso:{noPrevious:"没有可恢复的上一次 LAYISO 图层状态。",layerNotFound:"未找到图层",nothingRestored:"没有恢复任何 LAYISO 图层改动。",restored:"已恢复图层数量"},laylck:{prompt:"选择要锁定其图层的对象",invalidSelection:"所选对象无效。",layerNotFound:"未找到图层",alreadyLocked:"图层已处于锁定状态",locked:"已锁定图层"},layulk:{prompt:"选择要解锁其图层的对象",invalidSelection:"所选对象无效。",layerNotFound:"未找到图层",alreadyUnlocked:"图层已处于解锁状态",unlocked:"已解锁图层"},layoff:{prompt:"选择要关闭其图层的对象或",invalidSelection:"所选对象无效。",settingsPrompt:"输入要修改的 LAYOFF 设置",viewportPrompt:"指定视口行为",blockSelectionPrompt:"指定嵌套块选择行为",vpfreezeFallback:"当前 viewer 不支持按视口关闭图层,已退化为普通 Off 行为。",nestedSelectionLimited:"嵌套块选择设置会被保存,但当前拾取仍只能解析顶层对象所在图层。",layerNotFound:"未找到图层",cannotTurnOffCurrent:"不能关闭当前图层。",alreadyOff:"图层已处于关闭状态",turnedOff:"已关闭图层",restored:"已恢复图层",nothingToUndo:"当前没有可撤销的 LAYOFF 操作。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},viewports:{display:"视口(V)",local:"视口",global:"Viewports"},blockSelection:{display:"块选择(B)",local:"块选择",global:"BlockSelection"},off:{display:"关闭(O)",local:"关闭",global:"Off"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"},block:{display:"块(B)",local:"块",global:"Block"},entity:{display:"对象(E)",local:"对象",global:"Entity"},none:{display:"无(N)",local:"无",global:"None"}}},layerp:{restored:"恢复了之前的图层状态。",noPreviousState:"没有可恢复的先前图层状态。"},line:{firstPoint:"指定第一个点:",firstPointOrContinue:"请指定第一个点或",nextPoint:"指定下一个点:",nextPointWithOptions:"请指定下一个点或",keywords:{continue:{display:"继续(C)",local:"继续",global:"Continue"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"}}},xline:{firstPointOrOptions:"指定点或",secondPoint:"指定第二个点:",throughPoint:"指定穿过点:",angle:"输入构造线角度:",invalidDirection:"XLINE 的方向无效。",keywords:{hor:{display:"水平(H)",local:"水平",global:"Hor"},ver:{display:"垂直(V)",local:"垂直",global:"Ver"},ang:{display:"角度(A)",local:"角度",global:"Ang"}}},ray:{startPoint:"指定起点:",throughPoint:"指定通过点:"},mline:{startPointWithOptions:"指定起点或",nextPointWithOptions:"指定下一点或",justificationPrompt:"输入对正方式",scalePrompt:"指定多线比例:",stylePrompt:"输入多线样式名或 [?] 列出样式:",styleNotFound:"未找到多线样式",styleListHeader:"已加载的多线样式:",styleListEmpty:"当前图纸没有已加载的多线样式。",keywords:{justification:{display:"对正(J)",local:"对正",global:"Justification"},scale:{display:"比例(S)",local:"比例",global:"Scale"},style:{display:"样式(ST)",local:"样式",global:"Style"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},top:{display:"上(T)",local:"上",global:"Top"},zero:{display:"零(Z)",local:"零",global:"Zero"},bottom:{display:"下(B)",local:"下",global:"Bottom"}}},measureArc:{startPoint:"指定弧的起点:",throughPoint:"指定弧上的一个点:",endPoint:"指定弧的终点:"},measureAngle:{vertex:"指定顶点:",arm1:"指定第一条边上的点:",arm2:"指定第二条边上的点:"},measureArea:{firstPoint:"指定第一个点:",nextPoint:"指定下一个点(或按 Enter 完成):"},measureDistance:{firstPoint:"指定第一个点:",secondPoint:"指定第二个点:"},move:{basePointOrDisplacement:"指定基点或",secondPointOrDisplacement:"指定第二个点或",displacement:"指定位移:",keywords:{displacement:{display:"位移(D)",local:"位移",global:"Displacement"}}},offset:{distance:"指定偏移距离:",selectObject:"选择要偏移的对象,或按 Enter 结束:",sidePoint:"指定要偏移到的那一侧的点:",invalidDistance:"偏移距离必须大于 0。",invalidSelection:"所选对象不能偏移。",offsetFailed:"无法在指定侧创建偏移曲线。"},mtext:{point:"指定多行文本插入点:"},pngout:{boundsFirstCorner:"指定边界的第一个角点",boundsSecondCorner:"指定对角点",longSidePrompt:"输入长边像素大小"},point:{point:"指定点"},polygon:{numberOfSides:"输入边数:",centerOrEdge:"指定多边形中心点或",radiusOrType:"输入选项",edgeStart:"指定边的第一个端点:",edgeEnd:"指定边的第二个端点:",keywords:{edge:{display:"边(E)",local:"边",global:"Edge"},inscribed:{display:"内接于圆(I)",local:"内接于圆",global:"Inscribed"},circumscribed:{display:"外切于圆(C)",local:"外切于圆",global:"Circumscribed"}},invalid:{sides:"边数无效:请输入 3 到 1024 之间的整数。",radius:"半径无效:半径必须大于 0。",edge:"边无效:边长必须大于 0。"}},polyline:{firstPoint:"指定第一个点:",nextPoint:"指定下一个点(或按 Enter 完成):",nextPointWithOptions:"请指定下一个点或",nextPointWithArcOptions:"请指定下一个点或",keywords:{arc:{display:"圆弧(A)",local:"圆弧",global:"Arc"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},line:{display:"直线(L)",local:"直线",global:"Line"},angle:{display:"角度(A)",local:"角度",global:"Angle"},center:{display:"圆心(C)",local:"圆心",global:"Center"},secondPoint:{display:"第二点(P)",local:"第二点",global:"SecondPoint"},radius:{display:"半径(R)",local:"半径",global:"Radius"}},arcAngle:"指定弧角度:",arcCenter:"指定圆心:",arcSecondPoint:"指定弧上的第二点:",arcEndPoint:"指定弧的终点:",arcRadius:"指定弧半径:"},rotate:{basePoint:"指定基点:",rotationAngleOrOptions:"指定旋转角度或",referenceAngleOrPoints:"指定参考角或",firstReferencePoint:"指定参考角的第一点:",secondReferencePoint:"指定第二点:",newAngle:"指定新角度:",keywords:{copy:{display:"复制(C)",local:"复制",global:"Copy"},reference:{display:"参照(R)",local:"参照",global:"Reference"},points:{display:"点(P)",local:"点",global:"Points"}},invalid:{referencePoints:"参考点输入无效:两点必须不同。"}},rect:{firstPoint:"指定第一个角点:",nextPoint:"指定另一个角点:",firstPointWithOptions:"指定第一个角点或者",otherCornerWithOptions:"指定另一个角点或者",chamferFirst:"指定第一个倒角距离:",chamferSecond:"指定第二个倒角距离:",filletRadius:"指定圆角半径:",segmentWidth:"指定矩形线宽:",elevationValue:"指定标高:",thicknessValue:"指定厚度:",rotationAngle:"指定矩形旋转角度:",dimensionLength:"指定矩形长度:",dimensionWidth:"指定矩形宽度:",areaValue:"指定矩形面积:",areaLengthOrWidth:"指定矩形长度",areaSpecifyWidth:"指定矩形宽度:",invalidPositive:"输入无效:请输入大于 0 的数值。",invalidRect:"无法创建矩形:请输入有效的角点或尺寸。",thicknessNotSupported:"当前版本暂不支持将矩形厚度写入图元,已忽略厚度设置。",keywords:{chamfer:{display:"倒角(C)",local:"倒角",global:"Chamfer"},elevation:{display:"标高(E)",local:"标高",global:"Elevation"},fillet:{display:"圆角(F)",local:"圆角",global:"Fillet"},thickness:{display:"厚度(T)",local:"厚度",global:"Thickness"},width:{display:"宽度(W)",local:"宽度",global:"Width"},area:{display:"面积(A)",local:"面积",global:"Area"},dimensions:{display:"尺寸(D)",local:"尺寸",global:"Dimensions"},rotation:{display:"旋转(R)",local:"旋转",global:"Rotation"},length:{display:"长度(L)",local:"长度",global:"Length"},rectWidth:{display:"宽度(W)",local:"宽度",global:"Width"}}},sketch:{firstPoint:"指定第一个点:",nextPoint:"指定结束点:"},spline:{firstPoint:"指定第一个点:",nextPoint:"指定下一个点(或按 Enter 完成):",firstPointWithOptions:"指定第一个点或",nextPointWithFitOptions:"指定下一个点或",nextPointWithCvOptions:"指定下一个控制顶点或",methodPrompt:"输入样条创建方式",knotsPrompt:"输入节点参数化方式",degreePrompt:"指定样条次数:",keywords:{method:{display:"方法(M)",local:"方法",global:"Method"},fit:{display:"拟合(F)",local:"拟合",global:"Fit"},cv:{display:"控制顶点(C)",local:"控制顶点",global:"CV"},knots:{display:"节点(K)",local:"节点",global:"Knots"},degree:{display:"次数(D)",local:"次数",global:"Degree"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},chord:{display:"弦长(C)",local:"弦长",global:"Chord"},sqrtChord:{display:"平方根弦长(S)",local:"平方根弦长",global:"SqrtChord"},uniform:{display:"均匀(U)",local:"均匀",global:"Uniform"}}},sysvar:{prompt:"请输入新的值:"},zoom:{mainPrompt:"指定窗口角点或",firstCorner:"指定第一个角点:",secondCorner:"指定对角点:",centerPoint:"指定缩放中心点:",heightOrScale:"输入高度或比例因子(nX 或 nXP):",scaleFactor:"输入比例因子(nX 或 nXP):",keywords:{all:{display:"全部(A)",local:"全部",global:"All"},center:{display:"中心(C)",local:"中心",global:"Center"},extents:{display:"范围(E)",local:"范围",global:"Extents"},previous:{display:"上一个(P)",local:"上一个",global:"Previous"},scale:{display:"比例(S)",local:"比例",global:"Scale"},window:{display:"窗口(W)",local:"窗口",global:"Window"}}}},Da={commandLine:{noLast:"(无上一次命令)",unknownCommand:"未知命令",executed:"已执行命令",showHistory:"显示命令历史",placeholder:"输入命令",showMessages:"显示消息历史",canceled:"*已取消*",noHistory:"(无历史记录)",close:"关闭命令行"},inputManager:{firstCorner:"指定第一个角点或",secondCorner:"指定第二个角点或"},message:{fetchingDrawingFile:"正在加载图纸文件..."},progress:{start:"开始解析文件...",parse:"正在解析文件 ...",font:"正在下载图纸所需字体...",ltype:"正在解析线形...",style:"正在解析文字样式...",dimstyle:"正在解析标注样式...",layer:"正在解析图层...",vport:"正在解析视口...",blockrecord:"正在解析BTRs...",header:"正在解析文件头...",block:"正在解析块..",entity:"正在解析图元...",object:"正在解析NODs...",end:"完成!"}};p.mergeLocaleMessage("en",{command:Ta,jig:Ia,main:Ea}),p.mergeLocaleMessage("zh",{command:ka,jig:Ba,main:Da});const an=(a,e)=>{const t=`command.${a}.${e}`;return p.t(t)},Ma=a=>an(le.SYSTEMT_COMMAND_GROUP_NAME,a),Oa=a=>an(le.DEFAUT_COMMAND_GROUP_NAME,a);class ds{constructor(e){this.options=e}parse(e){const t=e.trim();if(t.length===0)return this.options.allowNone,null;const i=this.options.keywords.findByName(t);return i?i.globalName:this.options.allowArbitraryInput?t:null}}class Fa{start(){return new Promise(e=>{this.resolve=e,this.onStart()})}finish(e){this.cleanup(),this.resolve(e)}}class ja extends Fa{constructor(e,t,i=!0){super(),this.cli=e,this.options=t,this.allowTyping=i,this.handler=new ds(t)}onStart(){this.cli.clearInput(),this.cli.setInputReadOnly(!this.allowTyping),this.cli.renderKeywordPrompt(this.options,e=>this.finish(e)),this.cli.focusInput()}handleEnter(e){if(!this.allowTyping)return!0;if(!e.trim()){const i=this.options.keywords.default;return i!=null&&i.enabled?(this.finish(i.globalName),!0):this.options.allowNone?(this.finish(""),!0):!1}const t=this.handler.parse(e);return t!==null?(this.finish(t),!0):!1}handleEscape(){this.finish("")}cleanup(){this.cli.setInputReadOnly(!1),this.cli.clear()}}class ps{constructor(e=document.body){this.isPromptActive=!1,this.recentMessages=[],this.isCommandLifecycleBound=!1,this.container=e,this.history=[],this.historyIndex=-1,this.lastExecuted=null,this.isCmdPopupOpen=!1,this.isMsgPanelOpen=!1,this.minWidth=420,this.widthRatio=.66,this.autoCompleteIndex=-1,this.injectCSS(),this.createUI(),this.bindEvents(),this.bindCommandLifecycleEvents(),this.resizeHandler(),window.addEventListener("resize",()=>this.resizeHandler()),this.resizeObserver=new ResizeObserver(()=>this.resizeHandler()),this.resizeObserver.observe(this.container),p.events.localeChanged.addEventListener(()=>this.refreshLocale())}get visible(){return this.cliContainer.style.display!=="none"}set visible(e){this.cliContainer.style.display=e?"block":"none"}setPrompt(e){this.isPromptActive=!0,this.promptEl.innerHTML=e??"",this.textInput.placeholder="",this.recordRecentMessage(e)}clear(){this.clearPrompt(),this.clearInput()}clearPrompt(){this.promptEl.innerHTML="",this.isPromptActive=!1}clearInput(){this.textInput.value="",this.textInput.placeholder=this.isPromptActive?"":this.localize("main.commandLine.placeholder")}focusInput(){this.textInput.focus()}setInputReadOnly(e){this.textInput.readOnly=e}showMessage(e,t="info",i){this.appendMessage(e,t,i)}cancelActiveSession(){this.activeSession&&(this.activeSession.handleEscape(),this.activeSession=void 0)}async getKeywords(e,t=!0){this.activeSession=new ja(this,e,t);const i=await this.activeSession.start();return this.activeSession=void 0,i}localize(e,t){return p.t(e,{fallback:t})}refreshLocale(){Array.from(this.msgPanel.children).forEach(e=>{var n,s,r,o;const t=e,i=t.dataset.msgKey;if(i)if(i==="main.commandLine.executed"){const c=((s=(n=t.textContent)==null?void 0:n.split(":")[1])==null?void 0:s.trim())??"";t.textContent=`${this.localize(i)}: ${c}`}else if(i==="main.commandLine.unknownCommand"){const c=((o=(r=t.textContent)==null?void 0:r.split(":")[1])==null?void 0:o.trim())??"";t.textContent=`${this.localize(i)}: ${c}`}else t.textContent=this.localize(i)}),this.centerEl.setAttribute("data-placeholder",this.localize("main.commandLine.placeholder")),!this.isPromptActive&&!this.textInput.value&&(this.textInput.placeholder=this.localize("main.commandLine.placeholder")),this.downBtn.title=this.localize("main.commandLine.showHistory"),this.upBtn.title=this.localize("main.commandLine.showMessages")}executeCommand(e){if(!e||!e.trim())if(this.lastExecuted)e=this.lastExecuted;else{this.showMessage(this.localize("main.commandLine.noLast","(no last command)"));return}const t=this.resolveCommand(e);if(!t){const n=this.localize("main.commandLine.unknownCommand");this.showMessage(`${n}: ${e}`,"warning");return}this.history.push(t.globalName),this.historyIndex=this.history.length,this.lastExecuted=t.globalName,this.printHistoryLine(e);const i=this.localize("main.commandLine.executed");this.showMessage(`${i}: ${t.localName}`),S.instance.sendStringToExecute(e),this.clearInput()}injectCSS(){const e=document.createElement("style");e.textContent=`
|
|
10
|
-
.ml-cli-container {
|
|
11
|
-
position: fixed;
|
|
12
|
-
bottom: 10px;
|
|
13
|
-
left: 50%;
|
|
14
|
-
transform: translateX(-50%);
|
|
15
|
-
font-family: "Segoe UI", Arial, sans-serif;
|
|
16
|
-
font-size: 13px;
|
|
17
|
-
box-sizing: border-box;
|
|
18
|
-
user-select: none;
|
|
19
|
-
max-width: calc(100% - 20px);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
.ml-cli-bar {
|
|
23
|
-
display: flex;
|
|
24
|
-
align-items: center;
|
|
25
|
-
gap: 6px;
|
|
26
|
-
border-radius: 6px;
|
|
27
|
-
background: var(--ml-ui-bg, linear-gradient(#ededed, #e0e0e0));
|
|
28
|
-
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.35));
|
|
29
|
-
box-shadow: var(--ml-ui-shadow, 0 2px 6px rgba(0, 0, 0, 0.25));
|
|
30
|
-
min-width: 300px;
|
|
31
|
-
height: 30px;
|
|
32
|
-
max-width: 100%;
|
|
33
|
-
overflow: hidden;
|
|
34
|
-
}
|
|
1
|
+
(function(_,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("@mlightcad/data-model"),require("lodash-es"),require("three"),require("three/examples/jsm/lines/LineSegments2.js"),require("three/examples/jsm/lines/LineSegmentsGeometry.js"),require("@mlightcad/mtext-renderer"),require("three/examples/jsm/renderers/CSS2DRenderer.js"),require("three/examples/jsm/lines/LineMaterial.js"),require("three/examples/jsm/utils/BufferGeometryUtils.js"),require("three/examples/jsm/controls/OrbitControls"),require("three/examples/jsm/lines/Line2.js"),require("three/examples/jsm/lines/LineGeometry.js"),require("three/examples/jsm/libs/stats.module")):typeof define=="function"&&define.amd?define(["exports","@mlightcad/data-model","lodash-es","three","three/examples/jsm/lines/LineSegments2.js","three/examples/jsm/lines/LineSegmentsGeometry.js","@mlightcad/mtext-renderer","three/examples/jsm/renderers/CSS2DRenderer.js","three/examples/jsm/lines/LineMaterial.js","three/examples/jsm/utils/BufferGeometryUtils.js","three/examples/jsm/controls/OrbitControls","three/examples/jsm/lines/Line2.js","three/examples/jsm/lines/LineGeometry.js","three/examples/jsm/libs/stats.module"],u):(_=typeof globalThis<"u"?globalThis:_||self,u(_["cad-simple-viewer"]={},_.dataModel,_.lodashEs,_.h,_.LineSegments2_js,_.LineSegmentsGeometry_js,_.mtextRenderer,_.CSS2DRenderer_js,_.LineMaterial_js,_.BufferGeometryUtils_js,_.OrbitControls,_.Line2_js,_.LineGeometry_js,_.Stats))})(this,function(_,u,Ke,Ga,Ue,De,B,fs,xt,Ka,Ua,$a,Wa,Ha){"use strict";var Bu=Object.defineProperty;var Du=(_,u,Ke)=>u in _?Bu(_,u,{enumerable:!0,configurable:!0,writable:!0,value:Ke}):_[u]=Ke;var I=(_,u,Ke)=>Du(_,typeof u!="symbol"?u+"":u,Ke);function Ya(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const y=Ya(Ga),rn=class rn{constructor(e){this._database=e}getAnnotationLayer(){const e="$revision_",t=u.MLIGHTCAD_APPID,i=this._database.tables.layerTable;for(const c of i.newIterator())if(this.hasAnnotationXData(c))return c.name;let n=1,s=`${e}${n}`;for(;i.has(s);)n++,s=`${e}${n}`;const r=new u.AcDbLayerTableRecord({name:s,isOff:!1,color:new u.AcCmColor(u.AcCmColorMethod.ByACI,1),isPlottable:!0}),a=new u.AcDbResultBuffer([{code:u.AcDbDxfCode.ExtendedDataRegAppName,value:t},{code:u.AcDbDxfCode.ExtendedDataAsciiString,value:t}]);return r.setXData(a),i.add(r),s}filterAnnotationEntities(e){const t=this.getAnnotationLayer();return e.filter(i=>{const n=this._database.tables.blockTable.getEntityById(i);return n&&n.layer==t})}hasAnnotationXData(e){const t=u.MLIGHTCAD_APPID,i=e.getXData(t);if(!i)return!1;for(const n of i)if(n.code===u.AcDbDxfCode.ExtendedDataAsciiString&&n.value===t)return!0;return!1}};rn.DEFAULT_ANNOTATION_COLOR=new u.AcCmColor(u.AcCmColorMethod.ByACI,1),rn.DEFAULT_ANNOTATION_LINE_WEIGHT=u.AcGiLineWeight.LineWeight100;let fe=rn;class ys{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.entityErased.addEventListener(i=>{this.view.removeEntity(i.entity)}),t.database.events.layerAppended.addEventListener(i=>{this._view.addLayer(i.layer)}),t.database.events.layerModified.addEventListener(i=>{this._view.updateLayer(i.layer,i.changes)}),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(i=>{if(i.name==u.AcDbSystemVariables.PDMODE.toLowerCase())this._view.rerenderPoints(i.database.pdmode);else if(i.name==u.AcDbSystemVariables.LWDISPLAY.toLowerCase()){const n=this._view,s=!!i.database.lwdisplay;n.renderer.showLineWeight!==s&&(n.renderer.showLineWeight=s,n.clear(),i.database.regen())}}),t.database.events.dictObjetSet.addEventListener(i=>{i.object instanceof u.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}}var Z;(function(o){o[o.BeforeStart=0]="BeforeStart",o[o.EqualStart=1]="EqualStart",o[o.BetweenStartAndEnd=2]="BetweenStartAndEnd",o[o.EqualEnd=3]="EqualEnd",o[o.AfterEnd=4]="AfterEnd"})(Z||(Z={}));class Xa{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 ws extends Xa{constructor(e=1e-10){super(),this.epsilon=e}pointAboveOrOnLine(e,t,i){const n=t[0],s=t[1],r=i[0],a=i[1],c=e[0],l=e[1];return(r-n)*(l-s)-(a-s)*(c-n)>=-this.epsilon}pointBetween(e,t,i){const n=e[1]-t[1],s=i[0]-t[0],r=e[0]-t[0],a=i[1]-t[1],c=r*s+n*a;if(c<this.epsilon)return!1;const l=s*s+a*a;return!(c-l>-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],a=t[1]-i[1];return Math.abs(n*a-r*s)<this.epsilon}linesIntersect(e,t,i,n){const s=t[0]-e[0],r=t[1]-e[1],a=n[0]-i[0],c=n[1]-i[1],l=s*c-r*a;if(Math.abs(l)<this.epsilon)return null;const h=e[0]-i[0],d=e[1]-i[1],p=(a*d-c*h)/l,m=(s*d-r*h)/l,f=x=>x<=-this.epsilon?Z.BeforeStart:x<this.epsilon?Z.EqualStart:x-1<=-this.epsilon?Z.BetweenStartAndEnd:x-1<this.epsilon?Z.EqualEnd:Z.AfterEnd,w=[e[0]+p*s,e[1]+p*r];return{alongA:f(p),alongB:f(m),p:w}}}class bs{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=(c,l)=>t(l)-t(c);let r=0,a=this.nodes.length;for(;r<a;){const c=r+a>>1;s(this.nodes[c],e)>0?a=c:r=c+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:c=>(this.nodes.splice(r,0,c),c)}}}class tt{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 vs{constructor(e,t,i,n){this.status=null,this.isStart=e,this.p=t,this.seg=i,this.primary=n}}class xs{constructor(e,t,i=null){this.events=new bs,this.status=new bs,this.selfIntersection=e,this.geo=t,this.log=i}compareEvents(e,t,i,n,s,r){const a=this.geo.pointsCompare(t,s);return a!==0?a: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 tt(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 tt(e,t,null,this.log):new tt(t,e,null,this.log)}addSegment(e,t){const i=new vs(!0,e.start,e,t),n=new vs(!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,a=n.end,c=s.start,l=s.end;(i=this.log)===null||i===void 0||i.checkIntersection(n,s);const h=this.geo.linesIntersect(r,a,c,l);if(h===null){if(!this.geo.pointsCollinear(r,a,c)||this.geo.pointsSame(r,l)||this.geo.pointsSame(a,c))return null;const d=this.geo.pointsSame(r,c),p=this.geo.pointsSame(a,l);if(d&&p)return t;const m=!d&&this.geo.pointBetween(r,c,l),f=!p&&this.geo.pointBetween(a,c,l);if(d)return f?this.divideEvent(t,a):this.divideEvent(e,l),t;m&&(p||(f?this.divideEvent(t,a):this.divideEvent(e,l)),this.divideEvent(t,r))}else h.alongA===Z.BetweenStartAndEnd&&(h.alongB===Z.EqualStart?this.divideEvent(e,c):h.alongB===Z.BetweenStartAndEnd?this.divideEvent(e,h.p):h.alongB===Z.EqualEnd&&this.divideEvent(e,l)),h.alongB===Z.BetweenStartAndEnd&&(h.alongA===Z.EqualStart?this.divideEvent(t,r):h.alongA===Z.BetweenStartAndEnd?this.divideEvent(t,h.p):h.alongA===Z.EqualEnd&&this.divideEvent(t,a));return null}calculate(e,t){var i,n,s,r,a,c,l,h;const d=[];for(;!this.events.isEmpty();){const p=this.events.getHead();if((i=this.log)===null||i===void 0||i.vert(p.p[0]),p.isStart){(n=this.log)===null||n===void 0||n.segmentNew(p.seg,p.primary);const m=this.statusFindSurrounding(p),f=m.before,w=m.after;(s=this.log)===null||s===void 0||s.tempStatus(p.seg,f?f.seg:!1,w?w.seg:!1);const b=(()=>{if(f){const v=this.checkIntersection(p,f);if(v)return v}return w?this.checkIntersection(p,w):null})();if(b){if(this.selfIntersection){let v;p.seg.myFill.below===null?v=!0:v=p.seg.myFill.above!==p.seg.myFill.below,v&&(b.seg.myFill.above=!b.seg.myFill.above)}else b.seg.otherFill=p.seg.myFill;(r=this.log)===null||r===void 0||r.segmentUpdate(b.seg),this.events.remove(p.other),this.events.remove(p)}if(this.events.getHead()!==p){(a=this.log)===null||a===void 0||a.rewind(p.seg);continue}if(this.selfIntersection){let v;p.seg.myFill.below===null?v=!0:v=p.seg.myFill.above!==p.seg.myFill.below,w?p.seg.myFill.below=w.seg.myFill.above:p.seg.myFill.below=e,v?p.seg.myFill.above=!p.seg.myFill.below:p.seg.myFill.above=p.seg.myFill.below}else if(p.seg.otherFill===null){let v;if(!w)v=p.primary?t:e;else if(p.primary===w.primary){if(w.seg.otherFill===null)throw new Error("otherFill is null");v=w.seg.otherFill.above}else v=w.seg.myFill.above;p.seg.otherFill={above:v,below:v}}(c=this.log)===null||c===void 0||c.status(p.seg,f?f.seg:!1,w?w.seg:!1),p.other.status=m.insert(p)}else{const m=p.status;if(m===null)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");const f=this.status.getIndex(m);if(f>0&&f<this.status.nodes.length-1){const w=this.status.nodes[f-1],x=this.status.nodes[f+1];this.checkIntersection(w,x)}if((l=this.log)===null||l===void 0||l.statusRemove(m.seg),this.status.remove(m),!p.primary){if(!p.seg.otherFill)throw new Error("otherFill is null");const w=p.seg.myFill;p.seg.myFill=p.seg.otherFill,p.seg.otherFill=w}d.push(p.seg)}this.events.removeHead()}return(h=this.log)===null||h===void 0||h.done(),d}}function St(o,e,t){const i=[];for(const n of o){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 tt(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 At{static union(e,t){return St(e,[0,2,1,0,2,2,0,0,1,0,1,0,0,0,0,0],t)}static intersect(e,t){return St(e,[0,0,0,0,0,2,0,2,0,0,1,1,0,2,1,0],t)}static difference(e,t){return St(e,[0,0,0,0,2,0,2,0,1,1,0,0,0,1,2,0],t)}static differenceRev(e,t){return St(e,[0,2,1,0,0,0,1,1,0,2,0,2,0,0,0,0],t)}static xor(e,t){return St(e,[0,2,1,0,2,0,0,1,1,0,0,2,0,1,2,0],t)}}function qa(o,e,t){const i=[],n=[];for(const s of o){let d=function(b,v,C){return h&&(h.index=b,h.matches_head=v,h.matches_pt1=C),h===c?(h=l,!1):(h=null,!0)},p=function(b){t==null||t.chainReverse(b),i[b].reverse()},m=function(b,v){const C=i[b],P=i[v];let L=C[C.length-1];const M=C[C.length-2],k=P[0],E=P[1];e.pointsCollinear(M,L,k)&&(t==null||t.chainRemoveTail(b,L),C.pop(),L=M),e.pointsCollinear(L,k,E)&&(t==null||t.chainRemoveHead(v,k),P.shift()),t==null||t.chainJoin(b,v),i[b]=C.concat(P),i.splice(v,1)};const r=s.start,a=s.end;if(e.pointsSame(r,a)){console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large");continue}t==null||t.chainStart(s);const c={index:0,matches_head:!1,matches_pt1:!1},l={index:0,matches_head:!1,matches_pt1:!1};let h=c;for(let b=0;b<i.length;b++){const v=i[b],C=v[0],P=v[v.length-1];if(e.pointsSame(C,r)){if(d(b,!0,!0))break}else if(e.pointsSame(C,a)){if(d(b,!0,!1))break}else if(e.pointsSame(P,r)){if(d(b,!1,!0))break}else if(e.pointsSame(P,a)&&d(b,!1,!1))break}if(h===c){i.push([r,a]),t==null||t.chainNew(r,a);continue}if(h===l){t==null||t.chainMatch(c.index);const b=c.index,v=c.matches_pt1?a:r,C=c.matches_head,P=i[b];let L=C?P[0]:P[P.length-1];const M=C?P[1]:P[P.length-2],k=C?P[P.length-1]:P[0],E=C?P[P.length-2]:P[1];if(e.pointsCollinear(M,L,v)&&(C?(t==null||t.chainRemoveHead(c.index,v),P.shift()):(t==null||t.chainRemoveTail(c.index,v),P.pop()),L=M),e.pointsSame(k,v)){i.splice(b,1),e.pointsCollinear(E,k,L)&&(C?(t==null||t.chainRemoveTail(c.index,L),P.pop()):(t==null||t.chainRemoveHead(c.index,L),P.shift())),t==null||t.chainClose(c.index),n.push(P);continue}C?(t==null||t.chainAddHead(c.index,v),P.unshift(v)):(t==null||t.chainAddTail(c.index,v),P.push(v));continue}const f=c.index,w=l.index;t==null||t.chainConnect(f,w);const x=i[f].length<i[w].length;c.matches_head?l.matches_head?x?(p(f),m(f,w)):(p(w),m(w,f)):m(w,f):l.matches_head?m(f,w):x?(p(f),m(w,f)):(p(w),m(f,w))}return n}class Za{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 Ss{constructor(e){this.log=null,this.geo=e}buildLog(e){var t;return this.log=e?new Za:null,(t=this.log)===null||t===void 0?void 0:t.list}segments(e){const t=new xs(!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 xs(!1,this.geo,this.log);for(const n of e.segments)i.addSegment(new tt(n.start,n.end,n,this.log),!0);for(const n of t.segments)i.addSegment(new tt(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:At.union(e.combined,this.log),inverted:e.inverted1||e.inverted2}}selectIntersect(e){return{segments:At.intersect(e.combined,this.log),inverted:e.inverted1&&e.inverted2}}selectDifference(e){return{segments:At.difference(e.combined,this.log),inverted:e.inverted1&&!e.inverted2}}selectDifferenceRev(e){return{segments:At.differenceRev(e.combined,this.log),inverted:!e.inverted1&&e.inverted2}}selectXor(e){return{segments:At.xor(e.combined,this.log),inverted:e.inverted1!==e.inverted2}}polygon(e){return{regions:qa(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 Ss(new ws);const ye=[.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],we=[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],Ja=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(ye),indices:new Uint16Array(we)}],[33,{position:new Float32Array(ye),indices:new Uint16Array(we)}],[34,{position:new Float32Array([...ye,-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([...we,26,27,28,29])}],[35,{position:new Float32Array([...ye,-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([...we,26,27,28,29])}],[36,{position:new Float32Array([...ye,0,0,0,0,.5,0]),indices:new Uint16Array([...we,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([...ye,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0]),indices:new Uint16Array([...we,26,27,27,28,28,29,29,26])}],[97,{position:new Float32Array([...ye,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0]),indices:new Uint16Array([...we,26,27,27,28,28,29,29,30])}],[98,{position:new Float32Array([...ye,-.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([...we,26,27,27,28,28,29,29,30,31,32,33,34])}],[99,{position:new Float32Array([...ye,-.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([...we,26,27,27,28,28,29,29,26,30,31,32,33])}],[100,{position:new Float32Array([...ye,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,0,0,0,0,.5,0]),indices:new Uint16Array([...we,26,27,27,28,28,29,29,30,31,32])}]]);class Me{constructor(){this._symbols=this.initialize()}static get instance(){return Me._instance||(Me._instance=new Me),Me._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)Ct.copy(t),i.point=new y.BufferGeometry().setFromPoints([Ct]);else if(e!=1){const n=this._symbols.get(e);if(n==null)throw new Error(`[AcTrPointSymbolCreator] Invalid point type value: '${e}'!`);Ct.copy(t),As.identity().makeTranslation(Ct),i.line=n.clone().applyMatrix4(As),(e==32||e==64||e==96)&&(i.point=new y.BufferGeometry().setFromPoints([Ct]))}return i}initialize(){const e=new Map;return Ja.forEach((t,i)=>{const n=new y.BufferGeometry;n.setAttribute("position",new y.BufferAttribute(t.position,3)),n.setIndex(new y.BufferAttribute(t.indices,1)),e.set(i,n)}),e}}const As=new y.Matrix4,Ct=new y.Vector3;function Ce(o){return o.userData}function ln(o,e){Object.assign(Ce(o),e)}function Cs(o){return o.isByLayerColor===!0||o.isByLayerLineType===!0||o.isByLayerLineWeight===!0||o.isByLayerTransparency===!0}const ti=new y.Vector3,ii=new y.Vector3;class Pt{static release(e){e.index=null,e.attributes={}}static toNonIndexed(e){if(!e.index)return e;const t=new y.BufferGeometry,i=e.index;for(const n in e.attributes)t.setAttribute(n,Pt.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 a=0;a<i;a++){const c=t.getX(a)*n;for(let l=0;l<n;l++)r[a*n+l]=e.array[c+l]}return new y.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 y.InterleavedBufferAttribute){const n=i.clone();e.attributes[t]=n}})}static createBufferGeometryByPoints(e){const t=new y.BufferGeometry,i=new Float32Array(e.length*3),n=new Uint16Array((e.length-1)*2);return e.forEach((s,r)=>{let a=r*3;i[a]=s.x,i[a+1]=s.y,i[a+2]=s.z,r>0&&(a=(r-1)*2,n[a]=r-1,n[a+1]=r)}),t.setAttribute("position",new y.Float32BufferAttribute(i,3)),t.setIndex(new y.Uint16BufferAttribute(n,1)),t}static computeLineDistance(e){const t=e.isLineSegments===!0;let i=e.geometry;const n=e.matrixWorld;if(i.index&&(i=Pt.toNonIndexed(i)),i.index===null){const s=i.attributes.position;if(!s||s.count===0)return;const r=[];if(t)for(let a=0,c=s.count;a<c;a+=2)ti.fromBufferAttribute(s,a).applyMatrix4(n),ii.fromBufferAttribute(s,a+1).applyMatrix4(n),r[a]=a===0?0:r[a-1],r[a+1]=r[a]+ti.distanceTo(ii);else{r[0]=0;for(let a=1,c=s.count;a<c;a++)ti.fromBufferAttribute(s,a-1).applyMatrix4(n),ii.fromBufferAttribute(s,a).applyMatrix4(n),r[a]=r[a-1],r[a]+=ti.distanceTo(ii)}i.setAttribute("lineDistance",new y.Float32BufferAttribute(r,1)),e.geometry.dispose(),e.geometry=i}}static computeLineDistances(e){e.traverse(t=>{let i=t;i.isLine&&i.material instanceof y.ShaderMaterial&&this.computeLineDistance(i)})}static apply2dTransform(e,t,i=0,n=1){const s=e.attributes.position,r=s.itemSize,a=s.array;if(i!=0){const c=Math.cos(i),l=Math.sin(i);for(let h=0;h<a.length;h+=r){const d=a[h],p=a[h+1],m=d*c-p*l,f=d*l+p*c;a[h]=m*n+t.x,a[h+1]=f*n+t.y}}else for(let c=0;c<a.length;c+=r)a[c]=a[c]*n+t.x,a[c+1]+=a[c+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,a=Math.cos(i.x),c=Math.sin(i.x),l=Math.cos(i.y),h=Math.sin(i.y),d=Math.cos(i.z),p=Math.sin(i.z);for(let m=0;m<r.length;m+=s){let f=r[m],w=r[m+1],x=r[m+2],b=w*a-x*c,v=w*c+x*a;w=b,x=v;let C=f*l+x*h;v=-f*h+x*l,f=C,x=v,C=f*d-w*p,b=f*p+w*d,f=C,w=b,r[m]=f+t.x,r[m+1]=w+t.y,r[m+2]=x+t.z}return n.needsUpdate=!0,e}}class hn{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,a)=>r+a,0);if(s==="object"){let r=0;for(const a in n)Object.prototype.hasOwnProperty.call(n,a)&&(r+=a.length*2,r+=i(n[a]));return r}return 0}return i(e)}static getFileName(e){return e.split("/").pop()}static getFileNameWithoutExtension(e){const t=hn.getFileName(e);if(t){const i=t.lastIndexOf(".");return i===-1?t:t.substring(0,i)}return e}}class un{static toAcCmColor(e){const t=new u.AcCmColor;return e?e.isRgb&&typeof e.rgbValue=="number"?(t.setRGBValue(e.rgbValue),t):(typeof e.aci=="number"&&(e.aci===256?t.setByLayer():e.aci===0?t.setByBlock():t.colorIndex=e.aci),t):t}static toMTextColor(e){const t=new B.MTextColor;if(!e)return t;if(e.isByLayer)return t.aci=256,t;if(e.isByBlock)return t.aci=0,t;if(e.isByACI&&typeof e.colorIndex=="number")return t.aci=e.colorIndex,t;const i=e.RGB;return typeof i=="number"&&(t.rgbValue=i),t}static resolveRgbColor(e){const{color:t,byBlockColor:i,byLayerColor:n}=e;if(t.isRgb&&typeof t.rgbValue=="number")return t.rgbValue;if(t.aci===0)return i;if(t.aci===256||t.aci==null)return n;const s=new u.AcCmColor;s.colorIndex=t.aci;const r=s.RGB;return typeof r=="number"?r:n}}class dn{static createDefaultTraits(){return{color:new u.AcCmColor,rgbColor:16777215,lineType:{type:"ByLayer",name:"Continuous",standardFlag:0,description:"Solid line",totalPatternLength:0},lineTypeScale:1,lineWeight:u.AcGiLineWeight.ByLayer,fillType:{solidFill:!0,patternAngle:0,definitionLines:[]},transparency:new u.AcCmTransparency,thickness:0,layer:"0",drawOrder:0}}static createTraitsForMText(e){const t=un.toAcCmColor(e.color),i=un.resolveRgbColor(e);return{color:t,rgbColor:i,lineType:{type:"ByLayer",name:"Continuous",standardFlag:0,description:"Solid line",totalPatternLength:0},lineTypeScale:1,lineWeight:u.AcGiLineWeight.ByLayer,fillType:{solidFill:!0,patternAngle:0,definitionLines:[]},transparency:new u.AcCmTransparency,thickness:0,layer:e.layer??"0",drawOrder:0}}}function $e(o){return o.userData}function Qa(o){return o.userData}function ie(o){return $e(o)}function ni(o){return $e(o)}function Ps(o,e){const t=$e(o),i=ie(e);t.useSplitTranslation&&(i.useSplitTranslation=!0),t.noBatch&&(i.noBatch=!0);const n=Math.min(o.children.length,e.children.length);for(let s=0;s<n;s++)Ps(o.children[s],e.children[s])}const ec=new y.Color(583902);class We{static cloneMaterial(e){if(!e)return e;if(Array.isArray(e)){const t=[];return e.forEach(i=>{t.push(this.cloneSingleMaterial(i))}),t}return this.cloneSingleMaterial(e)}static setMaterialColor(e,t=ec){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),e.uniforms.u_startColor&&e.uniforms.u_startColor.value.set(t),e.uniforms.u_endColor&&e.uniforms.u_endColor.value.set(t))}static hasColorProperty(e){return"color"in e&&e.color instanceof y.Color}static hasEmissiveProperty(e){return"emissive"in e&&e.emissive instanceof y.Color}static hasUniformsProperty(e){return"uniforms"in e&&e.uniforms!==void 0}static cloneSingleMaterial(e){const t=e.clone();return this.resetRuntimeShaderState(t),t}static resetRuntimeShaderState(e){const t=Qa(e);delete t.relativeToEyePatchVersion,delete t.relativeToEyeCompiledShader,e.onBeforeCompile=y.Material.prototype.onBeforeCompile,e.customProgramCacheKey=y.Material.prototype.customProgramCacheKey,e.needsUpdate=!0}}class _s{static createMatrix4(e){const t=e.elements;return new y.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])}}function Ls(o){let e=o;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}function tc(o,e){return o-e}function gn(o,e,t=0){const i=e.itemSize;if(o.isInterleavedBufferAttribute||o.array.constructor!==e.array.constructor){const n=o.count;for(let s=0;s<n;s++)for(let r=0;r<i;r++)e.setComponent(s+t,r,o.getComponent(s,r))}else e.array.set(o.array,t*i);e.needsUpdate=!0}function He(o,e){if(o.constructor!==e.constructor){const t=Math.min(o.length,e.length);for(let i=0;i<t;i++)e[i]=o[i]}else{const t=Math.min(o.length,e.length);e.set(new o.constructor(o.buffer,0,t))}}function ic(o){const e=o.length;let t=0;return e>0&&(t=hn.estimateObjectSize(o[0])),{count:e,size:e*t}}function pn(o,e,t,i){for(const n in e.attributes){const s=e.getAttribute(n),{array:r,itemSize:a,normalized:c}=s,l=new r.constructor(t*a),h=new y.BufferAttribute(l,a,c);o.setAttribute(n,h)}if(i!=null&&e.getIndex()!==null){const n=t>65535?new Uint32Array(i):new Uint16Array(i);o.setIndex(new y.BufferAttribute(n,1))}}function mn(o,e,t,i){if(i&&!!e.getIndex()!=!!o.getIndex())throw new Error(`${t}: All geometries must consistently have "index".`);for(const n in o.attributes){if(!e.hasAttribute(n))throw new Error(`${t}: Added geometry missing "${n}". All geometries must have consistent attributes.`);const s=e.getAttribute(n),r=o.getAttribute(n);if(s.itemSize!==r.itemSize||s.normalized!==r.normalized)throw new Error(`${t}: All attributes must have a consistent itemSize and normalized value.`)}}function si(o,e,t,i){let n,s=t;return o.length>0?(o.sort(tc),n=o.shift(),e[n]=i):(n=t,s++,e.push(i)),{geometryId:n,geometryCount:s}}function it(o,e){return o===-1?e:o}function ri(){return{boundingBox:null,active:!0,visible:!0}}function oi(o){const{typeName:e,maxVertexCount:t,vertexStart:i,reservedVertexCount:n,maxIndexCount:s,indexStart:r=-1,reservedIndexCount:a=0}=o;if(s!=null&&r!==-1&&r+a>s||i+n>t)throw new Error(`${e}: Reserved space request exceeds the maximum buffer size.`)}function nt(o){const{currentMaxCount:e,nextStart:t,requiredCount:i,growthFactor:n}=o,s=t+i;return s<=e?e:Math.ceil(s*n)}function nc(o,e,t){return o>=e.length||e[o].active===!1?!1:(e[o].active=!1,e[o].visible=!1,t.push(o),!0)}function sc(o,e,t){if(o<0||o>=e.length||e[o].active===!1)throw new Error(`${t}: Invalid geometryId ${o}. Geometry is either out of range or has been deleted.`)}function rc(o,e,t,i){for(const n in o.attributes){const s=e.getAttribute(n),r=o.getAttribute(n);gn(s,r,t);const a=s.itemSize;for(let c=s.count,l=i;c<l;c++){const h=t+c;for(let d=0;d<a;d++)r.setComponent(h,d,0)}r.needsUpdate=!0,r.addUpdateRange(t*a,i*a)}}function oc(o,e,t,i,n){const s=o.getIndex(),r=e.getIndex();if(!(!s||!r)){for(let a=0;a<r.count;a++)s.setX(i+a,t+r.getX(a));for(let a=r.count,c=n;a<c;a++)s.setX(i+a,t);s.needsUpdate=!0,s.addUpdateRange(i,n)}}function fn(o,e,t,i){const n=e.getIndex()!==null,s=t.getIndex();if(n&&s&&s.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw new Error(`${i}: Reserved space not large enough for provided geometry.`);const r=o.vertexStart,a=o.reservedVertexCount;if(o.vertexCount=t.getAttribute("position").count,rc(e,t,r,a),n&&s){const c=o;c.indexCount=s.count,oc(e,t,r,c.indexStart,c.reservedIndexCount)}o.boundingBox=null}function ac(o,e){const t=o??new y.Box3;t.makeEmpty();for(let i=0,n=e.length;i<n;i++){const s=e[i];s.active!==!1&&s.boundingBox!=null&&t.union(s.boundingBox)}return t}function cc(o,e,t){const i=o??new y.Sphere;i.makeEmpty();const n=new y.Sphere;for(let s=0,r=e.length;s<r;s++)e[s].active!==!1&&(t(s,n),i.union(n));return i}function lc(o,e,t){o.material=t,o.geometry.index=e.index,o.geometry.attributes=e.attributes,o.geometry.boundingBox===null&&(o.geometry.boundingBox=new y.Box3),o.geometry.boundingSphere===null&&(o.geometry.boundingSphere=new y.Sphere)}function hc(o,e,t,i,n){o.geometry.setDrawRange(e,t),o.geometry.boundingBox.copy(i),o.geometry.boundingSphere.copy(n)}function uc(o){o.geometry.index=null,o.geometry.attributes={},o.geometry.setDrawRange(0,1/0)}function ai(o,e){return class extends o{constructor(){super(...arguments),this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._geometryCount=0,this._raycastObject=e.createObject(),this._batchIntersects=[],this._box=new y.Box3,this._sphere=new y.Sphere,this._vector=new y.Vector3,this._typedBatchIntersects=this._batchIntersects}get mappingStats(){return ic(this._geometryInfo)}validateGeometryId(t){sc(t,this._geometryInfo,e.typeName)}getGeometryRangeAt(t){return this.validateGeometryId(t),this._geometryInfo[t]}computeBoundingBox(){this.boundingBox=ac(this.boundingBox,this._geometryInfo)}computeBoundingSphere(){this.boundingSphere=cc(this.boundingSphere,this._geometryInfo,(t,i)=>this.getBoundingSphereAt(t,i))}setVisibleAt(t,i){return this.validateGeometryId(t),this._geometryInfo[t].visible===i?this:(this._geometryInfo[t].visible=i,this)}getVisibleAt(t){return this.validateGeometryId(t),this._geometryInfo[t].visible}deleteGeometry(t){return nc(t,this._geometryInfo,this._availableGeometryIds)?this:this}getObjectAt(t){const i=e.createObject();this._initializeRaycastObject(i);const n=this._geometryInfo[t],{start:s,count:r}=e.getDrawRange(this,n);return this._setRaycastObjectInfo(i,t,s,r),i}intersectWith(t,i,n){this._initializeRaycastObject(this._raycastObject),this._intersectWith(t,i,n),this._resetRaycastObjectInfo(this._raycastObject)}raycast(t,i){this._initializeRaycastObject(this._raycastObject);for(let n=0,s=this._geometryInfo.length;n<s;n++)this._intersectWith(n,t,i);this._resetRaycastObjectInfo(this._raycastObject)}dispose(){return this.geometry.dispose(),this}_initializeRaycastObject(t){lc(t,this.geometry,this.material),t.position.copy(this.position),t.quaternion.copy(this.quaternion),t.scale.copy(this.scale),t.updateMatrix(),t.updateMatrixWorld(!0)}_setRaycastObjectInfo(t,i,n,s){const r=this;r.getBoundingBoxAt(i,this._box),r.getBoundingSphereAt(i,this._sphere),hc(t,n,s,this._box,this._sphere)}_resetRaycastObjectInfo(t){uc(t)}_intersectWith(t,i,n){const s=this._geometryInfo[t];if(!(!s.visible||!s.active))if(s.bboxIntersectionCheck){if(this.getBoundingBoxAt(t,this._box),this._box.applyMatrix4(this.matrixWorld),i.ray.intersectBox(this._box,this._vector)){const r=i.ray.origin.distanceTo(this._vector);n.push({distance:r,point:this._vector.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:t,objectId:s.objectId})}}else{const{start:r,count:a}=e.getDrawRange(this,s);this._setRaycastObjectInfo(this._raycastObject,t,r,a),this._raycastObject.raycast(i,this._batchIntersects);for(let c=0,l=this._typedBatchIntersects.length;c<l;c++){const h=this._typedBatchIntersects[c];h.object=this,h.batchId=t,h.objectId=s.objectId,n.push(h)}this._batchIntersects.length=0}}}}const st=new y.Box3,dc=new y.Vector3,yn=new y.Vector3,gc=ai(y.LineSegments,{typeName:"AcTrBatchedLine",createObject:()=>new y.LineSegments,getDrawRange:(o,e)=>o.geometry.index!=null?{start:e.indexStart,count:e.indexCount}:{start:e.vertexStart,count:e.vertexCount}}),Ts=class ps extends gc{constructor(e=1e3,t=e*2,i){super(new y.BufferGeometry,i),this._nextIndexStart=0,this._nextVertexStart=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}_initializeGeometry(e){this._geometryInitialized===!1&&(pn(this.geometry,e,this._maxVertexCount,this._maxIndexCount),this._geometryInitialized=!0)}_validateGeometry(e){mn(this.geometry,e,"AcTrBatchedLine",!0)}_resizeSpaceIfNeeded(e){const t=e.getIndex(),i=t==null?this._maxIndexCount:nt({currentMaxCount:this._maxIndexCount,nextStart:this._nextIndexStart,requiredCount:t.count,growthFactor:ps.GROWTH_FACTOR}),n=e.getAttribute("position"),s=n==null?this._maxVertexCount:nt({currentMaxCount:this._maxVertexCount,nextStart:this._nextVertexStart,requiredCount:n.count,growthFactor:ps.GROWTH_FACTOR});(i>this._maxIndexCount||s>this._maxVertexCount)&&this.setGeometrySize(s,i)}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._origin=void 0,this.position.set(0,0,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=Me.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)}}})}addGeometry(e,t=-1,i=-1,n=new y.Vector3){this.rebaseGeometryInPlace(e,n),this._initializeGeometry(e),this._validateGeometry(e),this._resizeSpaceIfNeeded(e);const s=e.getAttribute("position").count,r=e.getIndex(),a={vertexStart:this._nextVertexStart,vertexCount:-1,reservedVertexCount:it(t,s),indexStart:r?this._nextIndexStart:-1,indexCount:-1,reservedIndexCount:r?it(i,r.count):0,...ri()};oi({typeName:"AcTrBatchedLine",maxVertexCount:this._maxVertexCount,vertexStart:a.vertexStart,reservedVertexCount:a.reservedVertexCount,maxIndexCount:this._maxIndexCount,indexStart:a.indexStart,reservedIndexCount:a.reservedIndexCount});const{geometryId:c,geometryCount:l}=si(this._availableGeometryIds,this._geometryInfo,this._geometryCount,a);return this._geometryCount=l,this.setGeometryAt(c,e),this._nextIndexStart=a.indexStart+a.reservedIndexCount,this._nextVertexStart=a.vertexStart+a.reservedVertexCount,this._syncDrawRange(),c}rebaseGeometryInPlace(e,t){const i=e.getAttribute("position");if(!i)return;if(!this._origin){e.computeBoundingBox();const r=e.boundingBox?e.boundingBox.getCenter(new y.Vector3):new y.Vector3;this._origin=r.add(t.clone()),this.position.copy(this._origin)}const n=this._origin;if(!n)return;const s=i.array;if(s instanceof Float32Array){for(let r=0;r<s.length;r+=3)s[r]=s[r]+t.x-n.x,s[r+1]=s[r+1]+t.y-n.y,s[r+2]=s[r+2]+t.z-n.z;i.needsUpdate=!0;return}for(let r=0;r<i.count;r++)i.setXYZ(r,i.getX(r)+t.x-n.x,i.getY(r)+t.y-n.y,i.getZ(r)+t.z-n.z);i.needsUpdate=!0}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];return fn(n,i,t,"AcTrBatchedLine"),e}optimize(){const e=this.geometry,t=e.index!==null,i=e.attributes,n=e.index;let s=0,r=0;const a=this._geometryInfo.map((c,l)=>({info:c,id:l})).filter(c=>c.info.active).sort((c,l)=>c.info.vertexStart-l.info.vertexStart);for(const{info:c}of a){const l=c.vertexCount,h=t?c.indexCount:0,d=c.vertexStart,p=s,m=p-d;if(m!==0&&l>0)for(const f in i){const w=i[f],{array:x,itemSize:b}=w;x.copyWithin(p*b,d*b,(d+l)*b),w.addUpdateRange(p*b,l*b),w.needsUpdate=!0}if(t&&n&&h>0){const f=c.indexStart,w=r,x=n.array;if(m!==0)for(let b=f;b<f+h;b++)x[b]+=m;f!==w&&x.copyWithin(w,f,f+h),n.addUpdateRange(w,h),n.needsUpdate=!0,c.indexStart=w}c.vertexStart=p,s+=c.reservedVertexCount,r+=c.reservedIndexCount}if(t&&n){const c=n.array;for(let l=r;l<c.length;l++)c[l]=0;n.needsUpdate=!0}return t?e.setDrawRange(0,r):e.setDrawRange(0,s),this._nextVertexStart=s,this._nextIndexStart=r,this._syncDrawRange(),this._availableGeometryIds.length=0,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 y.Box3,r=i.index,a=i.attributes.position,{start:c,count:l}=r!=null?{start:n.indexStart,count:n.indexCount}:{start:n.vertexStart,count:n.vertexCount};for(let h=c,d=c+l;h<d;h++){let p=h;r&&(p=r.getX(p)),s.expandByPoint(dc.fromBufferAttribute(a,p))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){return e>=this._geometryCount?null:(this.getBoundingBoxAt(e,st),st.getBoundingSphere(t),t)}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 y.BufferGeometry,this._initializeGeometry(i));const n=this.geometry;i.index&&He(i.index.array,n.index.array);for(const s in i.attributes)He(i.attributes[s].array,n.attributes[s].array);this._syncDrawRange()}getObjectAt(e){const t=super.getObjectAt(e);return t.position.copy(this.position),t}_initializeRaycastObject(e){super._initializeRaycastObject(e),e.position.copy(this.position),e.updateMatrixWorld(!0)}_syncDrawRange(){const e=this.geometry;e.index?e.setDrawRange(0,this._nextIndexStart):e.setDrawRange(0,this._nextVertexStart)}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!n.active||!n.visible)return;if(n.bboxIntersectionCheck){if(this.getBoundingBoxAt(e,this._box),this._box.applyMatrix4(this.matrixWorld),t.ray.intersectBox(this._box,this._vector)){const r=t.ray.origin.distanceTo(this._vector);i.push({distance:r,point:this._vector.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}return}const s=this.geometry.index!=null?{start:n.indexStart,count:n.indexCount}:{start:n.vertexStart,count:n.vertexCount};if(this._setRaycastObjectInfo(this._raycastObject,e,s.start,s.count),this._raycastObject.raycast(t,this._batchIntersects),this._batchIntersects.length===0){this.getBoundingBoxAt(e,st),st.applyMatrix4(this.matrixWorld);const r=t.params.Line.threshold;if(r>0&&st.expandByScalar(r),t.ray.intersectBox(st,yn)){const a=t.ray.origin.distanceTo(yn);i.push({distance:a,point:yn.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}return}for(let r=0,a=this._typedBatchIntersects.length;r<a;r++){const c=this._typedBatchIntersects[r];c.object=this,c.batchId=e,c.objectId=n.objectId,i.push(c)}this._batchIntersects.length=0}copy(e){var t;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(i=>({...i,boundingBox:i.boundingBox!==null?i.boundingBox.clone():null})),this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._origin=(t=e._origin)==null?void 0:t.clone(),this}};Ts.GROWTH_FACTOR=1.25;let pc=Ts;const Pe=new y.Box3,ci=new y.Vector3,li=new y.Vector3,_t=[],Oe=new Ue.LineSegments2(new De.LineSegmentsGeometry),mc=ai(Ue.LineSegments2,{typeName:"AcTrBatchedLine2",createObject:()=>new Ue.LineSegments2(new De.LineSegmentsGeometry),getDrawRange:(o,e)=>({start:e.vertexStart,count:e.vertexCount})}),Is=class za extends mc{constructor(e=1e3,t){super(new De.LineSegmentsGeometry,t),this._nextSegmentStart=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxSegmentCount=e}get geometryCount(){return this._geometryCount}get unusedSegmentCount(){return this._maxSegmentCount-this._nextSegmentStart}_initializeGeometry(e){this._geometryInitialized||(this.geometry.setPositions(new Float32Array(this._maxSegmentCount*6)),this._copyStaticAttributes(e),this._geometryInitialized=!0)}_copyStaticAttributes(e,t=this.geometry){const i=t,n=e.getIndex();n&&i.setIndex(n.clone());for(const s in e.attributes)s==="instanceStart"||s==="instanceEnd"||i.setAttribute(s,e.getAttribute(s).clone())}_validateGeometry(e){const t=e.getAttribute("instanceStart"),i=e.getAttribute("instanceEnd");if(!t||!i)throw new Error('AcTrBatchedLine2: Geometry must have "instanceStart" and "instanceEnd" attributes.');if(t.itemSize!==3||i.itemSize!==3||t.count!==i.count)throw new Error("AcTrBatchedLine2: Invalid line segment attributes. Expected matching vec3 instanceStart/instanceEnd.")}_resizeSpaceIfNeeded(e){const t=e.getAttribute("instanceStart").count,i=nt({currentMaxCount:this._maxSegmentCount,nextStart:this._nextSegmentStart,requiredCount:t,growthFactor:za.GROWTH_FACTOR});i>this._maxSegmentCount&&this.setGeometrySize(i)}reset(){this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextSegmentStart=0,this._geometryCount=0,this._origin=void 0,this.position.set(0,0,0),this._geometryInitialized=!1,this.geometry.dispose()}addGeometry(e,t=-1,i=new y.Vector3){this.rebaseGeometryInPlace(e,i),this._initializeGeometry(e),this._validateGeometry(e),this._resizeSpaceIfNeeded(e);const n=e.getAttribute("instanceStart").count,s={vertexStart:this._nextSegmentStart,vertexCount:-1,reservedVertexCount:it(t,n),...ri()};oi({typeName:"AcTrBatchedLine2",maxVertexCount:this._maxSegmentCount,vertexStart:s.vertexStart,reservedVertexCount:s.reservedVertexCount});const{geometryId:r,geometryCount:a}=si(this._availableGeometryIds,this._geometryInfo,this._geometryCount,s);return this._geometryCount=a,this.setGeometryAt(r,e),this._nextSegmentStart=s.vertexStart+s.reservedVertexCount,this._syncDrawRange(),r}rebaseGeometryInPlace(e,t){const i=e.getAttribute("instanceStart"),n=e.getAttribute("instanceEnd");if(!i||!n)return;if(!this._origin){e.computeBoundingBox();const r=e.boundingBox?e.boundingBox.getCenter(new y.Vector3):new y.Vector3;this._origin=r.add(t.clone()),this.position.copy(this._origin)}const s=this._origin;if(s){for(let r=0;r<i.count;r++)i.setXYZ(r,i.getX(r)+t.x-s.x,i.getY(r)+t.y-s.y,i.getZ(r)+t.z-s.z),n.setXYZ(r,n.getX(r)+t.x-s.x,n.getY(r)+t.y-s.y,n.getZ(r)+t.z-s.z);i.needsUpdate=!0,n.needsUpdate=!0}}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine2: 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("AcTrBatchedLine2: Maximum geometry count reached.");this._validateGeometry(t);const i=this._geometryInfo[e],n=t.getAttribute("instanceStart").count;if(n>i.reservedVertexCount)throw new Error("AcTrBatchedLine2: Reserved space not large enough for provided geometry.");const s=this.geometry.getAttribute("instanceStart"),r=this.geometry.getAttribute("instanceEnd"),a=t.getAttribute("instanceStart"),c=t.getAttribute("instanceEnd"),l=i.vertexStart;gn(a,s,l),gn(c,r,l);for(let h=n,d=i.reservedVertexCount;h<d;h++){const p=l+h;for(let m=0;m<3;m++)s.setComponent(p,m,0),r.setComponent(p,m,0)}return s.needsUpdate=!0,r.needsUpdate=!0,i.vertexCount=n,i.boundingBox=null,e}optimize(){const e=this._getPackedSegmentArray();let t=0;const i=this._geometryInfo.map((r,a)=>({info:r,id:a})).filter(r=>r.info.active).sort((r,a)=>r.info.vertexStart-a.info.vertexStart);for(const{info:r}of i){const a=r.vertexStart,c=r.reservedVertexCount;a!==t&&e.copyWithin(t*6,a*6,(a+c)*6),r.vertexStart=t,t+=c}for(let r=t*6,a=e.length;r<a;r++)e[r]=0;this._nextSegmentStart=t,this._syncDrawRange(),this._availableGeometryIds.length=0;const n=this.geometry.getAttribute("instanceStart"),s=this.geometry.getAttribute("instanceEnd");return n.needsUpdate=!0,s.needsUpdate=!0,this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this._geometryInfo[e];if(i.boundingBox===null){const n=new y.Box3,s=this.geometry.getAttribute("instanceStart"),r=this.geometry.getAttribute("instanceEnd");for(let a=i.vertexStart,c=i.vertexStart+i.vertexCount;a<c;a++)n.expandByPoint(ci.fromBufferAttribute(s,a)),n.expandByPoint(li.fromBufferAttribute(r,a));i.boundingBox=n}return t.copy(i.boundingBox),t}getBoundingSphereAt(e,t){return e>=this._geometryCount?null:(this.getBoundingBoxAt(e,Pe),Pe.getBoundingSphere(t),t)}getGeometryAt(e){return this.validateGeometryId(e),this._geometryInfo[e]}setGeometrySize(e){const t=this.geometry,i=this._getPackedSegmentArray();this._maxSegmentCount=e,this.geometry=new De.LineSegmentsGeometry,this.geometry.setPositions(new Float32Array(e*6));const n=this._getPackedSegmentArray();He(i,n),this._copyStaticAttributes(t),this._geometryInitialized=!0,this._syncDrawRange(),t.dispose()}getObjectAt(e){const t=this._geometryInfo[e],i=this._createSubGeometry(t.vertexStart,t.vertexCount,!0),n=new Ue.LineSegments2(i,this.material);return n.position.copy(this.position),n.updateMatrix(),n.updateMatrixWorld(!0),this.getBoundingBoxAt(e,n.geometry.boundingBox??new y.Box3),this.getBoundingSphereAt(e,n.geometry.boundingSphere??new y.Sphere),n}intersectWith(e,t,i){this._intersectWith(e,t,i)}raycast(e,t){for(let i=0,n=this._geometryInfo.length;i<n;i++)this._intersectWith(i,e,t)}copy(e){var t;return super.copy(e),this.geometry=e.geometry.clone(),this.boundingBox=e.boundingBox?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(i=>({...i,boundingBox:i.boundingBox?i.boundingBox.clone():null})),this._maxSegmentCount=e._maxSegmentCount,this._geometryCount=e._geometryCount,this._nextSegmentStart=e._nextSegmentStart,this._geometryInitialized=e._geometryInitialized,this._origin=(t=e._origin)==null?void 0:t.clone(),this}dispose(){return this.geometry.dispose(),this}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!n.active||!n.visible)return;if(n.bboxIntersectionCheck){if(this.getBoundingBoxAt(e,Pe),Pe.applyMatrix4(this.matrixWorld),t.ray.intersectBox(Pe,ci)){const r=t.ray.origin.distanceTo(ci);i.push({distance:r,point:ci.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}return}const s=this._createSubGeometry(n.vertexStart,n.vertexCount,!1);if(Oe.geometry=s,Oe.material=this.material,Oe.position.copy(this.position),Oe.quaternion.copy(this.quaternion),Oe.scale.copy(this.scale),Oe.updateMatrix(),Oe.updateMatrixWorld(!0),Oe.raycast(t,_t),_t.length===0){this.getBoundingBoxAt(e,Pe),Pe.applyMatrix4(this.matrixWorld);const r=t.params.Line.threshold;if(r>0&&Pe.expandByScalar(r),t.ray.intersectBox(Pe,li)){const a=t.ray.origin.distanceTo(li);i.push({distance:a,point:li.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}s.dispose();return}for(let r=0,a=_t.length;r<a;r++){const c=_t[r];c.batchId=e,c.objectId=n.objectId,c.object=this,i.push(c)}_t.length=0,s.dispose()}_createSubGeometry(e,t,i){const n=this._getPackedSegmentArray(),s=i?n.slice(e*6,(e+t)*6):n.subarray(e*6,(e+t)*6),r=new De.LineSegmentsGeometry;return r.setPositions(s),this._copyStaticAttributes(this.geometry,r),r}_getPackedSegmentArray(){var e;const t=this.geometry.getAttribute("instanceStart");if("data"in t&&(e=t.data)!=null&&e.array)return t.data.array;const i=this.geometry.getAttribute("instanceEnd"),n=t.count,s=new Float32Array(n*6);for(let r=0,a=0;r<n;r++)s[a++]=t.getComponent(r,0),s[a++]=t.getComponent(r,1),s[a++]=t.getComponent(r,2),s[a++]=i.getComponent(r,0),s[a++]=i.getComponent(r,1),s[a++]=i.getComponent(r,2);return s}_syncDrawRange(){this.geometry.instanceCount=this._nextSegmentStart}};Is.GROWTH_FACTOR=1.25;let Es=Is;const ks=new y.Box3,fc=new y.Vector3,yc=ai(y.Mesh,{typeName:"AcTrBatchedMesh",createObject:()=>new y.Mesh,getDrawRange:(o,e)=>o.geometry.index!=null?{start:e.indexStart,count:e.indexCount}:{start:e.vertexStart,count:e.vertexCount}}),Bs=class ms extends yc{constructor(e=1e3,t=e*2,i){super(new y.BufferGeometry,i),this._nextIndexStart=0,this._nextVertexStart=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}_initializeGeometry(e){this._geometryInitialized===!1&&(pn(this.geometry,e,this._maxVertexCount,this._maxIndexCount),this._geometryInitialized=!0)}_validateGeometry(e){mn(this.geometry,e,"AcTrBatchedMesh",!0)}_resizeSpaceIfNeeded(e){const t=e.getIndex(),i=t==null?this._maxIndexCount:nt({currentMaxCount:this._maxIndexCount,nextStart:this._nextIndexStart,requiredCount:t.count,growthFactor:ms.GROWTH_FACTOR}),n=e.getAttribute("position"),s=n==null?this._maxVertexCount:nt({currentMaxCount:this._maxVertexCount,nextStart:this._nextVertexStart,requiredCount:n.count,growthFactor:ms.GROWTH_FACTOR});(i>this._maxIndexCount||s>this._maxVertexCount)&&this.setGeometrySize(s,i)}addGeometry(e,t=-1,i=-1,n=new y.Vector3){this.rebaseGeometryInPlace(e,n),e.hasAttribute("uv")&&e.deleteAttribute("uv"),e.hasAttribute("normal")&&e.deleteAttribute("normal"),this._initializeGeometry(e),this._validateGeometry(e),this._resizeSpaceIfNeeded(e);const s=e.getAttribute("position").count,r=e.getIndex(),a={vertexStart:this._nextVertexStart,vertexCount:-1,reservedVertexCount:it(t,s),indexStart:r?this._nextIndexStart:-1,indexCount:-1,reservedIndexCount:r?it(i,r.count):0,...ri()};oi({typeName:"AcTrBatchedMesh",maxVertexCount:this._maxVertexCount,vertexStart:a.vertexStart,reservedVertexCount:a.reservedVertexCount,maxIndexCount:this._maxIndexCount,indexStart:a.indexStart,reservedIndexCount:a.reservedIndexCount});const{geometryId:c,geometryCount:l}=si(this._availableGeometryIds,this._geometryInfo,this._geometryCount,a);return this._geometryCount=l,this.setGeometryAt(c,e),this._nextIndexStart=a.indexStart+a.reservedIndexCount,this._nextVertexStart=a.vertexStart+a.reservedVertexCount,this._syncDrawRange(),c}rebaseGeometryInPlace(e,t){const i=e.getAttribute("position");if(!i)return;if(!this._origin){e.computeBoundingBox();const r=e.boundingBox?e.boundingBox.getCenter(new y.Vector3):new y.Vector3;this._origin=r.add(t.clone()),this.position.copy(this._origin)}const n=this._origin;if(!n)return;const s=i.array;if(s instanceof Float32Array){for(let r=0;r<s.length;r+=3)s[r]=s[r]+t.x-n.x,s[r+1]=s[r+1]+t.y-n.y,s[r+2]=s[r+2]+t.z-n.z;i.needsUpdate=!0;return}for(let r=0;r<i.count;r++)i.setXYZ(r,i.getX(r)+t.x-n.x,i.getY(r)+t.y-n.y,i.getZ(r)+t.z-n.z);i.needsUpdate=!0}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=this._geometryInfo[e];return fn(n,i,t,"AcTrBatchedMesh"),e}optimize(){const e=this.geometry,t=e.index!==null,i=e.attributes,n=e.index;let s=0,r=0;const a=this._geometryInfo.map((c,l)=>({info:c,i:l})).filter(c=>c.info.active).sort((c,l)=>c.info.vertexStart-l.info.vertexStart);for(const{info:c}of a){const l=c.vertexCount,h=t?c.indexCount:0,d=c.vertexStart,p=c.indexStart;if(d!==s){for(const m in i){const f=i[m],{array:w,itemSize:x}=f;w.copyWithin(s*x,d*x,(d+l)*x),f.addUpdateRange(s*x,l*x),f.needsUpdate=!0}c.vertexStart=s}if(t&&n&&p!==r){const m=n.array,f=s-d;for(let w=0;w<h;w++)m[r+w]=m[p+w]+f;n.addUpdateRange(r,h),n.needsUpdate=!0,c.indexStart=r}s+=l,r+=h}if(t&&n){const c=n.array;for(let l=r,h=c.length;l<h;l++)c[l]=0;n.needsUpdate=!0}return this._nextVertexStart=s,this._nextIndexStart=r,this._syncDrawRange(),this._availableGeometryIds.length=0,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 y.Box3,r=i.index,a=i.attributes.position,{start:c,count:l}=r!=null?{start:n.indexStart,count:n.indexCount}:{start:n.vertexStart,count:n.vertexCount};for(let h=c,d=c+l;h<d;h++){let p=h;r&&(p=r.getX(p)),s.expandByPoint(fc.fromBufferAttribute(a,p))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){return e>=this._geometryCount?null:(this.getBoundingBoxAt(e,ks),ks.getBoundingSphere(t),t)}setGeometrySize(e,t){const i=this.geometry;i.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new y.BufferGeometry,this._initializeGeometry(i));const n=this.geometry;i.index&&He(i.index.array,n.index.array);for(const s in i.attributes)He(i.attributes[s].array,n.attributes[s].array);this._syncDrawRange()}_syncDrawRange(){const e=this.geometry;e.index?e.setDrawRange(0,this._nextIndexStart):e.setDrawRange(0,this._nextVertexStart)}copy(e){var t;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(i=>({...i,boundingBox:i.boundingBox!==null?i.boundingBox.clone():null})),this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._origin=(t=e._origin)==null?void 0:t.clone(),this}};Bs.GROWTH_FACTOR=1.25;let wc=Bs;const Ds=new y.Box3,bc=new y.Vector3,vc=ai(y.Points,{typeName:"AcTrBatchedPoint",createObject:()=>new y.Points,getDrawRange:(o,e)=>({start:e.vertexStart,count:e.vertexCount})}),Ms=class Va extends vc{constructor(e=1e3,t){super(new y.BufferGeometry,t),this._nextVertexStart=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxVertexCount=e}get geometryCount(){return this._geometryCount}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}_initializeGeometry(e){this._geometryInitialized===!1&&(pn(this.geometry,e,this._maxVertexCount,null),this._geometryInitialized=!0)}_validateGeometry(e){mn(this.geometry,e,"AcTrBatchedPoint",!1)}_resizeSpaceIfNeeded(e){const t=e.getAttribute("position"),i=t==null?this._maxVertexCount:nt({currentMaxCount:this._maxVertexCount,nextStart:this._nextVertexStart,requiredCount:t.count,growthFactor:Va.GROWTH_FACTOR});i>this._maxVertexCount&&this.setGeometrySize(i)}reset(){this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextVertexStart=0,this._geometryCount=0,this._geometryInfo.length=0,this._origin=void 0,this.position.set(0,0,0),this._geometryInitialized=!1,this.geometry.dispose()}addGeometry(e,t=-1,i=new y.Vector3){this.rebaseGeometryInPlace(e,i),this._initializeGeometry(e),this._validateGeometry(e),this._resizeSpaceIfNeeded(e);const n=e.getAttribute("position").count,s={vertexStart:this._nextVertexStart,vertexCount:-1,reservedVertexCount:it(t,n),...ri()};oi({typeName:"AcTrBatchedPoint",maxVertexCount:this._maxVertexCount,vertexStart:s.vertexStart,reservedVertexCount:s.reservedVertexCount});const{geometryId:r,geometryCount:a}=si(this._availableGeometryIds,this._geometryInfo,this._geometryCount,s);return this._geometryCount=a,this.setGeometryAt(r,e),this._nextVertexStart=s.vertexStart+s.reservedVertexCount,this.geometry.setDrawRange(0,this._nextVertexStart),this._syncDrawRange(),r}rebaseGeometryInPlace(e,t){const i=e.getAttribute("position");if(!i)return;if(!this._origin){e.computeBoundingBox();const r=e.boundingBox?e.boundingBox.getCenter(new y.Vector3):new y.Vector3;this._origin=r.add(t.clone()),this.position.copy(this._origin)}const n=this._origin;if(!n)return;const s=i.array;if(s instanceof Float32Array){for(let r=0;r<s.length;r+=3)s[r]=s[r]+t.x-n.x,s[r+1]=s[r+1]+t.y-n.y,s[r+2]=s[r+2]+t.z-n.z;i.needsUpdate=!0;return}for(let r=0;r<i.count;r++)i.setXYZ(r,i.getX(r)+t.x-n.x,i.getY(r)+t.y-n.y,i.getZ(r)+t.z-n.z);i.needsUpdate=!0}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedPoint: 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("AcTrBatchedPoint: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=this._geometryInfo[e];return fn(n,i,t,"AcTrBatchedPoint"),e}optimize(){let e=0;const t=this.geometry,i=this._geometryInfo,n=i.map((s,r)=>r).filter(s=>i[s].active).sort((s,r)=>i[s].vertexStart-i[r].vertexStart);for(let s=0;s<n.length;s++){const r=n[s],a=i[r],c=a.vertexStart,l=a.reservedVertexCount;if(c!==e){for(const h in t.attributes){const d=t.attributes[h],{array:p,itemSize:m}=d;p.copyWithin(e*m,c*m,(c+l)*m),d.addUpdateRange(e*m,l*m),d.needsUpdate=!0}a.vertexStart=e}e+=l}return this._nextVertexStart=e,this._syncDrawRange(),this._availableGeometryIds.length=0,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 y.Box3,r=i.index,a=i.attributes.position;for(let c=n.vertexStart,l=n.vertexStart+n.vertexCount;c<l;c++){let h=c;r&&(h=r.getX(h)),s.expandByPoint(bc.fromBufferAttribute(a,h))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){return e>=this._geometryCount?null:(this.getBoundingBoxAt(e,Ds),Ds.getBoundingSphere(t),t)}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 y.BufferGeometry,this._initializeGeometry(t));const i=this.geometry;t.index&&He(t.index.array,i.index.array);for(const n in t.attributes)He(t.attributes[n].array,i.attributes[n].array);this._syncDrawRange()}_syncDrawRange(){this.geometry.setDrawRange(0,this._nextVertexStart)}copy(e){var t;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(i=>({...i,boundingBox:i.boundingBox!==null?i.boundingBox.clone():null})),this._maxVertexCount=e._maxVertexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._origin=(t=e._origin)==null?void 0:t.clone(),this}};Ms.GROWTH_FACTOR=1.25;let xc=Ms;const rt=class et extends y.Group{constructor(){super(),this._pointBatches=new Map,this._pointSymbolBatches=new Map,this._lineBatches=new Map,this._lineWithIndexBatches=new Map,this._line2Batches=new Map,this._meshBatches=new Map,this._meshWithIndexBatches=new Map,this._entitiesMap=new Map,this._unbatchedEntities=new Map,this._unbatchedObjects=new y.Group,this._selectedObjects=new y.Group,this._hoverObjects=new y.Group,this.add(this._unbatchedObjects),this.add(this._selectedObjects),this.add(this._hoverObjects)}get entityCount(){return this._entitiesMap.size}get stats(){const e=this.getUnbatchedStats(),t={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+this._line2Batches.size,geometrySize:this.getBatchedGeometrySize(this._lineBatches)+this.getBatchedGeometrySize(this._line2Batches),mappingSize:this.getBatchedGeometryMappingSize(this._lineBatches)+this.getBatchedGeometryMappingSize(this._line2Batches)}},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)}},unbatched:e};return t.summary.totalGeometrySize=t.line.indexed.geometrySize+t.line.nonIndexed.geometrySize+t.mesh.indexed.geometrySize+t.mesh.nonIndexed.geometrySize+t.point.indexed.geometrySize+t.point.nonIndexed.geometrySize+t.unbatched.geometrySize,t.summary.totalMappingSize=t.line.indexed.mappingSize+t.line.nonIndexed.mappingSize+t.mesh.indexed.mappingSize+t.mesh.nonIndexed.mappingSize+t.point.indexed.mappingSize+t.point.nonIndexed.mappingSize,t}rerenderPoints(e){const t=Me.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.groups.forEach(e=>{e.forEach(t=>{t.dispose(),t.removeFromParent()}),e.clear()}),this.clearHighlightGroup(this._selectedObjects),this.clearHighlightGroup(this._hoverObjects),this._unbatchedObjects.children.forEach(e=>{this.disposeObject(e)}),this._unbatchedObjects.clear(),this._unbatchedEntities.clear(),this._entitiesMap.clear(),this}updateMaterial(e,t){this.groups.forEach(i=>{const n=i.get(e);n&&(n.material=t,i.set(t.id,n))}),this._unbatchedObjects.traverse(i=>{if(!("material"in i))return;const n=ie(i);n.styleMaterialId===e&&(i.material=t,n.styleMaterialId=t.id)})}hasEntity(e){return this._entitiesMap.has(e)}addEntity(e){if(!e.visible)return;const t=e.objectId,i=e.visible;let n=this._entitiesMap.get(t);n||(n=[],this._entitiesMap.set(t,n));const s=this._unbatchedEntities.get(t)??[];let r=!1;const a=e.styleManager;e.updateMatrixWorld(!0),e.traverse(c=>{if(!Ls(c))return;const l=ie(c),h=!!l.bboxIntersectionCheck;if(c instanceof Ue.LineSegments2){const d=this.addLine2(c,{objectId:t,bboxIntersectionCheck:h});n.push(d),this.applyBatchSlotVisibility(d,i&&c.visible);return}if(l.noBatch){const d=this.cloneUnbatchedObject(c);d.visible=i&&c.visible,ie(d).bboxIntersectionCheck=h,this._unbatchedObjects.add(d),s.push(d),r=!0;return}if(c instanceof y.LineSegments){const d=this.addLine(c,{position:l.position,objectId:t,bboxIntersectionCheck:h});n.push(d),this.applyBatchSlotVisibility(d,i&&c.visible)}else if(c instanceof y.Mesh){const d=this.addMesh(c,{objectId:t,bboxIntersectionCheck:h},a);n.push(d),this.applyBatchSlotVisibility(d,i&&c.visible)}else if(c instanceof y.Points){const d=this.addPoint(c,{objectId:t,bboxIntersectionCheck:h});n.push(d),this.applyBatchSlotVisibility(d,i&&c.visible)}}),r&&this._unbatchedEntities.set(t,s)}removeEntity(e){let t=!1;const i=this._entitiesMap.get(e);if(i){const s=new Map;for(let r=0,a=i.length;r<a;r++){const c=i[r],l=this.getObjectById(c.batchedObjectId);l&&(l.deleteGeometry(c.batchId),s.set(c.batchedObjectId,l),t=!0)}s.forEach(r=>r.optimize()),this.unhighlight(e,this._selectedObjects),this._entitiesMap.delete(e)}const n=this._unbatchedEntities.get(e);return n&&(this.unhighlight(e,this._selectedObjects),this.unhighlight(e,this._hoverObjects),n.forEach(s=>{this.disposeObject(s),this._unbatchedObjects.remove(s)}),this._unbatchedEntities.delete(e),t=!0),t}isIntersectWith(e,t){const i=this._entitiesMap.get(e);if(i){const s=[];for(let r=0,a=i.length;r<a;r++){const c=i[r],l=this.getObjectById(c.batchedObjectId);if(l&&(l.intersectWith(c.batchId,t,s),s.length>0))return!0}}const n=this._unbatchedEntities.get(e);if(n)for(let s=0;s<n.length;s++){const r=n[s];if(t.intersectObject(r,!0).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)}get groups(){return[this._lineBatches,this._lineWithIndexBatches,this._line2Batches,this._meshBatches,this._meshWithIndexBatches,this._pointBatches,this._pointSymbolBatches]}highlight(e,t){const i=this._entitiesMap.get(e);i&&i.length<1e3&&i.forEach(s=>{const r=this.getObjectById(s.batchedObjectId),a=r.getObjectAt(s.batchId);this.copyHighlightMetadata(r,a),this.applyHighlightMaterial(a);const c=ni(a);c.objectId=e,c.disposeGeometryOnRemove=r instanceof Es,t.add(a)});const n=this._unbatchedEntities.get(e);n&&n.length<1e3&&n.forEach(s=>{const r=s.clone();this.copyHighlightMetadata(s,r),this.applyHighlightMaterial(r),ni(r).objectId=e,t.add(r)})}applyHighlightMaterial(e){if(this.hasMaterial(e)){const t=We.cloneMaterial(e.material);We.setMaterialColor(t),e.material=t}e.children.forEach(t=>this.applyHighlightMaterial(t))}copyHighlightMetadata(e,t){Ps(e,t)}unhighlight(e,t){const i=[];t.children.forEach(n=>{ni(n).objectId===e&&i.push(n)}),i.forEach(n=>this.disposeHighlightObject(n)),t.remove(...i)}applyBatchSlotVisibility(e,t){if(t)return;const i=this.getObjectById(e.batchedObjectId);i==null||i.setVisibleAt(e.batchId,!1)}addLine(e,t){const i=e.material,n=this.getMatchedLineBatches(e);let s=n.get(i.id);s==null&&(s=new pc(et.INITIAL_LINE_VERTEX_CAPACITY,et.INITIAL_LINE_INDEX_CAPACITY,i),n.set(i.id,s),this.add(s));const r=e.geometry.clone(),a=e.matrixWorld.clone(),c=new y.Vector3().setFromMatrixPosition(e.matrixWorld);a.setPosition(0,0,0),r.applyMatrix4(a);const l=s.addGeometry(r,-1,-1,c);return s.setGeometryInfo(l,t),r.dispose(),{batchedObjectId:s.id,batchId:l}}addLine2(e,t){const i=e.material;let n=this._line2Batches.get(i.id);n==null&&(n=new Es(et.INITIAL_LINE_VERTEX_CAPACITY,i),this._line2Batches.set(i.id,n),this.add(n));const s=e.matrixWorld.clone(),r=new y.Vector3().setFromMatrixPosition(e.matrixWorld);s.setPosition(0,0,0);const a=this.cloneLineSegments2Geometry(e,s),c=n.addGeometry(a,-1,r);return n.setGeometryInfo(c,t),a.dispose(),{batchedObjectId:n.id,batchId:c}}addMesh(e,t,i){let n=e.material;e.matrixWorld.determinant()<0&&(n=i.getBackSideVariant(n),e.material=n);const s=this.getMatchedMeshBatches(e);let r=s.get(n.id);if(r==null){const d=Ce(n).drawOrder??0;r=new wc(et.INITIAL_MESH_VERTEX_CAPACITY,et.INITIAL_MESH_INDEX_CAPACITY,n),r.renderOrder=d,s.set(n.id,r),this.add(r)}const a=e.geometry.clone(),c=e.matrixWorld.clone(),l=new y.Vector3().setFromMatrixPosition(e.matrixWorld);c.setPosition(0,0,0),a.applyMatrix4(c);const h=r.addGeometry(a,-1,-1,l);return r.setGeometryInfo(h,t),a.dispose(),{batchedObjectId:r.id,batchId:h}}addPoint(e,t){const i=e.material;let n=this._pointBatches.get(i.id);n==null&&(n=new xc(et.INITIAL_POINT_VERTEX_CAPACITY,i),n.visible=e.visible,this._pointBatches.set(i.id,n),this.add(n));const s=e.geometry.clone(),r=e.matrixWorld.clone(),a=new y.Vector3().setFromMatrixPosition(e.matrixWorld);r.setPosition(0,0,0),s.applyMatrix4(r);const c=n.addGeometry(s,-1,a);return n.setGeometryInfo(c,t),s.dispose(),{batchedObjectId:n.id,batchId:c}}getMatchedLineBatches(e){if(ie(e).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}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){const t=new Set;let i=0;if(this.hasGeometry(e)){const n=e.geometry;if(Object.keys(n.attributes).forEach(s=>{const r=n.attributes[s],a=this.getAttributeArray(r);a&&!t.has(a.buffer)&&(i+=a.byteLength,t.add(a.buffer))}),n.index){const s=n.index.array;t.has(s.buffer)||(i+=s.byteLength,t.add(s.buffer))}}return i}getUnbatchedStats(){const e={count:0,geometrySize:0,byType:{line:0,mesh:0,point:0,other:0}};return this._unbatchedObjects.children.forEach(t=>{e.count+=1,e.geometrySize+=this.getGeometrySize(t),this.isLineObject(t)?e.byType.line+=1:t instanceof y.Mesh?e.byType.mesh+=1:t instanceof y.Points?e.byType.point+=1:e.byType.other+=1}),e}cloneUnbatchedObject(e){const t=e.clone();if(this.hasGeometry(e)&&this.hasGeometry(t)){const i=e.geometry.clone();i.applyMatrix4(e.matrixWorld),t.geometry=i}if(this.hasMaterial(e)&&this.hasMaterial(t)){t.material=e.material;const i=ie(e),n=ie(t);n.styleMaterialId=i.styleMaterialId??this.getMaterialId(e.material),n.bakedWorldMatrix=e.matrixWorld.toArray()}return t.position.set(0,0,0),t.rotation.set(0,0,0),t.scale.set(1,1,1),t.updateMatrix(),t.updateMatrixWorld(!0),t}cloneLineSegments2Geometry(e,t){const i=e.geometry,n=i.getAttribute("instanceStart"),s=i.getAttribute("instanceEnd"),r=n.count,a=new Float32Array(r*6);for(let l=0,h=0;l<r;l++)hi.fromBufferAttribute(n,l).applyMatrix4(t),ui.fromBufferAttribute(s,l).applyMatrix4(t),a[h++]=hi.x,a[h++]=hi.y,a[h++]=hi.z,a[h++]=ui.x,a[h++]=ui.y,a[h++]=ui.z;const c=new De.LineSegmentsGeometry;return c.setPositions(a),i.hasAttribute("instanceColorStart")&&(c.setAttribute("instanceColorStart",i.getAttribute("instanceColorStart").clone()),c.setAttribute("instanceColorEnd",i.getAttribute("instanceColorEnd").clone())),c.computeBoundingBox(),c.computeBoundingSphere(),c}disposeObject(e){e.removeFromParent(),this.hasGeometry(e)&&e.geometry.dispose(),e.children.forEach(t=>this.disposeObject(t))}clearHighlightGroup(e){[...e.children].forEach(t=>this.disposeHighlightObject(t)),e.clear()}disposeHighlightObject(e){if(this.hasMaterial(e)){const t=e.material;Array.isArray(t)?t.forEach(i=>i.dispose()):t.dispose()}this.hasGeometry(e)&&ni(e).disposeGeometryOnRemove&&e.geometry.dispose()}hasMaterial(e){return"material"in e}hasGeometry(e){return"geometry"in e}getAttributeArray(e){return"array"in e&&e.array?e.array:"data"in e&&e.data&&e.data.array?e.data.array:null}isLineObject(e){return e instanceof y.Line?!0:!!e.isLineSegments2}getMaterialId(e){var t;return Array.isArray(e)?((t=e[0])==null?void 0:t.id)??-1:e.id}};rt.INITIAL_LINE_VERTEX_CAPACITY=128,rt.INITIAL_LINE_INDEX_CAPACITY=256,rt.INITIAL_MESH_VERTEX_CAPACITY=128,rt.INITIAL_MESH_INDEX_CAPACITY=256,rt.INITIAL_POINT_VERTEX_CAPACITY=16;let Sc=rt;const hi=new y.Vector3,ui=new y.Vector3;class Os extends y.Object3D{constructor(e){super(),this._styleManager=e}get styleManager(){return this._styleManager}copy(e,t){return this._styleManager=e._styleManager,super.copy(e,t)}}class Y extends Os{constructor(e){super(e),this._box=new y.Box3}get box(){return this._box}set box(e){this._box.copy(e)}get basePoint(){return this._basePoint}set basePoint(e){e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e)}get objectId(){return this.userData.objectId}set objectId(e){this.userData.objectId=e}get ownerId(){return this.userData.ownerId}set ownerId(e){this.userData.ownerId=e}get layerName(){return this.userData.layerName}set layerName(e){this.userData.layerName=e}static flattenObject(e){const t=[],i=new y.Vector3,n=new y.Quaternion,s=new y.Vector3;function r(c,l){l.decompose(i,n,s),c.position.copy(i),c.quaternion.copy(n),c.scale.copy(s),c.updateMatrix()}function a(c,l){const h=[...c.children];for(const d of h){const p=$e(c),m=$e(d);!m.layerName&&p.layerName&&(m.layerName=p.layerName),d.children.length>0?a(d,l):(d.updateMatrixWorld(!0),d.visible=Ls(d),t.push({object:d,relativeMatrix:l.clone().multiply(d.matrixWorld)})),c.remove(d)}}e.updateMatrixWorld(!0),a(e,e.matrixWorld.clone().invert());for(const c of t){const{object:l,relativeMatrix:h}=c;r(l,h),e.add(l)}e.updateMatrixWorld(!0)}static disposeObject(e,t=!0){t&&e.removeFromParent(),(e instanceof y.Mesh||e instanceof y.Line||e instanceof y.Points)&&e.geometry&&e.geometry.dispose(),(e instanceof y.Mesh||e instanceof y.Line||e instanceof y.Points)&&(Array.isArray(e.material)?e.material:[e.material]).forEach(i=>{var n,s,r,a,c,l,h,d;i.dispose(),(n=i.map)==null||n.dispose(),(s=i.envMap)==null||s.dispose(),(r=i.lightMap)==null||r.dispose(),(a=i.bumpMap)==null||a.dispose(),(c=i.normalMap)==null||c.dispose(),(l=i.roughnessMap)==null||l.dispose(),(h=i.metalnessMap)==null||h.dispose(),(d=i.alphaMap)==null||d.dispose()}),e.children.forEach(i=>this.disposeObject(i)),"geometry"in e&&(e.geometry=null),"material"in e&&(e.material=null),e.children=[]}flatten(){Y.flattenObject(this)}dispose(){Y.disposeObject(this)}async draw(){}addChild(e){this.add(e)}applyMatrix(e){const t=_s.createMatrix4(e);this.applyMatrix4(t),this.updateMatrixWorld(!0),this._box.applyMatrix4(t)}bakeTransformToChildren(){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.clone();this.children.forEach(t=>{t.updateMatrix(),t.applyMatrix4(e)}),this.position.set(0,0,0),this.rotation.set(0,0,0),this.scale.set(1,1,1),this.updateMatrix()}highlight(){this.highlightObject(this)}highlightObject(e){if("material"in e){const t=e.material,i=$e(e);if(i.originalMaterial==null){const n=We.cloneMaterial(t);We.setMaterialColor(n),i.originalMaterial=t,e.material=n}}else e.children.length>0&&e.children.forEach(t=>{this.highlightObject(t)})}unhighlight(){this.unhighlightObject(this)}fastDeepClone(){const e=new Y(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];if(n instanceof Y){t.add(n.fastDeepClone());continue}const s=n.clone(!1);"geometry"in s&&(s.geometry=s.geometry.clone()),t.add(s)}}unhighlightObject(e){if("material"in e){const t=e.material,i=$e(e);e.material=i.originalMaterial,delete i.originalMaterial,Array.isArray(t)?t.forEach(n=>n.dispose()):t instanceof y.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 a=0,c=0;a<t;a++)r[c]=i,r[c+1]=n,r[c+2]=s,c+=3;return r}}class Ye extends Y{constructor(e,t){super(t),this._boxes=[],e.forEach(s=>{if(Array.isArray(s)){const r=new Y(t);this.add(r),this.box.union(r.box)}else this.add(s),this.box.union(s.box);this.storeBoxes(s)}),this.flatten();let i=!1;const n=this.children;for(let s=0;s<n.length;++s){const r=n[s];if(r.userData.layerName!=null&&r.userData.layerName!=="0"){i=!0;break}}this._isOnTheSameLayer=!i}get isOnTheSameLayer(){return this._isOnTheSameLayer}get boxes(){return this._boxes}applyMatrix(e){const t=_s.createMatrix4(e);this._boxes.forEach(i=>this.applyMatrixToEntityBox(i,t)),super.applyMatrix(e)}copy(e,t){return this._isOnTheSameLayer=e._isOnTheSameLayer,this._boxes=[],e.boxes.forEach(i=>this._boxes.push({...i})),super.copy(e,t)}fastDeepClone(){const e=new Ye([],this.styleManager);return e.copy(this,!1),this.copyGeometry(this,e),e}storeBoxes(e){e instanceof Ye?e._boxes.forEach(t=>this._boxes.push(t)):e instanceof Y&&this._boxes.push({minX:e.box.min.x,minY:e.box.min.y,maxX:e.box.max.x,maxY:e.box.max.y,id:e.objectId})}applyMatrixToEntityBox(e,t){const i=[new y.Vector3(e.minX,e.minY,0),new y.Vector3(e.maxX,e.minY,0),new y.Vector3(e.maxX,e.maxY,0),new y.Vector3(e.minX,e.maxY,0)];for(const c of i)c.applyMatrix4(t);let n=1/0,s=1/0,r=-1/0,a=-1/0;for(const c of i)n=Math.min(n,c.x),s=Math.min(s,c.y),r=Math.max(r,c.x),a=Math.max(a,c.y);e.minX=n,e.minY=s,e.maxX=r,e.maxY=a}}const Ac="default";class Fs{constructor(e){this.scene=e,this.htmlGroup=new y.Group,this.htmlGroup.name="Html_Transient_Group",this.scene.add(this.htmlGroup),this.entries=new Map}add(e,t,i,n=Ac){this.remove(e);const s=new fs.CSS2DObject(t);s.position.set(i.x,i.y,i.z??0),this.entries.set(e,{object:s,layer:n}),this.htmlGroup.add(s)}updatePosition(e,t){const i=this.entries.get(e);i&&i.object.position.set(t.x,t.y,t.z??0)}remove(e){const t=this.entries.get(e);t&&(this.htmlGroup.remove(t.object),t.object.element.remove(),this.entries.delete(e))}clear(e){if(e==null){for(const t of this.entries.values())this.htmlGroup.remove(t.object),t.object.element.remove();this.entries.clear()}else for(const[t,i]of this.entries)i.layer===e&&(this.htmlGroup.remove(i.object),i.object.element.remove(),this.entries.delete(t))}has(e){return this.entries.has(e)}get(e){var t;return(t=this.entries.get(e))==null?void 0:t.object.element}setVisible(e,t){if(t==null)this.htmlGroup.visible=e;else for(const i of this.entries.values())i.layer===t&&(i.object.visible=e)}dispose(){this.clear(),this.scene.remove(this.htmlGroup)}}class Rs{constructor(e){this.scene=e,this.transientGroup=new y.Group,this.transientGroup.name="Transient_Object_Group",this.scene.add(this.transientGroup),this.entities=new Map}clear(){for(const e of this.entities.values())e.dispose();this.entities.clear(),this.transientGroup.clear()}add(e){const t=e.objectId,i=this.entities.get(t);i&&(this.transientGroup.remove(i),i.dispose()),this.entities.set(t,e),this.transientGroup.add(e)}update(e){const t=this.entities.get(e.objectId);t&&(this.transientGroup.remove(t),t.dispose()),this.entities.set(e.objectId,e),this.transientGroup.add(e)}remove(e){const t=this.entities.get(e);t&&(this.transientGroup.remove(t),Y.disposeObject(t),this.entities.delete(e))}get(e){return this.entities.get(e)}has(e){return this.entities.has(e)}setVisible(e){this.transientGroup.visible=e}dispose(){this.clear(),this.scene.remove(this.transientGroup)}}class Cc{constructor(e){this.unsupportedTextStyles={},this._styleManager=e}getMeshBasicMaterial(e){const t=dn.createTraitsForMText(e);return this._styleManager.getMTextFillMaterial(t)}getLineBasicMaterial(e){const t=dn.createTraitsForMText(e);return this._styleManager.getLineMaterial(t,!0)}}const js=class ei{constructor(){}static getInstance(){return ei._instance||(ei._instance=new ei),ei._instance}overrideStyleManager(e){this._styleManager=e}setFontUrl(e){this._fontUrl=e,this.applyFontUrl()}setRenderMode(e){this._renderMode=e,this._renderer&&(this._renderer.setDefaultMode(e),this.applyFontUrl())}async asyncRenderMText(e,t,i=B.createDefaultColorSettings()){if(!this._renderer)throw new Error("AcTrMTextRenderer not initialized!");return await this._renderer.asyncRenderMText(e,t,i)}syncRenderMText(e,t,i=B.createDefaultColorSettings()){if(this.ensureRendererCreated(),!this._renderer)throw new Error("AcTrMTextRenderer not initialized!");return this._renderer.syncRenderMText(e,t,i)}initialize(e){if(this._workerUrl=e,this._renderer=new B.UnifiedRenderer("worker",{workerUrl:e}),this._renderMode&&this._renderer.setDefaultMode(this._renderMode),this.applyFontUrl(),this._styleManager){const t=new Cc(this._styleManager);this._renderer.setStyleManager(t)}}dispose(){this._renderer&&(this._renderer.destroy(),this._renderer=void 0)}ensureRendererCreated(){!this._renderer&&this._workerUrl&&this.initialize(this._workerUrl)}applyFontUrl(){this._renderer&&this._fontUrl&&this._renderer.setFontUrl(this._fontUrl)}};js._instance=null;let Xe=js;class Pc extends B.DefaultFontLoader{onFontUrlChanged(e){Xe.getInstance().setFontUrl(e)}}class _c extends Y{constructor(e,t,i){super(i);const n=URL.createObjectURL(e),s=new y.TextureLoader().load(n,()=>URL.revokeObjectURL(n),void 0,()=>URL.revokeObjectURL(n));s.colorSpace=y.SRGBColorSpace;const r=new y.MeshBasicMaterial({side:y.DoubleSide,map:s}),a=new y.Shape(t.boundary),c=new y.ShapeGeometry(a);this.generateUVs(c);const l=new y.Mesh(c,r);ie(l).noBatch=!0,this.add(l)}generateUVs(e){const t=e.attributes.position.array,i=new Float32Array(t.length/3*2),n=Math.min(...t.filter((h,d)=>d%3===0)),s=Math.max(...t.filter((h,d)=>d%3===0)),r=Math.min(...t.filter((h,d)=>d%3===1)),a=Math.max(...t.filter((h,d)=>d%3===1)),c=s-n,l=a-r;for(let h=0;h<t.length;h+=3){const d=t[h],p=t[h+1];i[h/3*2]=(d-n)/c,i[h/3*2+1]=(p-r)/l}e.setAttribute("uv",new y.BufferAttribute(i,2))}}class Lc extends Y{constructor(e,t,i,n=!1){super(i);const s=this.styleManager.getLineMaterial(t,n),r=e.length,a=this.computeLocalOrigin(e);if(s instanceof xt.LineMaterial){const p=new Float32Array((r-1)*6);for(let w=0,x=0;w<r-1;w++){const b=e[w],v=e[w+1];p[x++]=b.x-a.x,p[x++]=b.y-a.y,p[x++]=(b.z??0)-a.z,p[x++]=v.x-a.x,p[x++]=v.y-a.y,p[x++]=(v.z??0)-a.z}const m=new De.LineSegmentsGeometry;m.setPositions(p),m.computeBoundingBox(),m.computeBoundingSphere(),this.geometry=m,this.setBoundingBox(m,a);const f=new Ue.LineSegments2(m,s);f.position.set(a.x,a.y,a.z),ie(f).styleMaterialId=s.id,this.add(f);return}const c=new Float32Array(r*3),l=r*2>65535?new Uint32Array(r*2):new Uint16Array(r*2);for(let p=0,m=0;p<r;p++){const f=e[p];c[m++]=f.x-a.x,c[m++]=f.y-a.y,c[m++]=(f.z??0)-a.z}for(let p=0,m=0;p<r-1;p++)l[m++]=p,l[m++]=p+1;const h=new y.BufferGeometry;h.setAttribute("position",new y.BufferAttribute(c,3)),h.setIndex(new y.BufferAttribute(l,1)),this.setBoundingBox(h,a),this.geometry=h;const d=new y.LineSegments(h,s);d.position.set(a.x,a.y,a.z),Pt.computeLineDistances(d),this.add(d)}setBoundingBox(e,t){e.computeBoundingBox();const i=e.boundingBox.clone();i.translate(t),this.box=i}computeLocalOrigin(e){const t=new y.Box3;for(let i=0;i<e.length;i++){const n=e[i];t.expandByPoint(Tc.set(n.x,n.y,n.z??0))}return t.getCenter(new y.Vector3)}}const Tc=new y.Vector3;class Ic extends Y{constructor(e,t,i,n,s){super(s);const r=this.styleManager.getLineMaterial(n);if(r instanceof xt.LineMaterial){const l=Math.floor(i.length/2),h=new Float32Array(l*6),d=new y.Box3;for(let f=0;f<e.length;f+=t)d.expandByPoint(Ec.set(e[f],e[f+1],e[f+2]??0));for(let f=0,w=0;f<l;f++){const x=i[f*2],b=i[f*2+1],v=x*t,C=b*t;h[w++]=e[v],h[w++]=e[v+1],h[w++]=e[v+2]??0,h[w++]=e[C],h[w++]=e[C+1],h[w++]=e[C+2]??0}const p=new De.LineSegmentsGeometry;p.setPositions(h),p.computeBoundingBox(),p.computeBoundingSphere(),this.box.copy(d);const m=new Ue.LineSegments2(p,r);ie(m).styleMaterialId=r.id,this.add(m);return}const a=new y.BufferGeometry;a.setAttribute("position",new y.BufferAttribute(e,t)),a.setIndex(new y.BufferAttribute(i,1)),a.computeBoundingBox(),this.box=a.boundingBox;const c=new y.LineSegments(a,r);Pt.computeLineDistances(c),this.add(c)}}const Ec=new y.Vector3,Ns=new y.Box3,wn=new y.Vector3;class kc extends Y{constructor(e,t,i,n,s=!1){super(n),this._text=e,this._style={...i},this._colorSettings={layer:t.layer,color:un.toMTextColor(t.color),byLayerColor:16777215,byBlockColor:16777215},s||this.syncDraw()}async syncDraw(){const e=Xe.getInstance();if(e)try{const t=this._style,i=this._text;this._mtext=e.syncRenderMText(i,t,this._colorSettings),this.attachMText(this._mtext)}catch(t){u.log.info(`Failed to render mtext '${this._text.text}' with the following error:
|
|
2
|
+
`,t)}}async draw(){const e=Xe.getInstance();if(e)try{const t=this._style,i=this._text,n=await e.asyncRenderMText(i,t,this._colorSettings);this._mtext=n,this.attachMText(this._mtext)}catch(t){u.log.info(`Failed to render mtext '${this._text.text}' with the following error:
|
|
3
|
+
`,t)}}raycast(e,t){var i;const n=t.length;(i=this._mtext)==null||i.raycast(e,t),!(t.length>n||this.box.isEmpty())&&(Ns.copy(this.box).applyMatrix4(this.matrixWorld),e.ray.intersectBox(Ns,wn)&&t.push({distance:e.ray.origin.distanceTo(wn),point:wn.clone(),object:this,face:null,faceIndex:void 0,uv:void 0}))}attachMText(e){this.add(e),this.flatten(),this.traverse(t=>{ie(t).bboxIntersectionCheck=!0}),this.updateSelectionBox(e)}updateSelectionBox(e){const t=this.computeGeometryBox();if(t.isEmpty()){this.box=e.box;return}if(!e.box.isEmpty()&&e.box.intersectsBox(t)){this.box=t.clone().union(e.box);return}this.box=t}computeGeometryBox(){const e=new y.Box3,t=new y.Box3;return this.updateMatrixWorld(!0),this.traverse(i=>{if(!this.hasGeometry(i))return;const n=i.geometry;n.boundingBox==null&&n.computeBoundingBox(),n.boundingBox!=null&&(i.updateMatrixWorld(!0),t.copy(n.boundingBox).applyMatrix4(i.matrixWorld),e.union(t))}),e}hasGeometry(e){return"geometry"in e&&e.geometry instanceof y.BufferGeometry}}const Bc=new y.Vector3;class Dc extends Y{constructor(e,t,i,n){super(n);const s=Me.instance.create(i.displayMode,e);this.isShowPoint=s.point!=null;const r=s.point??new y.BufferGeometry().setFromPoints([Bc.copy(e)]);r.computeBoundingBox(),r.boundingBox&&this.box.union(r.boundingBox);const a=this.styleManager.getPointsMaterial(t),c=new y.Points(r,a);if(ie(c).bboxIntersectionCheck=!0,c.visible=this.isShowPoint,this.add(c),s.line){const l=s.line;l.computeBoundingBox(),l.boundingBox&&this.box.union(l.boundingBox);const h=this.styleManager.getLineMaterial(t,!0),d=new y.LineSegments(l,h),p=ie(d);p.bboxIntersectionCheck=!0,p.isPoint=!0,p.position={x:e.x,y:e.y,z:e.z},this.add(d)}}}function bn(o){return o.map(e=>new y.Vector2(e.x,e.y))}function Mc(o){if(!o)return!1;const e=o.getAttribute("position");return!!e&&e.count>0}class Oc extends Y{constructor(e,t,i){super(i);const n=e.getPoints(100),s=e.buildHierarchy(),r=n.some(l=>l.length>=3),a=[];this.buildHatchGeometry(n,s,a);let c;if(a.length===1?c=a[0]:a.length>1&&(c=Ka.mergeGeometries(a)??void 0),c&&Mc(c)){c.computeBoundingBox(),this.box=c.boundingBox,this.addGradientPositionAttribute(c,t);const l={minX:this.box.min.x,minY:this.box.min.y,maxX:this.box.max.x,maxY:this.box.max.y},h=this.styleManager.getFillMaterial(t,void 0,l),d=new y.Mesh(c,h);this.isPatternedHatch(t)&&(ie(d).noBatch=!0),this.add(d)}else r&&u.log.warn("Failed to convert hatch boundaries!")}isPatternedHatch(e){var t;const i=e.fillType;return!i.gradient&&!!((t=i.definitionLines)!=null&&t.length)}addGradientPositionAttribute(e,t){if(!t.fillType.gradient||!e.boundingBox)return;const i=e.getAttribute("position");if(!i)return;const n=e.boundingBox,s=(n.min.x+n.max.x)*.5,r=(n.min.y+n.max.y)*.5,a=Math.max((n.max.x-n.min.x)*.5,1e-9),c=Math.max((n.max.y-n.min.y)*.5,1e-9),l=new Float32Array(i.count*2);for(let h=0;h<i.count;h++)l[h*2]=(i.getX(h)-s)/a,l[h*2+1]=(i.getY(h)-r)/c;e.setAttribute("gradientPosition",new y.BufferAttribute(l,2))}buildHatchGeometry(e,t,i){if(t.children.length===0)return;const n=[],s=new Map;t.children.forEach(c=>{c.children.length===0?n.push(c.index):s.set(c.index,c.children.map(l=>l.index))});const r=c=>{try{const l=new y.ShapeGeometry(c);l.hasAttribute("uv")&&l.deleteAttribute("uv"),l.hasAttribute("normal")&&l.deleteAttribute("normal"),i.push(l)}catch{u.log.warn(`Triangulate shape error: ${c.getPoints().map(l=>l.toArray()).toString()}`)}};n.forEach(c=>{const l=e[c];if(l.length<3)return;const h=new y.Shape(bn(l));r(h)});const a=c=>c.map(l=>l.toArray());for(const c of s){const l=e[c[0]];if(l.length<3)continue;const h=new y.Shape(bn(l));let d={regions:[],inverted:!1};const p=this.findIntersectHole(e,c[1]);p.forEach(f=>{let w={segments:[],inverted:!1},x=1e-6;try{f.forEach((b,v)=>{x=Math.min(e[b][0].relativeEps(),1e-6);const C=new Ss(new ws(x));if(v===0)w=C.segments({regions:[a(e[b])],inverted:!1});else{const P=C.segments({regions:[a(e[b])],inverted:!1}),L=C.combine(w,P);d=C.polygon(C.selectUnion(L)),d.regions.length>0?d.regions.forEach(M=>{if(M.length===0)return;const k=M.map(E=>new y.Vector2(E[0],E[1]));h.holes.push(new y.Path(k))}):u.log.warn("mergedHoles.regions is empty!")}})}catch(b){u.log.warn(`Polybool error: ${b}, epsilon is ${x}`)}});const m=p.flat(2);for(let f=0;f<c[1].length;f++){const w=c[1][f];if(!m.includes(w)){const x=e[w];if(x.length<3)continue;h.holes.push(new y.Path(bn(x)))}}r(h)}t.children.forEach(c=>{c.children.forEach(l=>{this.buildHatchGeometry(e,l,i)})})}findIntersectHole(e,t){const i=t.length,n=[];for(let s=0;s<i;s++){const r=e[t[s]];let a=!1;const c=[];for(let l=s+1;l<i;l++){const h=e[t[l]];u.AcGeGeometryUtil.isPolygonIntersect(r,h)&&(a=!0,c.push(t[l]))}a&&(c.push(t[s]),n.push(c))}return n}}const qe=0,zs=16777215,Vs=16777215,Gs=0,Fc=128;function Lt(o){const e=o>>16&255,t=o>>8&255,i=o&255;return .299*e+.587*t+.114*i>Fc}function vn(o){return o?Gs:Vs}function xn(o){return vn(Lt(o))}const Ks=class{constructor(e){this.cache={},this.keyToTraits={},this.options=e}getMaterial(e,t){const i=this.buildKey(e,t);return this.keyToTraits[i]||(this.keyToTraits[i]={...u.deepClone(e),...t}),this.cache[i]?this.cache[i]:this.createMaterial(i,e,t)}updateLayerMaterial(e,t){const i={};for(const n of Object.keys(this.cache)){const s=this.cache[n],r=Ce(s);if(!(r.layer===e&&Cs(r)))continue;const a=this.keyToTraits[n];if(!a)continue;const c=this.resolveByLayerBindings(a,s),l=u.deepClone(a);this.applyInheritedLayerTraits(l,t,c),t.layer!=null&&(l.layer=t.layer);const h=this.buildKey(l,l),d=s.id;s.dispose(),delete this.cache[n],delete this.keyToTraits[n];const p=this.createMaterial(h,l,l,c);this.keyToTraits[h]=l,i[d]=p}return i}changeForeground(e){for(const t of Object.keys(this.cache)){const i=this.cache[t];Ce(i).isForeground!==!0||!this.keyToTraits[t]||We.setMaterialColor(i,new y.Color(e))}}changeBackground(e){for(const t of Object.keys(this.cache)){const i=this.cache[t];Ce(i).isBackgroundFill!==!0||!this.keyToTraits[t]||We.setMaterialColor(i,new y.Color(e))}}dispose(){Object.values(this.cache).forEach(e=>e.dispose()),this.cache={},this.keyToTraits={}}getBackSideVariant(e){return e}getLayerBoundMaterial(e,t,i){const n=Ce(e).materialKey;if(!n)return;const s=this.keyToTraits[n];if(!s)return;if(s.layer===t&&!i)return e;const r={...u.deepClone(s),layer:t},a=this.resolveByLayerBindings(s,e);this.applyInheritedLayerTraits(r,i,a);const c=this.buildKey(r,r);return this.cache[c]?this.cache[c]:(this.keyToTraits[c]=r,this.createMaterial(c,r,r,a))}applyInheritedLayerTraits(e,t,i){if(!t)return;const n=(i==null?void 0:i.isByLayerColor)===!0,s=(i==null?void 0:i.isByLayerLineType)===!0,r=(i==null?void 0:i.isByLayerLineWeight)===!0,a=(i==null?void 0:i.isByLayerTransparency)===!0;if(n){if(t.rgbColor!=null)e.rgbColor=t.rgbColor;else if(t.color){const c=t.color.RGB;c!=null&&(e.rgbColor=c)}}s&&t.lineType&&(e.lineType=u.deepClone(t.lineType)),r&&t.lineWeight!=null&&(e.lineWeight=t.lineWeight),a&&t.transparency&&(e.transparency=u.deepClone(t.transparency))}resolveByLayerBindings(e,t){var i;const n=t?Ce(t):void 0,s=((i=e.transparency)==null?void 0:i.isByLayer)===!0;return{isByLayerColor:(n==null?void 0:n.isByLayerColor)??e.color.isByLayer===!0,isByLayerLineType:(n==null?void 0:n.isByLayerLineType)??e.lineType.type==="ByLayer",isByLayerLineWeight:(n==null?void 0:n.isByLayerLineWeight)??e.lineWeight===u.AcGiLineWeight.ByLayer,isByLayerTransparency:(n==null?void 0:n.isByLayerTransparency)??s}}createMaterial(e,t,i,n){const s=this.createMaterialImpl(t,i),r=this.shouldTrackForeground(t,i),a=this.shouldTrackBackground(t,i);r&&We.setMaterialColor(s,new y.Color(xn(this.options.currentBackgroundColor)));const c=n??this.resolveByLayerBindings(t);return ln(s,{layer:t.layer,isByLayerColor:c.isByLayerColor,isByLayerLineType:c.isByLayerLineType,isByLayerLineWeight:c.isByLayerLineWeight,isByLayerTransparency:c.isByLayerTransparency,isForeground:r,isBackgroundFill:a,drawOrder:t.drawOrder??0,materialKey:e}),this.cache[e]=s,s}hasByLayerKeyTraits(e){return e.color.isByLayer||e.lineType.type==="ByLayer"}shouldTrackForeground(e,t){return e.color.isForeground}shouldTrackBackground(e,t){return!1}buildDrawOrderSuffix(e){return e.drawOrder===0?"":`_draw_${e.drawOrder??0}`}};Ks.CameraZoomUniform={value:1};let ot=Ks;const Rc={LINEAR:0,CYLINDER:1,INVCYLINDER:2,SPHERICAL:3,INVSPHERICAL:4,HEMISPHERICAL:5,INVHEMISPHERICAL:6,CURVED:7,INVCURVED:8};function jc(o,e,t,i=y.FrontSide){const n=new y.Color(o.startColor??t.getHex()),s=new y.Color(o.endColor??zc(n,o.oneColorMode,o.shadeTintValue)),r=Rc[(o.name||"LINEAR").trim().toUpperCase()]??0;return Nc({startColor:n.getHex(),endColor:s.getHex(),angle:o.angle??0,shift:o.shift??0,gradientType:r},i)}function Nc(o,e=y.FrontSide){const t={u_startColor:{value:new y.Color(o.startColor)},u_endColor:{value:new y.Color(o.endColor)},u_angle:{value:o.angle},u_shift:{value:o.shift},u_gradientType:{value:o.gradientType}},i=`
|
|
4
|
+
attribute vec2 gradientPosition;
|
|
35
5
|
|
|
36
|
-
|
|
37
|
-
display: flex;
|
|
38
|
-
align-items: center;
|
|
39
|
-
gap: 4px;
|
|
40
|
-
background: var(--ml-ui-bg, rgba(0, 0, 0, 0.06));
|
|
41
|
-
border-radius: 4px;
|
|
42
|
-
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.08));
|
|
43
|
-
height: 100%;
|
|
44
|
-
}
|
|
6
|
+
varying vec2 v_gradientPosition;
|
|
45
7
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
display: inline-flex;
|
|
50
|
-
align-items: center;
|
|
51
|
-
justify-content: center;
|
|
52
|
-
font-weight: 700;
|
|
53
|
-
color: var(--ml-ui-text, #222);
|
|
54
|
-
font-size: 12px;
|
|
55
|
-
background: transparent;
|
|
56
|
-
cursor: pointer;
|
|
57
|
-
padding: 0;
|
|
58
|
-
}
|
|
8
|
+
#include <clipping_planes_pars_vertex>
|
|
9
|
+
void main() {
|
|
10
|
+
v_gradientPosition = gradientPosition;
|
|
59
11
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
12
|
+
#include <begin_vertex>
|
|
13
|
+
#include <project_vertex>
|
|
14
|
+
#include <clipping_planes_vertex>
|
|
15
|
+
}`,n=`
|
|
16
|
+
precision highp float;
|
|
63
17
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
align-items: center;
|
|
70
|
-
justify-content: center;
|
|
71
|
-
border-radius: 3px;
|
|
72
|
-
background: transparent;
|
|
73
|
-
border: none;
|
|
74
|
-
cursor: pointer;
|
|
75
|
-
font-size: 16px;
|
|
76
|
-
color: var(--ml-ui-text, #222);
|
|
77
|
-
padding: 0;
|
|
78
|
-
}
|
|
18
|
+
uniform vec3 u_startColor;
|
|
19
|
+
uniform vec3 u_endColor;
|
|
20
|
+
uniform float u_angle;
|
|
21
|
+
uniform float u_shift;
|
|
22
|
+
uniform int u_gradientType;
|
|
79
23
|
|
|
80
|
-
|
|
81
|
-
transform: rotate(180deg);
|
|
82
|
-
transform-origin: center;
|
|
83
|
-
}
|
|
24
|
+
varying vec2 v_gradientPosition;
|
|
84
25
|
|
|
85
|
-
|
|
86
|
-
display: flex;
|
|
87
|
-
align-items: center;
|
|
88
|
-
justify-content: center;
|
|
89
|
-
background: var(--ml-ui-bg, rgba(0, 0, 0, 0.06));
|
|
90
|
-
border-radius: 4px;
|
|
91
|
-
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.08));
|
|
92
|
-
height: 100%;
|
|
93
|
-
}
|
|
26
|
+
#include <clipping_planes_pars_fragment>
|
|
94
27
|
|
|
95
|
-
|
|
96
|
-
display: flex;
|
|
97
|
-
align-items: center;
|
|
98
|
-
flex: 1;
|
|
99
|
-
min-width: 0;
|
|
100
|
-
overflow: hidden;
|
|
101
|
-
color: var(--ml-ui-text-muted, #333);
|
|
102
|
-
height: 100%;
|
|
103
|
-
}
|
|
28
|
+
const float EPSILON = 1e-6;
|
|
104
29
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
min-width: 0;
|
|
111
|
-
max-width: calc(100% - 80px);
|
|
112
|
-
overflow: hidden;
|
|
113
|
-
user-select: none;
|
|
114
|
-
margin-right: 4px;
|
|
115
|
-
line-height: 1;
|
|
116
|
-
font-family: "Microsoft YaHei", "PingFang SC", "Segoe UI", Arial, sans-serif;
|
|
117
|
-
font-size: 12px;
|
|
118
|
-
letter-spacing: 0;
|
|
119
|
-
word-spacing: 0;
|
|
120
|
-
}
|
|
30
|
+
vec2 rotate(vec2 samplePos, float angle) {
|
|
31
|
+
float s = sin(angle);
|
|
32
|
+
float c = cos(angle);
|
|
33
|
+
return vec2(c * samplePos.x - s * samplePos.y, c * samplePos.y + s * samplePos.x);
|
|
34
|
+
}
|
|
121
35
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
height: 100%;
|
|
126
|
-
border: none;
|
|
127
|
-
outline: none;
|
|
128
|
-
background: transparent;
|
|
36
|
+
float saturate(float value) {
|
|
37
|
+
return clamp(value, 0.0, 1.0);
|
|
38
|
+
}
|
|
129
39
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
40
|
+
float getGradientFactor(vec2 localPos) {
|
|
41
|
+
vec2 shiftedPos = localPos - vec2(clamp(u_shift, -1.0, 1.0), 0.0);
|
|
42
|
+
float linear = saturate(shiftedPos.x * 0.5 + 0.5);
|
|
43
|
+
float cylinder = saturate(1.0 - abs(shiftedPos.x));
|
|
44
|
+
float radial = saturate(length(shiftedPos));
|
|
45
|
+
float curved = smoothstep(0.0, 1.0, linear);
|
|
46
|
+
float hemi = saturate(1.0 - length(shiftedPos - vec2(0.0, -1.0)) * 0.5);
|
|
137
47
|
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
color: var(--ml-ui-text-muted, #333);
|
|
48
|
+
if (u_gradientType == 1) {
|
|
49
|
+
return cylinder;
|
|
141
50
|
}
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
display: inline-block;
|
|
145
|
-
background: var(--ml-ui-bg, #f7f7f7);
|
|
146
|
-
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.06));
|
|
147
|
-
padding: 1px 4px;
|
|
148
|
-
border-radius: 3px;
|
|
149
|
-
margin: 0 1px;
|
|
150
|
-
cursor: pointer;
|
|
151
|
-
font-size: 12px;
|
|
152
|
-
line-height: 1.1;
|
|
153
|
-
letter-spacing: 0;
|
|
154
|
-
word-spacing: 0;
|
|
51
|
+
if (u_gradientType == 2) {
|
|
52
|
+
return 1.0 - cylinder;
|
|
155
53
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
background: var(--ml-ui-border, #eaeaea);
|
|
54
|
+
if (u_gradientType == 3) {
|
|
55
|
+
return 1.0 - radial;
|
|
159
56
|
}
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
position: absolute;
|
|
163
|
-
bottom: 100%;
|
|
164
|
-
left: 0;
|
|
165
|
-
transform: translate(0, 0);
|
|
166
|
-
max-height: 220px;
|
|
167
|
-
overflow-y: auto;
|
|
168
|
-
background: var(--ml-ui-bg, #333);
|
|
169
|
-
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.5));
|
|
170
|
-
box-shadow: var(--ml-ui-shadow, 0 6px 18px rgba(0, 0, 0, 0.35));
|
|
171
|
-
border-radius: 4px;
|
|
172
|
-
padding: 6px 0;
|
|
173
|
-
color: var(--ml-ui-text, #fff);
|
|
174
|
-
z-index: 3;
|
|
57
|
+
if (u_gradientType == 4) {
|
|
58
|
+
return radial;
|
|
175
59
|
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
padding: 8px 14px;
|
|
179
|
-
cursor: pointer;
|
|
180
|
-
color: var(--ml-ui-text, #fff);
|
|
181
|
-
font-size: 14px;
|
|
60
|
+
if (u_gradientType == 5) {
|
|
61
|
+
return hemi;
|
|
182
62
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
background: var(--ml-ui-border, #444);
|
|
63
|
+
if (u_gradientType == 6) {
|
|
64
|
+
return 1.0 - hemi;
|
|
186
65
|
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
position: absolute;
|
|
190
|
-
bottom: 100%;
|
|
191
|
-
left: 0;
|
|
192
|
-
transform: translate(0, 0);
|
|
193
|
-
max-height: 340px;
|
|
194
|
-
overflow-y: auto;
|
|
195
|
-
background: var(--ml-ui-bg, #333);
|
|
196
|
-
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.5));
|
|
197
|
-
box-shadow: var(--ml-ui-shadow, 0 6px 18px rgba(0, 0, 0, 0.35));
|
|
198
|
-
border-radius: 4px;
|
|
199
|
-
padding: 6px 0;
|
|
200
|
-
font-family: "Microsoft YaHei", Arial, sans-serif;
|
|
201
|
-
color: var(--ml-ui-text, #fff);
|
|
202
|
-
font-size: 14px;
|
|
203
|
-
white-space: pre-wrap;
|
|
204
|
-
line-height: 1.35;
|
|
205
|
-
z-index: 4;
|
|
66
|
+
if (u_gradientType == 7) {
|
|
67
|
+
return curved;
|
|
206
68
|
}
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
padding: 4px 6px;
|
|
210
|
-
color: var(--ml-ui-text, #fff);
|
|
69
|
+
if (u_gradientType == 8) {
|
|
70
|
+
return 1.0 - curved;
|
|
211
71
|
}
|
|
72
|
+
return linear;
|
|
73
|
+
}
|
|
212
74
|
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
}
|
|
75
|
+
void main() {
|
|
76
|
+
#include <clipping_planes_fragment>
|
|
216
77
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
width: 100%;
|
|
220
|
-
}
|
|
78
|
+
vec2 localPos = rotate(v_gradientPosition, -u_angle);
|
|
79
|
+
float factor = saturate(getGradientFactor(localPos));
|
|
221
80
|
|
|
222
|
-
.
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
display: flex;
|
|
227
|
-
flex-direction: column;
|
|
228
|
-
align-items: flex-start;
|
|
229
|
-
gap: 4px;
|
|
230
|
-
pointer-events: none;
|
|
231
|
-
z-index: 2;
|
|
232
|
-
}
|
|
81
|
+
gl_FragColor = vec4(mix(u_startColor, u_endColor, factor), 1.0);
|
|
82
|
+
#include <colorspace_fragment>
|
|
83
|
+
}`;return new y.ShaderMaterial({uniforms:t,vertexShader:i,fragmentShader:n,side:e})}function zc(o,e=!1,t=0){if(!e)return 16777215;const i=Math.abs(y.MathUtils.clamp(t,-1,1))||.5,n=t<0?new y.Color(0):new y.Color(16777215);return o.clone().lerp(n,i).getHex()}function Us(o){return o?{minX:di(o.minX,0),minY:di(o.minY,0),maxX:di(o.maxX,1),maxY:di(o.maxY,1)}:{minX:0,minY:0,maxX:1,maxY:1}}function di(o,e){return Number.isFinite(o)?o:e}function Vc(o,e,t,i,n=0,s=y.FrontSide){const r=Math.max(2,...o.map(h=>h.dashLengths.length)),a={u_cameraZoom:t,u_patternLines:{value:o},u_patternAngle:{value:e},u_color:{value:i}},c=`
|
|
84
|
+
varying vec3 v_pos;
|
|
233
85
|
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
text-overflow: ellipsis;
|
|
239
|
-
white-space: nowrap;
|
|
240
|
-
color: rgba(230, 233, 238, 0.95);
|
|
241
|
-
background: rgba(45, 48, 54, 0.88);
|
|
242
|
-
border-radius: 4px;
|
|
243
|
-
padding: 4px 8px;
|
|
244
|
-
font-family: "Microsoft YaHei", "PingFang SC", "Segoe UI", Arial, sans-serif;
|
|
245
|
-
font-size: 12px;
|
|
246
|
-
line-height: 1.25;
|
|
247
|
-
letter-spacing: 0;
|
|
248
|
-
word-spacing: 0;
|
|
249
|
-
}
|
|
86
|
+
#include <clipping_planes_pars_vertex>
|
|
87
|
+
void main() {
|
|
88
|
+
//vec4 worldPosition = modelMatrix * vec4(position, 1.0);
|
|
89
|
+
v_pos = position;
|
|
250
90
|
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
91
|
+
#include <begin_vertex>
|
|
92
|
+
#include <project_vertex>
|
|
93
|
+
#include <clipping_planes_vertex>
|
|
94
|
+
}`,l=`
|
|
95
|
+
precision highp float;
|
|
96
|
+
uniform mat4 modelMatrix;
|
|
97
|
+
uniform float u_cameraZoom;
|
|
98
|
+
uniform vec3 u_color;
|
|
99
|
+
varying vec3 v_pos;
|
|
254
100
|
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
101
|
+
struct PatternLine {
|
|
102
|
+
float angle;
|
|
103
|
+
vec2 base;
|
|
104
|
+
vec2 offset;
|
|
105
|
+
float dashLengths[MAX_PATTERN_SEGMENT_COUNT];
|
|
106
|
+
float patternLength;
|
|
107
|
+
};
|
|
258
108
|
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
width: 10px;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
.ml-cli-cmd-popup::-webkit-scrollbar-thumb,
|
|
265
|
-
.ml-cli-msg-panel::-webkit-scrollbar-thumb {
|
|
266
|
-
background: var(--ml-ui-border, rgba(255, 255, 255, 0.2));
|
|
267
|
-
border-radius: 6px;
|
|
268
|
-
}
|
|
269
|
-
`,document.head.appendChild(e)}createUI(){this.cliContainer=document.createElement("div"),this.cliContainer.className="ml-cli-container",this.cliContainer.style.position=this.useViewportPositioning()?"fixed":"absolute",this.useViewportPositioning()||getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.wrapper=document.createElement("div"),this.wrapper.className="ml-cli-wrapper",this.cliContainer.appendChild(this.wrapper),this.recentPanel=document.createElement("div"),this.recentPanel.className="ml-cli-recent",this.wrapper.appendChild(this.recentPanel),this.bar=document.createElement("div"),this.bar.className="ml-cli-bar",this.wrapper.appendChild(this.bar),this.leftGroup=document.createElement("div"),this.leftGroup.className="ml-cli-left",this.bar.appendChild(this.leftGroup),this.closeBtn=document.createElement("div"),this.closeBtn.className="ml-cli-close-btn",this.closeBtn.innerHTML="✕",this.leftGroup.appendChild(this.closeBtn),this.downBtn=document.createElement("button"),this.downBtn.className="ml-cli-down",this.downBtn.innerHTML="▾",this.leftGroup.appendChild(this.downBtn),this.centerEl=document.createElement("div"),this.centerEl.className="ml-cli-center",this.bar.appendChild(this.centerEl),this.promptEl=document.createElement("div"),this.promptEl.className="ml-cli-prompt",this.centerEl.appendChild(this.promptEl),this.textInput=document.createElement("input"),this.textInput.className="ml-cli-text",this.textInput.type="text",this.textInput.spellcheck=!1,this.textInput.autocomplete="off",this.textInput.placeholder=this.localize("main.commandLine.placeholder"),this.centerEl.appendChild(this.textInput);const e=document.createElement("div");e.className="ml-cli-right",this.bar.appendChild(e),this.upBtn=document.createElement("button"),this.upBtn.className="ml-cli-up",this.upBtn.innerHTML="▾",e.appendChild(this.upBtn),this.cmdPopup=document.createElement("div"),this.cmdPopup.className="ml-cli-cmd-popup hidden",this.wrapper.appendChild(this.cmdPopup),this.msgPanel=document.createElement("div"),this.msgPanel.className="ml-cli-msg-panel hidden",this.wrapper.appendChild(this.msgPanel),this.container.appendChild(this.cliContainer)}bindEvents(){this.closeBtn.addEventListener("click",e=>{e.stopPropagation(),this.visible=!1,ye.instance.isShowCommandLine=!1}),this.downBtn.addEventListener("click",e=>{e.stopPropagation(),this.isCmdPopupOpen=!this.isCmdPopupOpen,this.updatePopups({showCmd:this.isCmdPopupOpen,showMsg:!1}),this.isCmdPopupOpen&&this.showCommandHistoryPopup()}),this.upBtn.addEventListener("click",e=>{e.stopPropagation(),this.isMsgPanelOpen=!this.isMsgPanelOpen,this.updatePopups({showCmd:!1,showMsg:this.isMsgPanelOpen}),this.isMsgPanelOpen&&this.showMessagePanel()}),document.addEventListener("click",e=>{this.cliContainer.contains(e.target)||this.updatePopups({showCmd:!1,showMsg:!1})}),this.textInput.addEventListener("keydown",e=>this.handleKeyDown(e)),this.textInput.addEventListener("input",()=>this.handleInputChange()),this.centerEl.addEventListener("focus",()=>this.updatePopups({showCmd:!1,showMsg:!1})),this.cmdPopup.addEventListener("click",e=>{const t=e.target.closest(".item");t&&(this.setInputText(t.dataset.value||""),this.centerEl.focus(),this.updatePopups({showCmd:!1,showMsg:!1}))})}handleKeyDown(e){if(!e.isComposing)switch(e.key){case"Enter":{if(e.preventDefault(),e.stopImmediatePropagation(),this.activeSession){this.activeSession.handleEnter(this.getInputText())||this.showMessage(this.localize("main.commandLine.invalidKeyword"),"warning");return}this.executeCommand(this.getInputText()),this.historyIndex=this.history.length,this.updatePopups({showCmd:!1,showMsg:!1});return}case"Escape":{if(e.preventDefault(),e.stopImmediatePropagation(),this.activeSession){this.activeSession.handleEscape(),this.activeSession=void 0;return}this.clear(),this.showMessage(this.localize("main.commandLine.canceled")),this.updatePopups({showCmd:!1,showMsg:!1});return}case"ArrowUp":{e.preventDefault(),this.isCmdPopupOpen?this.navigateAutoComplete(-1):this.navigateHistory(-1);return}case"ArrowDown":{e.preventDefault(),this.isCmdPopupOpen?this.navigateAutoComplete(1):this.navigateHistory(1);return}case"Backspace":case"Delete":{e.stopPropagation(),e.stopImmediatePropagation();return}}}handleInputChange(){const e=this.getInputText();if(!e){this.updatePopups({showCmd:!1});return}const t=S.instance.searchCommandsByPrefix(e);t.length?(this.autoCompleteIndex=-1,this.cmdPopup.innerHTML="",t.forEach((i,n)=>{const s=document.createElement("div");s.className="item",s.dataset.value=i.command.globalName;const r=p.cmdDescription(i.commandGroup,i.command.globalName),o=S.instance.commandManager.getCommandAliases(i.command,i.commandGroup),c=o.length?`(${o.join(", ")})`:"";s.innerHTML=`<strong>${i.command.globalName}${c} - ${r}</strong>`,n===this.autoCompleteIndex&&s.classList.add("selected"),this.cmdPopup.appendChild(s)}),this.updatePopups({showCmd:!0})):this.updatePopups({showCmd:!1})}navigateAutoComplete(e){const t=Array.from(this.cmdPopup.querySelectorAll(".item"));if(!t.length)return;this.autoCompleteIndex+=e,this.autoCompleteIndex<0&&(this.autoCompleteIndex=0),this.autoCompleteIndex>=t.length&&(this.autoCompleteIndex=t.length-1),t.forEach((n,s)=>{n.classList.toggle("selected",s===this.autoCompleteIndex)});const i=t[this.autoCompleteIndex];i&&this.setInputText(i.dataset.value??"")}navigateHistory(e){this.history.length&&(this.historyIndex===-1&&(this.historyIndex=this.history.length),this.historyIndex+=e,this.historyIndex<0&&(this.historyIndex=0),this.historyIndex>this.history.length&&(this.historyIndex=this.history.length),this.historyIndex>=0&&this.historyIndex<this.history.length?this.setInputText(this.history[this.historyIndex]):this.setInputText(""))}getInputText(){return this.textInput.value.trim()}setInputText(e=""){this.textInput.value=e,this.textInput.focus()}renderKeywordPrompt(e,t){var s;this.promptEl.innerHTML="",this.isPromptActive=!0,this.textInput.placeholder="",e.message&&this.promptEl.append(e.message.trim()+" ");const i=e.getKeywordPromptFormat();if(!i.visibleKeywords.length)return;const n=(s=e.keywords)==null?void 0:s.toArray().filter(r=>r.visible);n!=null&&n.length&&(this.promptEl.append("["),n.forEach((r,o)=>{o>0&&this.promptEl.append("/");const c=document.createElement("span");c.className="ml-cli-option",c.textContent=r.displayName,r.enabled?c.onclick=()=>t(r.globalName):(c.style.opacity="0.45",c.style.pointerEvents="none"),this.promptEl.append(c)}),this.promptEl.append("]"),i.defaultKeyword&&this.promptEl.append(` <${i.defaultKeyword}>`),this.promptEl.append(": "),this.recordRecentMessage(this.promptEl.textContent??e.message))}bindCommandLifecycleEvents(){if(this.isCommandLifecycleBound)return;let e;try{e=S.instance.editor.events}catch{setTimeout(()=>this.bindCommandLifecycleEvents(),0);return}e.commandWillStart.addEventListener(()=>{this.cancelRecentAutoHide(),this.showRecentPanel()}),e.commandEnded.addEventListener(()=>{this.scheduleRecentAutoHide()}),this.isCommandLifecycleBound=!0}resolveCommand(e){const i=e.trim().split(/\s+/)[0].toUpperCase();return S.instance.lookupLocalCmd(i)}updatePopups({showCmd:e=!1,showMsg:t=!1}={}){this.isCmdPopupOpen=e,this.isMsgPanelOpen=t,this.cmdPopup.classList.toggle("hidden",!e),this.msgPanel.classList.toggle("hidden",!t),this.recentPanel.classList.toggle("ml-cli-recent-covered",t),e&&this.positionCmdPopup(),t&&this.positionMsgPanel()}showCommandHistoryPopup(){if(this.cmdPopup.innerHTML="",this.history.length)for(let e=this.history.length-1;e>=0;e--){const t=document.createElement("div");t.className="item",t.dataset.value=this.history[e],t.textContent=this.history[e],this.cmdPopup.appendChild(t)}else{const e=document.createElement("div");e.className="item",e.textContent=this.localize("main.commandLine.noHistory"),this.cmdPopup.appendChild(e)}this.positionCmdPopup()}positionCmdPopup(){this.cmdPopup.style.left="0px",this.cmdPopup.style.width=this.bar.offsetWidth+"px"}showMessagePanel(){if(!this.msgPanel.children.length){const e=document.createElement("div");e.className="ml-cli-history-line",e.textContent=this.localize("main.commandLine.noHistory"),e.dataset.msgKey="main.commandLine.noHistory",this.msgPanel.appendChild(e)}this.msgPanel.scrollTop=this.msgPanel.scrollHeight,this.positionMsgPanel()}positionMsgPanel(){this.msgPanel.style.width=this.bar.offsetWidth+"px"}clearNoHistoryPlaceholder(){Array.from(this.msgPanel.children).forEach(e=>{const t=e;t.dataset.msgKey==="main.commandLine.noHistory"&&this.msgPanel.removeChild(t)})}appendMessage(e,t="info",i){this.clearNoHistoryPlaceholder();const n=document.createElement("div");n.className=t==="warning"?"ml-cli-history-line ml-cli-msg-error":"ml-cli-history-line",n.textContent=e,i&&(n.dataset.msgKey=i),this.msgPanel.appendChild(n),this.recordRecentMessage(e),this.showMessagePanel()}printHistoryLine(e){this.clearNoHistoryPlaceholder();const t=document.createElement("div");t.className="ml-cli-history-line",t.textContent="> "+e,t.dataset.msgKey="main.commandLine.executed",this.msgPanel.appendChild(t),this.showMessagePanel()}resizeHandler(){const e=this.useViewportPositioning()?window.innerWidth:this.container.getBoundingClientRect().width;let t=Math.max(this.minWidth,e*this.widthRatio);t=Math.min(t,Math.max(200,e-20)),this.bar.style.width=t+"px",this.recentPanel.style.width=t+"px",this.positionMsgPanel(),this.positionCmdPopup()}recordRecentMessage(e){const t=e==null?void 0:e.replace(/\s+/g," ").trim();t&&(this.recentMessages.push(t),this.recentMessages.length>2&&this.recentMessages.shift(),this.showRecentPanel(),this.renderRecentMessages())}renderRecentMessages(){this.recentPanel.innerHTML="",this.recentMessages.forEach(e=>{const t=document.createElement("div");t.className="ml-cli-recent-line",t.textContent=e,this.recentPanel.appendChild(t)})}scheduleRecentAutoHide(){this.cancelRecentAutoHide(),this.recentHideTimer=setTimeout(()=>{this.hideRecentPanel(),this.recentHideTimer=void 0},2e3)}cancelRecentAutoHide(){this.recentHideTimer&&(clearTimeout(this.recentHideTimer),this.recentHideTimer=void 0)}showRecentPanel(){this.recentPanel.classList.remove("hidden")}hideRecentPanel(){this.recentPanel.classList.add("hidden")}useViewportPositioning(){return this.container===document.body}}class Na{constructor(e){this.options=e}parse(e){const t=Number(e);return isNaN(t)||!this.options.allowNegative&&t<0||!this.options.allowZero&&t===0?null:t}}class cn{constructor(e){this.options=e}parse(e){const t=Number(e);return isNaN(t)||!this.options.allowNegative&&t<0||!this.options.allowZero&&t===0?null:t}}class Ra extends cn{}class za extends cn{}class gs extends cn{constructor(e){super(e)}parse(e){const t=super.parse(e);return t==null?t:!Number.isInteger(t)||this.options.lowerLimit!==void 0&&t<this.options.lowerLimit||this.options.upperLimit!==void 0&&t>this.options.upperLimit?null:t}}class ms{constructor(e){this.options=e}parse(e,t){const i=Number(e),n=Number(t);return isNaN(i)||isNaN(n)?null:{x:i,y:n,z:0}}}class ys{constructor(e){this.options=e}parse(e){return!this.options.allowSpaces&&e.includes(" ")||!this.options.allowEmpty&&e.length===0||this.options.maxLength&&e.length>this.options.maxLength?null:e}}class ai{constructor(e="rect",t=12,i="var(--ml-ui-canvas-line, green)",n){this._type=e,this._size=t,this._color=i,this._host=n,ai.injectCSS(),getComputedStyle(this._host).position==="static"&&(this._host.style.position="relative"),this._el=document.createElement("div"),this._el.classList.add("ml-marker"),this._el.style.color=i,this.applyShape(),this._host.appendChild(this._el)}get color(){return this._color}set color(e){this._color=e,this._el.style.color=e}get type(){return this._type}set type(e){this._type=e,this.applyShape()}static injectCSS(){if(document.getElementById("ml-marker-style"))return;const e=document.createElement("style");e.id="ml-marker-style",e.textContent=`
|
|
270
|
-
.ml-marker {
|
|
271
|
-
position: absolute;
|
|
272
|
-
pointer-events: none;
|
|
273
|
-
transform: translate(-50%, -50%);
|
|
274
|
-
z-index: 999999;
|
|
275
|
-
box-sizing: border-box;
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
.ml-marker-circle {
|
|
279
|
-
border-radius: 50%;
|
|
280
|
-
border: 2px solid currentColor;
|
|
281
|
-
background: transparent;
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
.ml-marker-rect {
|
|
285
|
-
border: 2px solid currentColor;
|
|
286
|
-
background: transparent;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
.ml-marker-triangle {
|
|
290
|
-
width: 0;
|
|
291
|
-
height: 0;
|
|
292
|
-
border-left: 0.5em solid transparent;
|
|
293
|
-
border-right: 0.5em solid transparent;
|
|
294
|
-
border-bottom: 1em solid currentColor;
|
|
295
|
-
transform: translate(-50%, -100%);
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
.ml-marker-diamond {
|
|
299
|
-
border: 2px solid currentColor;
|
|
300
|
-
background: transparent;
|
|
301
|
-
transform: translate(-50%, -50%) rotate(45deg);
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
.ml-marker-x::before,
|
|
305
|
-
.ml-marker-x::after {
|
|
306
|
-
content: '';
|
|
307
|
-
position: absolute;
|
|
308
|
-
top: 50%;
|
|
309
|
-
left: 50%;
|
|
310
|
-
width: 100%;
|
|
311
|
-
height: 2px;
|
|
312
|
-
background: currentColor;
|
|
313
|
-
transform-origin: center;
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
.ml-marker-x::before {
|
|
317
|
-
transform: translate(-50%, -50%) rotate(45deg);
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
.ml-marker-x::after {
|
|
321
|
-
transform: translate(-50%, -50%) rotate(-45deg);
|
|
322
|
-
}
|
|
323
|
-
`,document.head.appendChild(e)}applyShape(){switch(this._el.className="ml-marker",this._el.style.width="",this._el.style.height="",this._el.style.fontSize="",this._el.style.transform="translate(-50%, -50%)",this._type){case"circle":this._el.classList.add("ml-marker-circle"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"rect":this._el.classList.add("ml-marker-rect"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"triangle":this._el.classList.add("ml-marker-triangle"),this._el.style.fontSize=`${this._size}px`;break;case"diamond":this._el.classList.add("ml-marker-diamond"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"x":this._el.classList.add("ml-marker-x"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break}}setPosition(e){this._el.style.left=`${e.x}px`,this._el.style.top=`${e.y}px`}destroy(){this._el.remove()}}class fs{constructor(e){this.stack=[],this.view=e}showMarker(e,t,i,n){const s=this.view.worldToScreen(e),r=this.view.canvasToContainer(s),o=new ai(t,i,n,this.view.container);return o.setPosition(r),this.stack.push(o),o}hideMarker(){const e=this.stack.pop();e&&e.destroy()}clear(){for(const e of this.stack)e.destroy();this.stack=[]}top(){return this.stack[this.stack.length-1]}}class ws{constructor(e){this.userTyped=!1,this.parent=e,this.input=document.createElement("input"),this.input.type="text",this.boundOnInput=()=>{this.userTyped=!0,this.resetValidation()},this.input.addEventListener("input",this.boundOnInput),this.parent.appendChild(this.input)}markInvalid(){this.input.classList.add("invalid")}markValid(){this.input.classList.remove("invalid")}resetValidation(){this.input.classList.remove("invalid")}get placeholder(){return this.input.placeholder}set placeholder(e){e&&(this.input.placeholder=e)}set value(e){e!==void 0&&(this.input.value=e)}get value(){return this.input.value}get focused(){return document.activeElement===this.input}focus(){this.input.focus()}blur(){this.input.blur()}select(){this.input.select()}remove(){this.input.remove()}isEventTarget(e){return e.target===this.input}dispose(){this.input.removeEventListener("input",this.boundOnInput),this.remove()}addEventListener(e,t,i){this.input.addEventListener(e,t,i)}removeEventListener(e,t,i){this.input.removeEventListener(e,t,i)}}class Va{constructor(e){this.parent=e.parent,this.twoInputs=e.twoInputs??!0,this.boundOnInput=()=>this.handleInput(),this.boundOnKeyDown=t=>this.handleKeyDown(t),this.xInput=new ws(this.parent),this.xInput.addEventListener("input",this.boundOnInput),this.xInput.addEventListener("keydown",this.boundOnKeyDown),this.twoInputs&&(this.yInput=new ws(this.parent),this.yInput.addEventListener("input",this.boundOnInput),this.yInput.addEventListener("keydown",this.boundOnKeyDown)),this.validateFn=e.validate,this.onCommit=e.onCommit,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onNone=e.onNone,this.allowNone=e.allowNone??!1,this.useDefaultValue=e.useDefaultValue??!1,this.defaultValue=e.defaultValue,e.autoFocus!==!1&&setTimeout(()=>{this.yInput&&this.yInput.select(),this.xInput.focus(),this.xInput.select()},0)}get userTyped(){var e;return this.xInput.userTyped||!!((e=this.yInput)!=null&&e.userTyped)}get focused(){var e;return this.xInput.focused||((e=this.yInput)==null?void 0:e.focused)}focus(){this.xInput.focus()}blur(){var e;this.xInput.blur(),(e=this.yInput)==null||e.blur()}setValue(e){this.xInput.userTyped||(this.xInput.value=e.x),this.twoInputs&&this.yInput&&!this.yInput.userTyped&&(this.yInput.value=e.y??"")}dispose(){var e;this.xInput.removeEventListener("input",this.boundOnInput),this.xInput.removeEventListener("keydown",this.boundOnKeyDown),this.xInput.dispose(),this.yInput&&(this.yInput.removeEventListener("input",this.boundOnInput),this.yInput.removeEventListener("keydown",this.boundOnKeyDown),(e=this.yInput)==null||e.dispose())}handleInput(){var t;const e=this.validate();(t=this.onChange)==null||t.call(this,e)}handleKeyDown(e){var n,s,r;let t=this.xInput,i=this.yInput;if(this.yInput&&this.yInput.isEventTarget(e)&&(t=this.yInput,i=this.xInput),e.key==="Enter"){if(this.useDefaultValue&&!this.userTyped){!this.onCommit||this.onCommit(this.defaultValue)?t.markValid():t.markInvalid(),e.preventDefault(),e.stopPropagation();return}if(this.allowNone&&!this.userTyped)(n=this.onNone)==null||n.call(this);else{const o=this.validate();o.isValid&&o.value!=null?((s=this.onCommit)==null||s.call(this,o.value),t.markValid()):t.markInvalid()}e.preventDefault(),e.stopPropagation()}else e.key==="Escape"?((r=this.onCancel)==null||r.call(this),e.preventDefault(),e.stopPropagation()):e.key==="Tab"&&(e.preventDefault(),i&&(i==null||i.focus(),i==null||i.select()))}validate(){const e=this.xInput.value.trim(),t=this.twoInputs&&this.yInput?this.yInput.value.trim():void 0;return this.validateFn({x:e,y:t})}}const $t=class $t{constructor(e,t){this.visible=!1,this.disposed=!1,this.isHovering=!1,this.view=e,this.parent=t.parent??this.view.canvas,this.host=this.view.container,getComputedStyle(this.host).position==="static"&&(this.host.style.position="relative"),this.container=document.createElement("div"),this.container.className="ml-floating-input",this.allowPrompt=t.allowPrompt!==!1;const n=t.message??"";this.label=document.createElement("span"),this.label.className="ml-floating-input-label",this.label.textContent=n,n.trim()||(this.label.style.display="none"),this.container.appendChild(this.label),this.host.appendChild(this.container),this.boundOnMouseEnter=s=>this.handleMouseEnter(s),this.boundOnMouseLeave=()=>this.handleMouseLeave(),this.boundOnMouseMove=s=>this.handleMouseMove(s),this.parent.addEventListener("mouseenter",this.boundOnMouseEnter),this.parent.addEventListener("mouseleave",this.boundOnMouseLeave),this.boundOnSysVarChanged=s=>{var o;const r=(o=s.name)==null?void 0:o.toLowerCase();(r===u.AcDbSystemVariables.DYNMODE.toLowerCase()||r===u.AcDbSystemVariables.DYNPROMPT.toLowerCase())&&this.updateDynamicDisplay()},u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.boundOnSysVarChanged),this.updateDynamicDisplay(),this.injectCSS()}injectCSS(){if($t.stylesInjected)return;$t.stylesInjected=!0;const e=document.createElement("style");e.textContent=`
|
|
324
|
-
.ml-floating-input {
|
|
325
|
-
position: absolute;
|
|
326
|
-
display: flex;
|
|
327
|
-
align-items: center;
|
|
328
|
-
padding: 2px 4px;
|
|
329
|
-
background: var(--ml-ui-bg, #444);
|
|
330
|
-
color: var(--ml-ui-text, #fff);
|
|
331
|
-
border-radius: 4px;
|
|
332
|
-
font-size: 12px;
|
|
333
|
-
pointer-events: none;
|
|
334
|
-
z-index: 10000;
|
|
335
|
-
}
|
|
336
|
-
.ml-floating-input-label {
|
|
337
|
-
white-space: nowrap;
|
|
338
|
-
color: var(--ml-ui-text, #fff);
|
|
339
|
-
}
|
|
340
|
-
`,document.head.appendChild(e)}get isVisible(){return this.visible}showAt(e){this.disposed||this.shouldShowPrompt()&&(this.visible=!0,this.container.style.display="flex",this.setPosition(e),this.parent.addEventListener("mousemove",this.boundOnMouseMove))}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.parent.removeEventListener("mousemove",this.boundOnMouseMove))}dispose(){this.disposed||(this.disposed=!0,this.hide(),this.parent.removeEventListener("mouseenter",this.boundOnMouseEnter),this.parent.removeEventListener("mouseleave",this.boundOnMouseLeave),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.boundOnSysVarChanged),this.container.remove())}setPosition(e){const t=this.host.getBoundingClientRect(),i=this.container.getBoundingClientRect(),n=this.view.viewportToCanvas(e),s=this.view.viewportToContainer(e);let r=s.x+10,o=s.y+10;return r=Math.min(r,t.width-i.width),o=Math.min(o,t.height-i.height),r=Math.max(r,0),o=Math.max(o,0),this.container.style.left=`${r}px`,this.container.style.top=`${o}px`,n}handleMouseEnter(e){this.isHovering=!0,this.showAt(e)}handleMouseLeave(){this.isHovering=!1,this.hide()}handleMouseMove(e){this.visible&&this.setPosition(e)}getSysVarValue(e){const t=u.acdbHostApplicationServices().workingDatabase;return u.AcDbSysVarManager.instance().getVar(e,t)}isDynamicInputEnabled(){return this.getSysVarValue(u.AcDbSystemVariables.DYNMODE)!==0}isDynamicPromptEnabled(){return!!this.getSysVarValue(u.AcDbSystemVariables.DYNPROMPT)}shouldShowPrompt(){var t;return!(!!!((t=this.label.textContent)!=null&&t.trim())||!this.allowPrompt||!this.isDynamicInputEnabled()||!this.isDynamicPromptEnabled())}updateDynamicDisplay(){if(!this.shouldShowPrompt()){this.hide();return}this.isHovering&&this.showAt(this.view.canvasToViewport(this.view.curMousePos))}};$t.stylesInjected=!1;let vt=$t;class bs{constructor(e){this.container=null,this.baseLine=null,this.perpLineAtBase=null,this.perpLineAtCursor=null,this.connectorLine=null,this.labelEl=null,this.angleLabelEl=null,this.xAxisLine=null,this.angleSvg=null,this.anglePath=null,this.options={},this.view=e}get element(){return this.container}start(e,t){this.basePoint=new u.AcGePoint3d(e),this.options=t||{};const i=this.options.color||"var(--ml-ui-canvas-line, #0f0)";this.container=document.createElement("div"),this.container.style.position="fixed",this.container.style.left="0",this.container.style.top="0",this.container.style.pointerEvents="none",this.container.style.zIndex="99999",document.body.appendChild(this.container),this.baseLine=document.createElement("div"),this.baseLine.style.position="fixed",this.baseLine.style.borderTop=`1px solid ${i}`,this.container.appendChild(this.baseLine);const n=()=>{const s=document.createElement("div");return s.style.position="fixed",s.style.borderTop=`1px dashed ${i}`,this.container.appendChild(s),s};this.options.showBaseLineOnly||(this.perpLineAtBase=n(),this.perpLineAtCursor=n(),this.connectorLine=n(),this.labelEl=document.createElement("div"),this.labelEl.style.position="fixed",this.labelEl.style.color=i,this.labelEl.style.fontSize="12px",this.labelEl.style.padding="2px 4px",this.labelEl.style.borderRadius="4px",this.container.appendChild(this.labelEl),this.xAxisLine=document.createElement("div"),this.xAxisLine.style.position="fixed",this.xAxisLine.style.borderTop=`1px solid ${i}`,this.container.appendChild(this.xAxisLine),this.angleSvg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.angleSvg.setAttribute("style","position:absolute; overflow:visible; pointer-events:none;"),this.anglePath=document.createElementNS("http://www.w3.org/2000/svg","path"),this.anglePath.setAttribute("fill","none"),this.anglePath.setAttribute("stroke",i),this.anglePath.setAttribute("stroke-width","1"),this.anglePath.setAttribute("stroke-dasharray","4 4"),this.angleSvg.appendChild(this.anglePath),this.container.appendChild(this.angleSvg),this.angleLabelEl=document.createElement("div"),this.angleLabelEl.style.position="fixed",this.angleLabelEl.style.color=i,this.angleLabelEl.style.fontSize="12px",this.angleLabelEl.style.padding="2px 4px",this.angleLabelEl.style.borderRadius="4px",this.container.appendChild(this.angleLabelEl))}update(e){var C,b;if(!this.container||!this.basePoint||!this.baseLine)return;const t=this.view.canvas.getBoundingClientRect(),i=this.view.worldToScreen(this.basePoint),n=this.view.worldToScreen(e),s=t.left,r=t.top,o=(x,A,_)=>{const L=_.x-A.x,T=_.y-A.y,O=Math.sqrt(L*L+T*T),k=Math.atan2(T,L)*(180/Math.PI);x.style.width=`${O}px`,x.style.transformOrigin="0 0",x.style.transform=`translate(${A.x+s}px, ${A.y+r}px) rotate(${k}deg)`};if(o(this.baseLine,i,n),this.options.showBaseLineOnly||!this.perpLineAtBase||!this.perpLineAtCursor||!this.connectorLine)return;const c=n.x-i.x,l=n.y-i.y,h=Math.sqrt(c*c+l*l);if(h===0){this.perpLineAtBase&&(this.perpLineAtBase.style.width="0px"),this.perpLineAtCursor&&(this.perpLineAtCursor.style.width="0px"),this.connectorLine&&(this.connectorLine.style.width="0px"),this.xAxisLine&&(this.xAxisLine.style.width="0px"),this.anglePath&&this.anglePath.setAttribute("d",""),this.angleLabelEl&&(this.angleLabelEl.style.display="none");return}const d=this.options.perpendicularLength??50,g=-l/h,m=c/h,y={x:i.x+g*d,y:i.y+m*d},w={x:n.x+g*d,y:n.y+m*d};if(o(this.perpLineAtBase,i,y),o(this.perpLineAtCursor,n,w),o(this.connectorLine,y,w),this.labelEl){const x=(y.x+w.x)/2+s,A=(y.y+w.y)/2+r-24,_=Math.sqrt((e.x-this.basePoint.x)**2+(e.y-this.basePoint.y)**2),L=(C=S.instance.curDocument)==null?void 0:C.database;this.labelEl.textContent=L?L.formatter.formatLength(_):_.toFixed(3),this.labelEl.style.left=`${x-20}px`,this.labelEl.style.top=`${A}px`,this.labelEl.style.display=""}if(this.xAxisLine){const x=(this.options.baseAngle??0)*Math.PI/180,A={x:this.basePoint.x+Math.cos(x),y:this.basePoint.y+Math.sin(x),z:0},_=this.view.worldToScreen(A),L=Math.atan2(_.y-i.y,_.x-i.x),T={x:i.x+h*Math.cos(L),y:i.y+h*Math.sin(L)};o(this.xAxisLine,i,T)}if(this.angleSvg&&this.anglePath&&this.angleLabelEl){const x=h,A=i.x+s,_=i.y+r,L=(this.options.baseAngle??0)*Math.PI/180,T={x:this.basePoint.x+Math.cos(L),y:this.basePoint.y+Math.sin(L),z:0},O=this.view.worldToScreen(T),k=Math.atan2(O.y-i.y,O.x-i.x);let M=Math.atan2(n.y-i.y,n.x-i.x)-k;for(;M<=-Math.PI;)M+=Math.PI*2;for(;M>Math.PI;)M-=Math.PI*2;const F=k+M/2,z=A-x,U=_-x,V=x*2;this.angleSvg.style.left=`${z}px`,this.angleSvg.style.top=`${U}px`,this.angleSvg.setAttribute("width",`${V}`),this.angleSvg.setAttribute("height",`${V}`),this.angleSvg.setAttribute("viewBox",`0 0 ${V} ${V}`);const K=x,G=x,W=K+x*Math.cos(k),ee=G+x*Math.sin(k),_e=K+x*Math.cos(k+M),wt=G+x*Math.sin(k+M),Qe=Math.abs(M)>Math.PI?"1":"0",Xt=M>=0?"1":"0",qt=`M ${W} ${ee} A ${x} ${x} 0 ${Qe} ${Xt} ${_e} ${wt}`;this.anglePath.setAttribute("d",qt);const nn=Math.abs(M),Zt=(b=S.instance.curDocument)==null?void 0:b.database,hu=Zt?Zt.formatter.formatAngle(nn,{showUnits:!0,applyAngbaseAngdir:!1}):`${(nn*180/Math.PI).toFixed(1)}°`,uu=A+x*Math.cos(F),du=_+x*Math.sin(F);this.angleLabelEl.textContent=hu;const pu=40;this.angleLabelEl.style.left=`${uu-pu/2}px`,this.angleLabelEl.style.top=`${du-12}px`,this.angleLabelEl.style.display=""}}dispose(){this.container&&this.container.remove(),this.container=null,this.baseLine=null,this.perpLineAtBase=null,this.perpLineAtCursor=null,this.connectorLine=null,this.labelEl=null,this.angleLabelEl=null,this.xAxisLine=null,this.angleSvg=null,this.anglePath=null}}const Kt=class Kt extends vt{constructor(e,t){super(e,t),this.lastPoint=null,this.suppressDisplay=!1,this.allowPrompt=t.allowPrompt!==!1,this.suppressDisplay=!this.isDynamicInputEnabled(),t.disableOSnap||(this.osnapMarkerManager=new fs(e)),t.basePoint&&(this.rubberBand=new bs(e),this.rubberBand.start(t.basePoint,{color:"var(--ml-ui-canvas-line, #0f0)",showBaseLineOnly:t.showBaseLineOnly,baseAngle:t.baseAngle})),this.validateFn=t.validate,this.getDynamicValue=t.getDynamicValue,this.drawPreview=t.drawPreview,this.onCommit=t.onCommit,this.onChange=t.onChange,this.onCancel=t.onCancel,this.onNone=t.onNone,t.inputCount!==0&&(this.inputs=new Va({parent:this.container,twoInputs:t.inputCount===2,validate:this.validateFn,onCancel:this.onCancel,onNone:this.onNone,onCommit:this.onCommit,onChange:this.onChange,autoFocus:this.isDynamicInputEnabled(),allowNone:t.allowNone,useDefaultValue:t.useDefaultValue,defaultValue:t.defaultValue})),this.boundOnClick=i=>this.handleClick(i),this.parent.addEventListener("click",this.boundOnClick),this.boundOnInputSysVarChanged=i=>{var s;const n=(s=i.name)==null?void 0:s.toLowerCase();(n===u.AcDbSystemVariables.DYNMODE.toLowerCase()||n===u.AcDbSystemVariables.DYNPROMPT.toLowerCase())&&this.updateDynamicInputDisplay()},u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.boundOnInputSysVarChanged),this.updateDynamicInputDisplay(),this.injectInputCSS()}showAt(e){if(this.disposed)return;if(this.updateDynamicInputDisplay(),!this.suppressDisplay){super.showAt(e);const i=this.view.screenToWorld(this.view.viewportToCanvas(e));this.updateDynamicPreview(i);return}this.visible=!0,this.container.style.display="none",this.setPosition(e),this.parent.addEventListener("mousemove",this.boundOnMouseMove);const t=this.view.screenToWorld(this.view.viewportToCanvas(e));this.updateDynamicPreview(t)}injectInputCSS(){if(Kt.inputStylesInjected)return;Kt.inputStylesInjected=!0;const e=document.createElement("style");e.textContent=`
|
|
341
|
-
.ml-floating-input input {
|
|
342
|
-
font-size: 12px;
|
|
343
|
-
padding: 2px 4px;
|
|
344
|
-
margin-left: 6px;
|
|
345
|
-
height: 22px;
|
|
346
|
-
width: 90px;
|
|
347
|
-
background: var(--ml-ui-bg, #888);
|
|
348
|
-
border: 1px solid var(--ml-ui-border, #666);
|
|
349
|
-
color: var(--ml-ui-text, #fff);
|
|
350
|
-
border-radius: 2px;
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
.ml-floating-input input.invalid {
|
|
354
|
-
border-color: var(--ml-ui-danger, red);
|
|
355
|
-
color: var(--ml-ui-danger, red);
|
|
356
|
-
}
|
|
357
|
-
`,document.head.appendChild(e)}dispose(){var e,t,i;this.disposed||(super.dispose(),this.parent.removeEventListener("click",this.boundOnClick),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.boundOnInputSysVarChanged),(e=this.inputs)==null||e.dispose(),(t=this.rubberBand)==null||t.dispose(),(i=this.osnapMarkerManager)==null||i.clear())}handleMouseMove(e){if(!this.visible)return;const t=this.getPosition(e);this.updateDynamicPreview(t)}requestPreviewRefresh(){!this.visible||!this.lastDynamicPoint||this.updateDynamicPreview(this.lastDynamicPoint)}handleClick(e){var s;if(!this.visible)return;const t=this.getPosition(e),i=this.getDynamicValue(t);(((s=this.onCommit)==null?void 0:s.call(this,i.value,t))??!0)&&(this.lastPoint=t)}setBasePoint(e,t){this.disposed||this.rubberBand||(this.rubberBand=new bs(this.view),this.rubberBand.start(e,{color:(t==null?void 0:t.color)??"var(--ml-ui-canvas-line, #0f0)",showBaseLineOnly:t==null?void 0:t.showBaseLineOnly,baseAngle:t==null?void 0:t.baseAngle}),this.requestPreviewRefresh())}updateDynamicPreview(e){var i,n,s;this.lastDynamicPoint={x:e.x,y:e.y};const t=this.getDynamicValue(e);(i=this.inputs)==null||i.setValue(t.raw),this.inputs&&!this.inputs.focused&&!this.suppressDisplay&&this.inputs.focus(),(n=this.rubberBand)==null||n.update(e),(s=this.drawPreview)==null||s.call(this,e)}getPosition(e){const t=super.setPosition(e),i=this.view.screenToWorld(t);return this.osnapMarkerManager&&(this.osnapMarkerManager.hideMarker(),this.lastOsnapPoint=this.getOsnapPoint(),this.lastOsnapPoint&&(i.x=this.lastOsnapPoint.x,i.y=this.lastOsnapPoint.y,this.osnapMarkerManager.showMarker(this.lastOsnapPoint,this.osnapMode2MarkerType(this.lastOsnapPoint.type)))),i}updateDynamicInputDisplay(){const e=this.isDynamicInputEnabled(),t=this.isDynamicPromptEnabled();this.setSuppressDisplay(!e),this.setPromptVisible(this.allowPrompt&&e&&t)}setSuppressDisplay(e){var t;this.suppressDisplay!==e&&(this.suppressDisplay=e,this.visible&&(this.suppressDisplay?(this.container.style.display="none",(t=this.inputs)==null||t.blur()):(this.container.style.display="flex",this.inputs&&!this.inputs.focused&&this.inputs.focus())))}setPromptVisible(e){var i;if(!!!((i=this.label.textContent)!=null&&i.trim())){this.label.style.display="none";return}this.label.style.display=e?"inline":"none"}osnapMode2MarkerType(e){switch(e){case u.AcDbOsnapMode.EndPoint:return"rect";case u.AcDbOsnapMode.MidPoint:return"triangle";case u.AcDbOsnapMode.Center:return"circle";case u.AcDbOsnapMode.Quadrant:return"diamond";case u.AcDbOsnapMode.Nearest:return"x";default:return"rect"}}osnapModePriority(e){switch(e){case u.AcDbOsnapMode.EndPoint:case u.AcDbOsnapMode.MidPoint:case u.AcDbOsnapMode.Center:return 0;case u.AcDbOsnapMode.Quadrant:return 1;case u.AcDbOsnapMode.Nearest:return 2;default:return 1}}getOsnapPoint(e,t=20){const i=this.getOsnapPoints(e,t);if(i.length===0)return;const n=this.view.screenToWorld({x:0,y:0}),r=this.view.screenToWorld({x:t,y:0}).x-n.x;let o=Number.MAX_VALUE,c=Number.MAX_VALUE,l=-1;for(let h=0;h<i.length;h++){const d=this.view.curPos.distanceTo(i[h]);if(d>=r)continue;const g=this.osnapModePriority(i[h].type);(g<o||g===o&&d<c)&&(o=g,c=d,l=h)}return l!==-1?i[l]:void 0}getOsnapPoints(e,t=20){const i=this.view.pick(e,t),s=u.acdbHostApplicationServices().workingDatabase.tables.blockTable.modelSpace,r=[];return i.forEach(o=>{const c=s.getIdAt(o.id);c&&(o.children&&o.children.length>0?o.children.forEach(l=>this.getOsnapPointsInAvailableModes(c,r,l.id)):this.getOsnapPointsInAvailableModes(c,r))}),r}getOsnapPointsInAvailableModes(e,t,i){u.acdbMaskToOsnapModes(ye.instance.osnapModes).forEach(s=>this.getOsnapPointsByMode(e,s,t,i))}getOsnapPointsByMode(e,t,i,n){const s=i.length,r={...this.view.curPos,z:0},o=this.lastPoint?{...this.lastPoint,z:0}:r;e.subGetOsnapPoints(t,r,o,i,n);for(let c=s;c<i.length;c++)i[c].type=t}};Kt.inputStylesInjected=!1;let ln=Kt;class St extends Error{constructor(e){super("keyword"),this.keyword=e}}class ci extends Error{constructor(){super("none")}}const Ut=class Ut{constructor(e){this.lastPoint=null,this._scriptInputs=[],this._modifierState={ctrlKey:!1,shiftKey:!1,altKey:!1,metaKey:!1},this._ctrlArcFlip=!1,this.active=!1,this.entitySelectionActive=!1,this.view=e,this.injectCSS(),getComputedStyle(this.view.container).position==="static"&&(this.view.container.style.position="relative");const i=new ps(this.view.container);this._commandLine=i,i.visible=ye.instance.isShowCommandLine,ye.instance.events.modified.addEventListener(()=>{i.visible=ye.instance.isShowCommandLine})}get isActive(){return this.active}get isEntitySelectionActive(){return this.entitySelectionActive}get modifiers(){return this._modifierState}get toggles(){return{ctrlArcFlip:this._ctrlArcFlip}}resetToggles(){this._ctrlArcFlip=!1}enqueueScriptInputs(e){e.length&&this._scriptInputs.push(...e)}clearScriptInputs(){this._scriptInputs.length=0}showMessage(e,t="info",i){this._commandLine.showMessage(e,t,i)}peekScriptInput(){return this._scriptInputs[0]}consumeScriptInput(){return this.dequeueScriptInput()}injectCSS(){if(Ut.stylesInjected)return;Ut.stylesInjected=!0;const e=document.createElement("style");e.textContent=`
|
|
358
|
-
.ml-jig-preview-rect {
|
|
359
|
-
position: absolute;
|
|
360
|
-
border: 1px dashed var(--line-color, var(--ml-ui-canvas-line, #0f0));
|
|
361
|
-
background: var(--ml-ui-canvas-fill-mix, var(--ml-ui-canvas-fill, rgba(64, 158, 255, 0.12)));
|
|
362
|
-
pointer-events: none;
|
|
363
|
-
z-index: 9999;
|
|
364
|
-
}
|
|
365
|
-
.ml-jig-preview-line {
|
|
366
|
-
position: absolute;
|
|
367
|
-
height: 1px;
|
|
368
|
-
background: var(--line-color, var(--ml-ui-canvas-line, #0f0));
|
|
369
|
-
transform-origin: 0 0;
|
|
370
|
-
pointer-events: none;
|
|
371
|
-
z-index: 9999;
|
|
372
|
-
}
|
|
373
|
-
`,document.head.appendChild(e)}formatNumber(e,t){var n;const i=(n=S.instance.curDocument)==null?void 0:n.database;if(!i)switch(t){case"angle":return e.toFixed(2);case"distance":case"point":default:return e.toFixed(3)}switch(t){case"angle":return i.formatter.formatAngle(e*Math.PI/180,{applyAngbaseAngdir:!1});case"distance":case"point":default:return i.formatter.formatLength(e)}}hasKeywords(e){var i;return(((i=e.keywords)==null?void 0:i.toArray())??[]).length>0}buildKeywordOptions(e){var n;const t=new Y(e.message);return t.appendKeywordsToMessage=e.appendKeywordsToMessage,(((n=e.keywords)==null?void 0:n.toArray())??[]).forEach(s=>{const r=t.keywords.add(s.displayName,s.globalName,s.localName,s.enabled,s.visible);e.keywords.default===s&&(t.keywords.default=r)}),t}copyKeywords(e,t){var n;t.appendKeywordsToMessage=e.appendKeywordsToMessage,(((n=e.keywords)==null?void 0:n.toArray())??[]).forEach(s=>{const r=t.keywords.add(s.displayName,s.globalName,s.localName,s.enabled,s.visible);e.keywords.default===s&&(t.keywords.default=r)})}getEntityById(e){return S.instance.curDocument.database.tables.blockTable.getEntityById(e)}isEntityOnLockedLayer(e){var i;const t=e.layer;return t?!!((i=S.instance.curDocument.database.tables.layerTable.getAt(t))!=null&&i.isLocked):!1}isEntityClassAllowed(e,t){var s;const i=new Set;e.type&&i.add(e.type);const n=(s=e.constructor)==null?void 0:s.name;n&&i.add(n);for(const r of i)if(t.isClassAllowed(r))return!0;return!1}startKeywordSession(e,t){if(!this.hasKeywords(e))return;const i=this.buildKeywordOptions(e);return{promise:this._commandLine.getKeywords(i,t),cancel:()=>this._commandLine.cancelActiveSession()}}isPromptKeyword(e){return e instanceof St}mapPromptError(e,t){if(t.none&&this.isPromptNone(e))return t.none();if(t.cancel&&this.isPromptCancelled(e))return t.cancel();if(t.keyword&&this.isPromptKeyword(e))return t.keyword(e.keyword)}withKeywordResult(e,t){return e.stringResult=t,e}mapPromptErrorToResult(e,t,i){const n=(i==null?void 0:i.none)??!0,s=(i==null?void 0:i.cancel)??!0,r=(i==null?void 0:i.keyword)??!0;return this.mapPromptError(e,{none:n?()=>t(v.None):void 0,cancel:s?()=>t(v.Cancel):void 0,keyword:r?o=>this.withKeywordResult(t(v.Keyword),o):void 0})}async executePrompt(e,t,i,n){try{const s=await e();return t(s)}catch(s){const r=this.mapPromptErrorToResult(s,i,n);if(r)return r;throw s}}resolvePromptDefaultValue(e){return"useDefaultValue"in e&&"defaultValue"in e&&e.useDefaultValue?{useDefaultValue:!0,defaultValue:e.defaultValue}:{useDefaultValue:!1}}async getPoint(e){return this.executePrompt(()=>this.getPointInternal(e),t=>new oi(v.OK,t),t=>new oi(t))}getNumberTyped(e,t){const i=()=>({value:0,raw:{x:""}});return this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:i})}resolveDistanceBasePoint(e){if(e.useBasePoint&&e.basePoint)return{x:e.basePoint.x,y:e.basePoint.y}}createDistanceDynamicValue(e){return t=>{const i=t.x-e.x,n=t.y-e.y,s=Math.sqrt(i*i+n*n);return{value:s,raw:{x:this.formatNumber(s,"distance")}}}}async getDistanceTwoPoint(e,t){let i,n;const s=r=>i?this.createDistanceDynamicValue(i)(r):{value:0,raw:{x:""}};return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:s,onFloatingInputCreated:r=>{n=r},onCommit:(r,o)=>i?!0:o?(i={x:o.x,y:o.y},n==null||n.setBasePoint(i,{showBaseLineOnly:!e.useDashedLine}),!1):!0})}async getDistance(e){const t=new Ra(e),i=this.tryGetScriptedNumber(t);if(i!=null)return new ie(v.OK,i);const n=this.resolveDistanceBasePoint(e);return this.executePrompt(async()=>n?await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:this.createDistanceDynamicValue(n)}):await this.getDistanceTwoPoint(e,t),s=>new ie(v.OK,s),s=>new ie(s))}async getAngle(e){const t=new Na(e),i=this.tryGetScriptedNumber(t);if(i!=null)return new ie(v.OK,i);const n=e.useBasePoint&&e.basePoint?e.basePoint:this.lastPoint;if(!n)return this.executePrompt(()=>this.getNumberTyped(e,t),r=>new ie(v.OK,r),r=>new ie(r));const s=r=>{const o=r.x-n.x,c=r.y-n.y,l=Math.atan2(c,o),h=e.baseAngle*Math.PI/180;let d=l-h;for(;d<=-Math.PI;)d+=Math.PI*2;for(;d>Math.PI;)d-=Math.PI*2;const g=d*180/Math.PI;return{value:g,raw:{x:this.formatNumber(g,"angle")}}};return this.executePrompt(()=>this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:s}),r=>new ie(v.OK,r),r=>new ie(r))}async getDouble(e){const t=new za(e),i=this.tryGetScriptedNumber(t);return i!=null?new ie(v.OK,i):this.executePrompt(()=>this.getNumberTyped(e,t),n=>new ie(v.OK,n),n=>new ie(n))}async getInteger(e){const t=this.tryGetScriptedNumber(new gs(e));return t!=null?new ri(v.OK,t):this.executePrompt(()=>this.getNumberTyped(e,new gs(e)),i=>new ri(v.OK,i),i=>new ri(i))}async getString(e){const t=this.tryGetScriptedValue(new ys(e));return t!=null?new ae(v.OK,t):this.executePrompt(async()=>{const i=()=>({value:"",raw:{x:""}}),n=new ys(e);return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:n,getDynamicValue:i})},i=>new ae(v.OK,i),i=>new ae(i))}async getKeywords(e){const t=this.tryGetScriptedValue(new ds(e));return t!=null?new ae(v.OK,t):this.executePrompt(async()=>{const i=await this._commandLine.getKeywords(e,!0);if(!i)throw e.allowNone?new ci:new Error("cancelled");return i},i=>new ae(v.OK,i),i=>new ae(i),{keyword:!1})}async getSelection(e){return this.executePrompt(()=>new Promise((t,i)=>{this.active=!0,this.entitySelectionActive=!0;const n=this.startKeywordSession(e,!0);n||this._commandLine.setPrompt(e.message);const s=new vt(this.view,{parent:this.view.canvas,message:e.message}),r=new Set;let o=null,c=null,l=null,h=!1;const d=()=>{h||(h=!0,this.active=!1,this.entitySelectionActive=!1,s==null||s.dispose(),l==null||l.remove(),n==null||n.cancel(),this._commandLine.clear(),document.removeEventListener("keydown",g),this.view.canvas.removeEventListener("mousedown",y),this.view.canvas.removeEventListener("mousemove",w),this.view.canvas.removeEventListener("mouseup",C),this.view.canvas.removeEventListener("contextmenu",m))};n==null||n.promise.then(b=>{if(!h){if(!b){d(),i(new Error("cancelled"));return}d(),i(new St(b))}});const g=b=>{if(b.key==="Escape"){d(),i(new Error("cancelled"));return}b.key==="Enter"&&(d(),t([...r]))},m=b=>{this.shouldUseRightClickEnter()&&b.preventDefault()},y=b=>{if(b.button===2){this.shouldUseRightClickEnter()&&(b.preventDefault(),d(),t([...r]));return}b.button===0&&(c=this.view.viewportToCanvas({x:b.clientX,y:b.clientY}),o=this.view.screenToWorld(c),l=document.createElement("div"),l.className="ml-jig-preview-rect",this.view.container.appendChild(l))},w=b=>{if(b.buttons!==1||!o||!l||!c)return;const x=this.view.screenToWorld(this.view.viewportToCanvas({x:b.clientX,y:b.clientY})),A=this.view.viewportToCanvas({x:b.clientX,y:b.clientY}),_=this.view.worldToScreen(o),L=this.view.worldToScreen(x),T=Math.min(_.x,L.x),O=Math.min(_.y,L.y),k=Math.abs(_.x-L.x),E=Math.abs(_.y-L.y),M=this.view.getSelectionMode(c,A),F=this.view.getSelectionActionFromEvent(b,"add"),z=this.view.getSelectionPreviewStyle(M,F);Object.assign(l.style,{left:`${T}px`,top:`${O}px`,width:`${k}px`,height:`${E}px`,borderStyle:z.borderStyle,background:z.background}),l.style.setProperty("--line-color",z.lineColor)},C=b=>{if(b.button!==0||!o||!c)return;const x=this.view.screenToWorld(this.view.viewportToCanvas({x:b.clientX,y:b.clientY})),A=this.view.viewportToCanvas({x:b.clientX,y:b.clientY});l==null||l.remove(),l=null;const _=this.view.getSelectionActionFromEvent(b,"add");if(this.view.isSelectionClick(c,A)){const L=this.view.pick(x);L.length>0?this.view.applySelection([L[0].id],_):_==="replace"&&this.view.selectionSet.clear()}else{const L=new u.AcGeBox2d().expandByPoint(o).expandByPoint(x),T=this.view.getSelectionMode(c,A);this.view.selectByBoxWithMode(L,T,_)}r.clear();for(const L of this.view.selectionSet.ids)r.add(L);e.singleOnly&&_!=="remove"&&r.size>0&&(d(),t([...r])),o=null,c=null};document.addEventListener("keydown",g),this.view.canvas.addEventListener("mousedown",y),this.view.canvas.addEventListener("mousemove",w),this.view.canvas.addEventListener("mouseup",C),this.view.canvas.addEventListener("contextmenu",m)}),t=>new xt(v.OK,new ei(t)),t=>new xt(t),{none:!1})}async getEntity(e){let t;return this.executePrompt(()=>new Promise((i,n)=>{this.active=!0,this.entitySelectionActive=!0;const s=this.startKeywordSession(e,!0),r=new vt(this.view,{parent:this.view.canvas,message:e.message});s||this._commandLine.setPrompt(e.message);let o=!1;const c=()=>{var m;o||(o=!0,this.active=!1,this.entitySelectionActive=!1,(m=e.jig)==null||m.end(),document.removeEventListener("keydown",d),this.view.canvas.removeEventListener("mousedown",l),this.view.canvas.removeEventListener("click",h),this.view.canvas.removeEventListener("contextmenu",g),r==null||r.dispose(),s==null||s.cancel(),this._commandLine.clear())};s==null||s.promise.then(m=>{if(!o){if(!m){c(),n(new Error("cancelled"));return}c(),n(new St(m))}});const l=m=>{if(m.button===2){this.shouldUseRightClickEnter()&&e.allowNone&&(m.preventDefault(),c(),i(null));return}},h=m=>{if(m.button!==0)return;const y=this.view.screenToWorld(this.view.viewportToCanvas({x:m.clientX,y:m.clientY})),w=this.view.pick(y,void 0,!0);if(w.length==0){this._commandLine.showMessage(e.rejectMessage,"warning");return}const C=this.getEntityById(w[0].id);if(!C){this._commandLine.showMessage(e.rejectMessage,"warning");return}if(!e.allowObjectOnLockedLayer&&this.isEntityOnLockedLayer(C)){this._commandLine.showMessage(e.rejectMessage,"warning");return}if(!this.isEntityClassAllowed(C,e)){this._commandLine.showMessage(e.rejectMessage,"warning");return}t={x:y.x,y:y.y,z:0},c(),i(w[0].id)},d=m=>{if(m.key==="Escape"){c(),n(new Error("cancelled"));return}m.key==="Enter"&&e.allowNone&&(c(),i(null))},g=m=>{this.shouldUseRightClickEnter()&&m.preventDefault()};document.addEventListener("keydown",d),this.view.canvas.addEventListener("mousedown",l),this.view.canvas.addEventListener("click",h),this.view.canvas.addEventListener("contextmenu",g)}),i=>new si(v.OK,i||void 0,t),i=>new si(i),{none:!1})}async getBox(e){return this.executePrompt(async()=>{const t=e.firstCornerMessage||p.t("main.inputManager.firstCorner"),i=new D(t);this.copyKeywords(e,i),i.useDashedLine=e.useDashedLine,i.useBasePoint=e.useBasePoint,i.disableOSnap=e.disableOSnap;const n=await this.getPoint(i);if(n.status!==v.OK)return new ii(n.status,void 0,n.stringResult);const s=n.value,r=this.view.worldToScreen(s),o=document.createElement("div");o.className="ml-jig-preview-rect",this.view.container.appendChild(o);const c=()=>{o.remove()},l=y=>{const w=this.view.worldToScreen(y),C=Math.min(w.x,r.x),b=Math.min(w.y,r.y),x=Math.abs(w.x-r.x),A=Math.abs(w.y-r.y);Object.assign(o.style,{left:`${C}px`,top:`${b}px`,width:`${x}px`,height:`${A}px`})},h=e.secondCornerMessage||p.t("main.inputManager.secondCorner"),d=new D(h);this.copyKeywords(e,d),d.useDashedLine=e.useDashedLine,d.useBasePoint=e.useBasePoint,d.disableOSnap=e.disableOSnap;const g=await this.getPointInternal(d,c,l),m=new u.AcGeBox2d().expandByPoint(s).expandByPoint(g);return new ii(v.OK,m)},t=>t,t=>new ii(t))}async getPointInternal(e,t,i){const n=this.tryGetScriptedPoint(e);if(n!=null)return t==null||t(),Promise.resolve(n);const s=o=>({value:{x:o.x,y:o.y,z:0},raw:{x:this.formatNumber(o.x,"point"),y:this.formatNumber(o.y,"point")}}),r=new ms(e);return this.makeFloatingInputPromise({inputCount:2,promptOptions:e,disableOSnap:e.disableOSnap,cleanup:t,handler:r,getDynamicValue:s,drawPreview:i})}tryGetScriptedPoint(e){const t=this.dequeueScriptInput();if(t===void 0)return;const i=t.trim();if(!i&&e.allowNone)throw new ci;const n=e.keywords.findByName(i);if(n)throw new St(n.globalName);const s=this.splitScriptedPoint(t);if(!s)throw new Error(`Invalid point input '${t}'`);const r=new ms(e).parse(s.x,s.y);if(r==null)throw new Error(`Invalid point input '${t}'`);return this.lastPoint={x:r.x,y:r.y},r}tryGetScriptedValue(e){const t=this.dequeueScriptInput();if(t===void 0)return;const i=e.parse(t);if(i==null)throw new Error(`Invalid scripted input '${t}'`);return i}tryGetScriptedNumber(e){return this.tryGetScriptedValue(e)}dequeueScriptInput(){if(this._scriptInputs.length)return this._scriptInputs.shift()}splitScriptedPoint(e){const t=e.trim();if(!t)return;if(t.includes(",")){const n=t.split(",").map(s=>s.trim());return n.length!==2&&n.length!==3||n.length===3&&Number.isNaN(Number(n[2]))?void 0:{x:n[0],y:n[1]}}const i=t.split(/\s+/);if(!(i.length<2))return{x:i[0],y:i[1]}}isPromptCancelled(e){return e instanceof Error&&e.message==="cancelled"}isPromptNone(e){return e instanceof ci}getShortcutMenuMode(){const e=u.acdbHostApplicationServices().workingDatabase,t=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.SHORTCUTMENU,e),i=Math.trunc(Number(t));return Number.isNaN(i)?0:i&3}shouldUseRightClickEnter(){const e=this.getShortcutMenuMode();return e===0?!0:e===1?this.active:!1}updateModifierStateFromEvent(e){const t={ctrlKey:!!e.ctrlKey,shiftKey:!!e.shiftKey,altKey:!!e.altKey,metaKey:!!e.metaKey},i=this._modifierState,n=i.ctrlKey!==t.ctrlKey||i.shiftKey!==t.shiftKey||i.altKey!==t.altKey||i.metaKey!==t.metaKey;return n&&(this._modifierState=t),n}handleCtrlToggleKey(e){return e.key!=="Control"||e.repeat||e.type!=="keydown"?!1:(this._ctrlArcFlip=!this._ctrlArcFlip,!0)}resolvePromptDefaults(e){const t="basePoint"in e,i="useBasePoint"in e,n="useDashedLine"in e,s="baseAngle"in e,r=t&&e.basePoint?e.basePoint:void 0,o=i?e.useBasePoint:!1,c=n?!e.useDashedLine:!1,l=s?e.baseAngle:void 0;return{message:e.message,jig:e.jig,basePoint:r,useBasePoint:o,showBaseLineOnly:c,baseAngle:l}}async makeFloatingInputPromise(e){return new Promise((t,i)=>{var L;this.active=!0,this.entitySelectionActive=!1;let n=!1;const s=T=>{const O=e.handler.parse(T.x,T.y);return{isValid:O!=null,value:O??void 0}},r=this.resolvePromptDefaults(e.promptOptions),o=this.startKeywordSession(e.promptOptions,!0);let c;r.useBasePoint&&r.basePoint&&(c=r.basePoint);const l=r.message;o||this._commandLine.setPrompt(l);const h="allowNone"in e.promptOptions?e.promptOptions.allowNone:!1,d=this.resolvePromptDefaultValue(e.promptOptions),g=new ln(this.view,{parent:this.view.canvas,inputCount:e.inputCount,message:r.message,disableOSnap:e.disableOSnap,showBaseLineOnly:r.showBaseLineOnly,basePoint:c,baseAngle:r.baseAngle,allowPrompt:e.allowPrompt!==!1,allowNone:h,useDefaultValue:d.useDefaultValue,defaultValue:d.defaultValue,validate:s,getDynamicValue:e.getDynamicValue,drawPreview:T=>{var O;if(r.jig){const k=e.getDynamicValue(T);r.jig.update(k.value),r.jig.render()}(O=e.drawPreview)==null||O.call(e,T)},onCommit:(T,O)=>{let k=!1;return(!e.onCommit||e.onCommit(T,O))&&(y(T),k=!0),k&&g.lastPoint&&(this.lastPoint={x:g.lastPoint.x,y:g.lastPoint.y}),k},onCancel:()=>w(),onNone:()=>C()});(L=e.onFloatingInputCreated)==null||L.call(e,g);const m=()=>{var T,O;n||(n=!0,this.active=!1,this.entitySelectionActive=!1,(T=e.cleanup)==null||T.call(e),(O=r.jig)==null||O.end(),document.removeEventListener("keydown",x),document.removeEventListener("keydown",A),document.removeEventListener("keyup",A),this.view.canvas.removeEventListener("contextmenu",_),g.dispose(),o==null||o.cancel(),this._commandLine.clear())},y=T=>{m(),t(T)},w=T=>{m(),i(T??new Error("cancelled"))},C=()=>{w(new ci)},b=T=>{w(new St(T))},x=T=>{T.key==="Escape"&&w()},A=T=>{const O=this.handleCtrlToggleKey(T),k=this.updateModifierStateFromEvent(T);(O||k)&&g.requestPreviewRefresh()},_=T=>{this.shouldUseRightClickEnter()&&(T.preventDefault(),C())};document.addEventListener("keydown",x),document.addEventListener("keydown",A),document.addEventListener("keyup",A),this.view.canvas.addEventListener("contextmenu",_),g.showAt(this.view.canvasToViewport(this.view.curMousePos)),o==null||o.promise.then(T=>{if(!n){if(!T){w();return}b(T)}})})}};Ut.stylesInjected=!1;let li=Ut;const hi="simkai";function Ga(){return{fontFamily:hi,fontSize:24,bold:!1,italic:!1,underline:!1,overline:!1,strike:!1,script:"normal",aci:null,rgb:16777215,obliqueAngle:0,widthFactor:1,tracking:1,paragraphAlignment:B.MTextParagraphAlignment.DEFAULT}}function xs(a,e){return a.fontFamily===e.fontFamily&&a.fontSize===e.fontSize&&a.bold===e.bold&&a.italic===e.italic&&a.underline===e.underline&&a.overline===e.overline&&a.strike===e.strike&&a.script===e.script&&a.aci===e.aci&&a.rgb===e.rgb&&a.obliqueAngle===e.obliqueAngle&&a.widthFactor===e.widthFactor&&a.tracking===e.tracking&&a.paragraphAlignment===e.paragraphAlignment}function ne(a,e,t){return Math.min(t,Math.max(e,a))}function $a(a,e){const t=Math.max(a.y-a.height/2,e.y-e.height/2),i=Math.min(a.y+a.height/2,e.y+e.height/2);return Math.max(0,i-t)}class Ka{constructor(e){I(this,"containerBox");I(this,"charBoxes");I(this,"explicitLineBreakIndices",[]);I(this,"explicitLineLayouts",[]);I(this,"cursorLineHint",null);I(this,"verticalAlign");I(this,"lineTolerance");I(this,"debug");I(this,"lines",[]);I(this,"cursorIndex",0);I(this,"selection",null);I(this,"dragAnchor",null);I(this,"preferredX",null);I(this,"handlers",{cursorMove:new Set,selectionChange:new Set,linesUpdate:new Set});this.containerBox={...e.containerBox};const t=this.normalizeCharLayout(e.charBoxes,e.lineBreakIndices);this.charBoxes=t.charBoxes,this.explicitLineBreakIndices=t.lineBreakIndices,this.explicitLineLayouts=this.normalizeLineLayouts(e.lineLayouts),this.verticalAlign=e.verticalAlign??"center",this.lineTolerance=e.lineTolerance??5,this.debug=e.debug??!1,this.cursorIndex=ne(e.initialIndex??0,0,this.charBoxes.length),this.recomputeLines(),e.initialSelection&&this.setSelection(e.initialSelection.start,e.initialSelection.end)}moveLeft(){if(this.selection&&!this.selection.isCollapsed){this.cursorIndex=this.selection.start,this.cursorLineHint=null,this.clearSelection(),this.emitCursor();return}const e=this.getCurrentLineIndex();if(e>=0){const t=this.lines[e];if(t){if(this.cursorIndex>t.startIndex&&this.cursorIndex<=t.endIndex+1){this.moveTo(this.cursorIndex-1,e);return}if(this.cursorIndex===t.startIndex&&e>0){this.moveTo(this.cursorIndex,e-1);return}}}this.moveTo(this.cursorIndex-1)}moveRight(){if(this.selection&&!this.selection.isCollapsed){this.cursorIndex=this.selection.end,this.cursorLineHint=null,this.clearSelection(),this.emitCursor();return}const e=this.getCurrentLineIndex();if(e>=0){const t=this.lines[e],i=e+1;if(t&&this.cursorIndex===t.endIndex&&i<this.lines.length&&this.isHardBreakChar(t.endIndex)){this.moveTo(t.endIndex+1,i);return}if(t&&this.cursorIndex===t.endIndex+1&&i<this.lines.length){this.moveTo(this.cursorIndex,i);return}}this.cursorIndex>=this.charBoxes.length||this.moveTo(this.cursorIndex+1)}moveUp(){this.moveVertical(-1)}moveDown(){this.moveVertical(1)}moveTo(e,t=null){const i=ne(e,0,this.charBoxes.length);i===this.cursorIndex&&this.cursorLineHint===t||(this.cursorIndex=i,this.cursorLineHint=t,this.preferredX=null,this.emitCursor())}moveToStart(){this.moveTo(0)}moveToEnd(){this.moveTo(this.charBoxes.length)}moveToLineStart(){const e=this.getCurrentLineIndex();if(e<0){this.moveToStart();return}const t=this.lines[e];t&&this.moveTo(t.startIndex,e)}moveToLineEnd(){const e=this.getCurrentLineIndex();if(e<0){this.moveToEnd();return}const t=this.lines[e];t&&this.moveTo(t.endIndex+1,e)}setSelection(e,t){const i=ne(e,0,this.charBoxes.length),n=ne(t,0,this.charBoxes.length);this.setSelectionWithDirection(i,n)}clearSelection(){this.selection&&(this.selection=null,this.dragAnchor=null,this.emit("selectionChange",null))}selectAll(){this.setSelectionWithDirection(0,this.charBoxes.length),this.cursorIndex=this.charBoxes.length,this.cursorLineHint=null,this.emitCursor()}setSelectionWithDirection(e,t){const i=ne(e,0,this.charBoxes.length),n=ne(t,0,this.charBoxes.length),s=Math.min(i,n),r=Math.max(i,n);this.selection={start:s,end:r,isCollapsed:s===r,anchor:i,active:n,isBackwards:n<i,selectedLines:this.resolveSelectedLines(s,r)},this.cursorIndex=n,this.cursorLineHint=null,this.emit("selectionChange",this.selection),this.emitCursor()}extendSelection(e){var n;const t=ne(e,0,this.charBoxes.length),i=((n=this.selection)==null?void 0:n.anchor)??this.cursorIndex;this.setSelectionWithDirection(i,t)}getSelection(){return this.selection?{...this.selection,selectedLines:[...this.selection.selectedLines]}:null}getSelectedCharBoxes(){return!this.selection||this.selection.isCollapsed?[]:this.charBoxes.slice(this.selection.start,this.selection.end).map(e=>({...e}))}getSelectedLines(){if(!this.selection||this.selection.isCollapsed)return[];const e=[],{start:t,end:i}=this.selection;for(let n=0;n<this.lines.length;n++){const s=this.lines[n];if(!s)continue;const r=s.startIndex,o=s.endIndex+1,c=Math.max(t,r),l=Math.min(i,o);c<l&&e.push({lineIndex:n,startOffset:c-r,endOffset:l-r})}return e}hasSelection(){return!!this.selection&&!this.selection.isCollapsed}moveToClick(e,t){const i=this.hitTest(e,t);if(i<0)return!1;const n=this.hitTestLine(t);return this.clearSelection(),this.moveTo(i,n>=0?n:null),!0}extendSelectionToClick(e,t){const i=this.hitTestClamped(e,t);i<0||(this.dragAnchor===null&&(this.dragAnchor=this.cursorIndex),this.setSelectionWithDirection(this.dragAnchor,i))}updateSelectionDrag(e,t){const i=this.hitTestClamped(e,t);i<0||(this.dragAnchor===null&&(this.dragAnchor=this.cursorIndex),this.setSelectionWithDirection(this.dragAnchor,i))}hitTest(e,t){if(!this.isInContainer(e,t))return-1;if(this.charBoxes.length===0)return 0;const i=this.hitTestLine(t);return i<0?-1:this.closestIndexInLine(i,e)}hitTestLine(e){if(this.lines.length===0)return-1;let t=-1,i=Number.POSITIVE_INFINITY;for(let n=0;n<this.lines.length;n++){const s=this.lines[n];if(!s)continue;const r=s.y-s.height/2,o=s.y+s.height/2;if(e>=r&&e<=o)return n;const c=e<r?r-e:e-o;c<i&&(i=c,t=n)}return t}getLines(){return this.lines.map(e=>({...e}))}getLineCount(){return this.lines.length}getLineIndex(e){if(this.lines.length===0)return-1;const t=ne(e,0,this.charBoxes.length);for(let i=0;i<this.lines.length;i++){const n=this.lines[i];if(n&&t>=n.startIndex&&t<=n.endIndex+1)return i}return this.lines.length-1}getLineInfo(e){const t=this.lines[e];if(!t)throw new Error(`Line index out of range: ${e}`);return{...t}}getCurrentLineInfo(){const e=this.getCurrentLineIndex();if(e<0)return{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0};const t=this.lines[e];return t?{...t}:{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0}}getCursorState(){var n,s;const e=this.getCurrentLineIndex(),t=this.getCursorPosition(),i=e>=0&&this.lines[e]?this.lines[e]:{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0};return{index:this.cursorIndex,position:t,lineIndex:e,lineInfo:{...i},isAtStart:this.cursorIndex===0,isAtEnd:this.cursorIndex===this.charBoxes.length,isAtLineStart:e<0?!0:this.cursorIndex===(((n=this.lines[e])==null?void 0:n.startIndex)??this.cursorIndex),isAtLineEnd:e<0?!0:this.cursorIndex===(((s=this.lines[e])==null?void 0:s.endIndex)??this.cursorIndex-1)+1}}getCurrentIndex(){return this.cursorIndex}getCursorPosition(){if(this.lines.length===0)return{x:this.containerBox.x,y:this.alignY(this.containerBox.y,this.containerBox.height)};const e=this.getCurrentLineIndex(),t=this.lines[Math.max(0,e)];if(!t)return{x:this.containerBox.x,y:this.alignY(this.containerBox.y,this.containerBox.height)};const i=this.alignY(t.y,t.height);return{x:this.indexToX(this.cursorIndex,e),y:i}}getCharBoxes(){return this.charBoxes.map(e=>({...e}))}getContainerBox(){return{...this.containerBox}}updateData(e,t,i,n){this.containerBox={...e};const s=this.normalizeCharLayout(t,i);if(this.charBoxes=s.charBoxes,this.explicitLineBreakIndices=s.lineBreakIndices,this.explicitLineLayouts=this.normalizeLineLayouts(n),this.recomputeLines(),this.cursorIndex=ne(this.cursorIndex,0,this.charBoxes.length),this.cursorLineHint=null,this.selection){const r=ne(this.selection.anchor,0,this.charBoxes.length),o=ne(this.selection.active,0,this.charBoxes.length);r===o?this.selection=null:this.setSelectionWithDirection(r,o)}this.emit("linesUpdate",this.getLines()),this.emitCursor()}setLineTolerance(e){this.lineTolerance=Math.max(0,e),this.recomputeLines(),this.emit("linesUpdate",this.getLines()),this.emitCursor(),this.selection&&(this.selection.selectedLines=this.resolveSelectedLines(this.selection.start,this.selection.end),this.emit("selectionChange",this.selection))}on(e,t){this.handlers[e].add(t)}off(e,t){(e==="cursorMove"||e==="selectionChange"||e==="linesUpdate")&&this.handlers[e].delete(t)}enableDebug(){this.debug=!0}disableDebug(){this.debug=!1}getDebugInfo(){return{debug:this.debug,container:this.getContainerBox(),cursor:this.getCursorState(),selection:this.getSelection(),lines:this.getLines(),gaps:this.lines.map((e,t)=>this.getGapPositions(t))}}destroy(){this.handlers.cursorMove.clear(),this.handlers.selectionChange.clear(),this.handlers.linesUpdate.clear(),this.selection=null,this.dragAnchor=null,this.preferredX=null}emitCursor(){this.emit("cursorMove",this.getCursorState())}emit(e,t){for(const i of this.handlers[e])i(t)}moveVertical(e){const t=this.getCurrentLineIndex();if(t<0)return;const i=this.lines[t],n=t+e;if(n<0||n>=this.lines.length)return;(this.preferredX===null||(i==null?void 0:i.charCount)===0)&&(this.preferredX=this.getCursorPosition().x);const s=this.closestIndexInLine(n,this.preferredX);this.cursorIndex=s,this.cursorLineHint=n,this.emitCursor()}getCurrentLineIndex(){const e=this.getLineIndex(this.cursorIndex);if(e<0||this.cursorLineHint===null)return e;const t=this.lines[this.cursorLineHint];return t&&this.cursorIndex>=t.startIndex&&this.cursorIndex<=t.endIndex+1?this.cursorLineHint:e}isHardBreakChar(e){const t=this.charBoxes[e];return t?t.width===0:!1}resolveSelectedLines(e,t){if(e===t)return[];const i=[];for(let n=0;n<this.lines.length;n++){const s=this.lines[n];s&&t>s.startIndex&&e<s.endIndex+1&&i.push(n)}return i}isInContainer(e,t){return e>=this.containerBox.x&&e<=this.containerBox.x+this.containerBox.width&&t>=this.containerBox.y&&t<=this.containerBox.y+this.containerBox.height}hitTestClamped(e,t){if(this.charBoxes.length===0)return 0;const i=this.lines.length===0?-1:this.hitTestLine(t);return i<0?e<=this.containerBox.x?0:e>=this.containerBox.x+this.containerBox.width?this.charBoxes.length:ne(this.cursorIndex,0,this.charBoxes.length):this.closestIndexInLine(i,e)}recomputeLines(){if(this.explicitLineBreakIndices.length>0){this.lines=this.linesFromBreakIndices(this.charBoxes,this.explicitLineBreakIndices,this.explicitLineLayouts);return}this.lines=this.detectLines(this.charBoxes,this.lineTolerance)}normalizeCharLayout(e,t){const i=[],n=[];for(const o of e){if(!o){n.push(i.length);continue}i.push({...o})}const s=[...n,...t??[]],r=this.normalizeBreakIndices(s,i.length);return{charBoxes:i,lineBreakIndices:r}}normalizeBreakIndices(e,t){if(e.length===0)return[];const i=[];for(const n of e){if(!Number.isFinite(n))continue;const s=ne(Math.round(n),0,t);i.push(s)}return i.sort((n,s)=>n-s)}normalizeLineLayouts(e){if(!e||e.length===0)return[];const t=[];for(const i of e)i&&(!Number.isFinite(i.y)||!Number.isFinite(i.height)||t.push({y:i.y,height:Math.max(1,i.height)}));return t}linesFromBreakIndices(e,t,i){if(e.length===0&&t.length===0)return[];if(t.length===0)return this.detectLines(e,this.lineTolerance);const n=[];let s=0;for(const r of t)if(!(r<s||r>e.length)){if(r===s){n.push(this.createEmptyLine(s,n[n.length-1],i[n.length]));continue}n.push(this.withLineLayout(this.aggregateLine(e,s,r-1),i[n.length])),s=r}return s<e.length?n.push(this.withLineLayout(this.aggregateLine(e,s,e.length-1),i[n.length])):n.push(this.createEmptyLine(s,n[n.length-1],i[n.length])),n}detectLines(e,t){if(e.length===0)return[];const i=[],n=.65;let s=0;for(let r=1;r<e.length;r++){const o=e[r-1],c=e[r];if(!o||!c)continue;const l=Math.abs(c.y-o.y),h=c.x+t<o.x,d=$a(o,c),g=Math.min(o.height,c.height),y=(g>0?d/g:0)<n;(h||l>t&&y)&&(i.push(this.aggregateLine(e,s,r-1)),s=r)}return i.push(this.aggregateLine(e,s,e.length-1)),i}aggregateLine(e,t,i){let n=0,s=0,r=0;for(let o=t;o<=i;o++){const c=e[o];c&&(n+=c.y,s+=1,r=Math.max(r,c.height))}return s===0?{startIndex:t,endIndex:i,y:this.containerBox.y,height:this.containerBox.height,charCount:Math.max(0,i-t+1)}:{startIndex:t,endIndex:i,y:n/s,height:r,charCount:i-t+1}}withLineLayout(e,t){return t?{...e,y:t.y,height:Math.max(1,t.height)}:e}createEmptyLine(e,t,i){if(i)return{startIndex:e,endIndex:e-1,y:i.y,height:Math.max(1,i.height),charCount:0};const n=Math.max(1,(t==null?void 0:t.height)??this.containerBox.height),s=t!==void 0?t.y+n:this.alignY(this.containerBox.y,this.containerBox.height);return{startIndex:e,endIndex:e-1,y:s,height:n,charCount:0}}alignY(e,t){return this.verticalAlign==="top"?e-t/2:this.verticalAlign==="bottom"?e+t/2:e}indexToX(e,t){if(this.charBoxes.length===0)return this.containerBox.x;if(e<=0)return this.containerBox.x;const i=t??this.getLineIndex(e);if(i<0)return this.containerBox.x;const n=this.lines[i];if(!n)return this.containerBox.x;if(e<=n.startIndex)return this.containerBox.x;if(e>n.endIndex+1){const r=this.charBoxes[this.charBoxes.length-1];return r?r.x+r.width:this.containerBox.x}const s=this.charBoxes[e-1];return s?s.x+s.width:this.containerBox.x}getGapPositions(e){const t=this.lines[e];if(!t)return[];const i=[{index:t.startIndex,x:this.containerBox.x}];for(let n=t.startIndex;n<=t.endIndex;n++){const s=this.charBoxes[n];s&&i.push({index:n+1,x:s.x+s.width})}return i}closestIndexInLine(e,t){const i=this.getGapPositions(e);if(i.length===0)return 0;let n=i[0],s=Math.abs(t-n.x);for(let r=1;r<i.length;r++){const o=i[r];if(!o)continue;const c=Math.abs(t-o.x);c<s&&(n=o,s=c)}return n.index}}const Ua={width:4,height:24,heightMode:"lineHeight",color:"#00f5ff",glowColor:"#00f5ff",glowIntensity:.9,blinkSpeed:1.05,blinkEnabled:!0,billboard:!0,depthTest:!1,renderOrder:100,mode:"plane"},Wa={fillColor:"rgba(0,120,255,0.30)",blendMode:"normal",animate:!1,strategy:"perChar"},Ha={charBoxColor:"rgba(64,160,255,0.55)",charBoxFill:"rgba(64,160,255,0.10)",charIndexColor:"rgba(255,255,255,0.85)",rowHoverColor:"rgba(200,200,200,0.10)",rowBoundaryColor:"rgba(255,255,255,0.22)",gapColor:"rgba(255,153,0,0.7)",baselineColor:"rgba(255,51,51,0.55)",containerColor:"rgba(255,255,255,0.30)"},Ya={showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0};class Xa{constructor(e){I(this,"renderer");I(this,"cursorStyle");I(this,"selectionStyle");I(this,"debugStyle");I(this,"debugVisibility");I(this,"enableSelection");I(this,"enableDebug");I(this,"debugYAxisUp");I(this,"visible",!0);I(this,"cursorState",null);I(this,"selectionBoxes",[]);I(this,"debugData",null);I(this,"viewTransform",{x:0,y:0,scaleX:1,scaleY:1,rotation:0});this.renderer=e.renderer,this.cursorStyle={...Ua,...e.cursorStyle},this.selectionStyle={...Wa,...e.selectionStyle},this.debugStyle={...Ha,...e.debugStyle},this.debugVisibility={...Ya,...e.debugVisibility},this.enableSelection=e.enableSelection??!0,this.enableDebug=e.enableDebug??!1,this.debugYAxisUp=e.debugYAxisUp??!1}updateCursor(e,t){this.cursorState={position:e,lineHeight:t}}updateSelection(e){this.selectionBoxes=e.map(t=>({...t}))}updateDebugInfo(e){const t={containerBox:{...e.containerBox},charBoxes:e.charBoxes.map(i=>({...i})),lines:e.lines.map(i=>({...i}))};e.chars&&(t.chars=[...e.chars]),e.gapPositions&&(t.gapPositions=[...e.gapPositions]),e.hoverLineIndex!==void 0&&(t.hoverLineIndex=e.hoverLineIndex),this.debugData=t}setCursorStyle(e){this.cursorStyle={...this.cursorStyle,...e}}setSelectionStyle(e){this.selectionStyle={...this.selectionStyle,...e}}setDebugMode(e){this.enableDebug=e}setDebugVisibility(e){this.debugVisibility={...this.debugVisibility,...e}}setViewTransform(e){this.viewTransform={...this.viewTransform,...e}}show(){this.visible=!0}hide(){this.visible=!1}toggle(){this.visible=!this.visible}render(){if(this.renderer.beginFrame(),!this.visible){this.renderer.endFrame();return}this.renderer.setTransform({x:this.viewTransform.x??0,y:this.viewTransform.y??0,scaleX:this.viewTransform.scaleX??1,scaleY:this.viewTransform.scaleY??1,rotation:this.viewTransform.rotation??0}),this.enableDebug&&this.debugData&&this.drawDebug(this.debugData),this.enableSelection&&this.selectionBoxes.length>0&&this.drawSelection(this.selectionBoxes),this.cursorState&&this.drawCursor(this.cursorState.position,this.cursorState.lineHeight),this.renderer.resetTransform(),this.renderer.endFrame()}dispose(){this.renderer.destroy(),this.selectionBoxes=[],this.cursorState=null,this.debugData=null}drawCursor(e,t){const i=Math.max(.2,this.cursorStyle.blinkSpeed)*1e3;if(!(!this.cursorStyle.blinkEnabled||Date.now()%i<i/2))return;const s=this.cursorStyle.heightMode==="fixed"?this.cursorStyle.height:Math.max(this.cursorStyle.height,t*.8);this.cursorStyle.glowColor&&(this.cursorStyle.glowIntensity??0)>0&&this.renderer.drawLine({x1:e.x,y1:e.y-s/2,x2:e.x,y2:e.y+s/2,color:this.cursorStyle.glowColor,width:this.cursorStyle.width+2,opacity:Math.min(1,this.cursorStyle.glowIntensity??0)}),this.renderer.drawLine({x1:e.x,y1:e.y-s/2,x2:e.x,y2:e.y+s/2,color:this.cursorStyle.color,width:this.cursorStyle.width,opacity:1})}drawSelection(e){if(this.selectionStyle.strategy==="merged"){this.mergeBoxes(e).forEach(t=>this.drawSelectionQuad(t));return}e.forEach(t=>this.drawSelectionQuad(t))}drawSelectionQuad(e){const t={x:e.x,y:e.y,width:e.width,height:e.height,fillColor:this.selectionStyle.fillColor,blendMode:this.selectionStyle.blendMode==="additive"?"lighter":this.selectionStyle.blendMode==="multiply"?"multiply":"source-over"};this.renderer.drawQuad({...t,...this.selectionStyle.borderColor?{borderColor:this.selectionStyle.borderColor}:{},...this.selectionStyle.borderWidth!==void 0?{borderWidth:this.selectionStyle.borderWidth}:{},...this.selectionStyle.cornerRadius!==void 0?{cornerRadius:this.selectionStyle.cornerRadius}:{}})}drawDebug(e){var i;this.renderer.drawBox({box:{x:e.containerBox.x,y:e.containerBox.y+e.containerBox.height/2,width:e.containerBox.width,height:e.containerBox.height},color:this.debugStyle.containerColor,opacity:1,lineWidth:1});const t=e.containerBox.x+e.containerBox.width+60;e.lines.forEach((n,s)=>{const r=this.debugYAxisUp?n.y+n.height/2:n.y-n.height/2,o=this.debugYAxisUp?n.y-n.height/2:n.y+n.height/2;e.hoverLineIndex===s&&this.renderer.drawQuad({x:0,y:n.y,width:t,height:n.height,fillColor:this.debugStyle.rowHoverColor}),this.renderer.drawLine({x1:0,y1:r,x2:t,y2:r,color:this.debugStyle.rowBoundaryColor,dashed:[5,5]}),this.renderer.drawLine({x1:0,y1:o,x2:t,y2:o,color:this.debugStyle.rowBoundaryColor,dashed:[5,5]}),this.debugVisibility.showLineIndices&&this.renderer.drawText({text:`L${s}`,x:8,y:r+(this.debugYAxisUp?-2:2),color:"rgba(255,255,255,0.65)",font:"12px monospace"})}),e.charBoxes.forEach((n,s)=>{var l;const r=this.debugYAxisUp?n.y+n.height/2:n.y-n.height/2,o=this.debugYAxisUp?-2:2,c=this.debugYAxisUp?-Math.max(8,n.height*.2):Math.max(8,n.height*.2);if(this.debugVisibility.showCharBoxes&&this.renderer.drawQuad({x:n.x,y:n.y,width:n.width,height:n.height,fillColor:this.debugStyle.charBoxFill,borderColor:this.debugStyle.charBoxColor,borderWidth:1}),this.debugVisibility.showCharIndices&&this.renderer.drawText({text:String(s),x:n.x+2,y:r+o,color:this.debugStyle.charIndexColor,font:"10px monospace"}),this.debugVisibility.showChars){const h=(l=e.chars)==null?void 0:l[s];if(!h)return;this.renderer.drawText({text:h,x:n.x+2,y:r+c,color:"rgba(255,255,255,0.95)",font:`${Math.max(12,Math.round(n.height*.6))}px monospace`})}}),(i=e.gapPositions)==null||i.forEach(n=>{this.renderer.drawLine({x1:n.x,y1:n.y-n.height/2,x2:n.x,y2:n.y+n.height/2,color:this.debugStyle.gapColor,opacity:n.strong?.9:.55,width:1})})}mergeBoxes(e){if(e.length===0)return[];const t=[...e].sort((n,s)=>n.y===s.y?n.x-s.x:n.y-s.y),i=[];for(const n of t){const s=i[i.length-1];if(!s){i.push({...n});continue}const r=Math.abs(s.y-n.y)<=1,o=n.x<=s.x+s.width+1,c=Math.abs(s.height-n.height)<=1;r&&o&&c?s.width=Math.max(s.x+s.width,n.x+n.width)-s.x:i.push({...n})}return i}}function ui(a){const e=a.match(/rgba?\(([^)]+)\)/i);if(e){const n=(e[1]??"").split(",").map(l=>Number(l.trim())),[s=255,r=255,o=255,c=1]=n;return{color:new f.Color(s/255,r/255,o/255),alpha:Number.isFinite(c)?c:1}}const t=new f.Color;return t.setStyle(a),{color:t,alpha:1}}class qa{constructor(e){I(this,"scene");I(this,"camera");I(this,"frameGroup",new f.Group);I(this,"currentTransform",{x:0,y:0,scaleX:1,scaleY:1,rotation:0});I(this,"canvas",null);this.scene=e.scene,this.camera=e.camera,this.scene.add(this.frameGroup)}initialize(e){this.canvas=e}destroy(){this.clearFrame(),this.scene.remove(this.frameGroup)}beginFrame(){this.clearFrame()}endFrame(){this.camera}drawQuad(e){const t=this.currentTransform.scaleX??1,i=this.currentTransform.scaleY??1,n=this.transformPoint(e.x+e.width/2,e.y),s=this.createQuadMesh(n.x-e.width*t/2,n.y,Math.abs(e.width*t),Math.abs(e.height*i),e.fillColor,e.opacity);if(s&&this.frameGroup.add(s),e.borderColor){const r=this.createRectBorder(n.x-e.width*t/2,n.y,Math.abs(e.width*t),Math.abs(e.height*i),e.borderColor,e.borderWidth??1,e.opacity??1);this.frameGroup.add(r)}}drawLine(e){const t=this.transformPoint(e.x1,e.y1),i=this.transformPoint(e.x2,e.y2),n=ui(e.color),s=(e.opacity??1)*n.alpha;if(e.dashed&&e.dashed.length>0){const h=[new f.Vector3(t.x,t.y,0),new f.Vector3(i.x,i.y,0)],d=new f.BufferGeometry().setFromPoints(h),g=new f.LineDashedMaterial({color:n.color,linewidth:e.width??1,transparent:s<1,opacity:s,dashSize:e.dashed[0]??4,gapSize:e.dashed[1]??2,depthTest:!1}),m=new f.Line(d,g);m.computeLineDistances(),m.renderOrder=e.renderOrder??1,this.frameGroup.add(m);return}const r=new _a.LineGeometry;r.setPositions([t.x,t.y,0,i.x,i.y,0]);const o=new bt.LineMaterial({color:n.color,linewidth:e.width??1,worldUnits:!1,transparent:s<1,opacity:s,depthTest:!1}),c=this.getResolution();o.resolution.set(c.x,c.y);const l=new Ca.Line2(r,o);l.computeLineDistances(),l.renderOrder=e.renderOrder??1,this.frameGroup.add(l)}drawText(e){var F;const t=e.font??"20px monospace",i=Number(((F=t.match(/(\d+(?:\.\d+)?)px/))==null?void 0:F[1])??20),n=4,s=document.createElement("canvas");let r=s.getContext("2d");if(!r)return;r.font=t;const c=Math.max(1,Math.ceil(r.measureText(e.text).width))+n*2,l=Math.max(1,Math.ceil(i*1.4));if(s.width=c,s.height=l,r=s.getContext("2d"),!r)return;r.clearRect(0,0,s.width,s.height),r.font=t;const h=e.align??"left",d=e.baseline??"top";r.textAlign=h,r.textBaseline=d;const g=ui(e.color);r.fillStyle=`rgba(${Math.round(g.color.r*255)}, ${Math.round(g.color.g*255)}, ${Math.round(g.color.b*255)}, ${e.opacity??g.alpha})`;const m=h==="center"?s.width/2:h==="right"?s.width-n:n,y=d==="middle"?s.height/2:d==="bottom"?s.height-n:n;r.fillText(e.text,m,y);const w=this.isYAxisUp(),C=new f.CanvasTexture(s);C.flipY=w,C.needsUpdate=!0;const b=Math.abs(this.currentTransform.scaleX??1),x=Math.abs(this.currentTransform.scaleY??1),A=Math.max(1,s.width*b),_=Math.max(1,s.height*x),L=new f.PlaneGeometry(A,_),T=new f.MeshBasicMaterial({map:C,transparent:!0,depthTest:!1,depthWrite:!1,side:f.DoubleSide}),O=new f.Mesh(L,T),k=this.transformPoint(e.x,e.y),E=h==="center"?0:h==="right"?-A/2:A/2,M=d==="middle"?0:d==="bottom"?w?_/2:-_/2:w?-_/2:_/2;O.position.set(k.x+E,k.y+M,.2),O.renderOrder=10,this.frameGroup.add(O)}drawBox(e){const t=this.currentTransform.scaleX??1,i=this.currentTransform.scaleY??1,n=this.transformPoint(e.box.x+e.box.width/2,e.box.y),s=this.createRectBorder(n.x-e.box.width*t/2,n.y,Math.abs(e.box.width*t),Math.abs(e.box.height*i),e.color,e.lineWidth??1,e.opacity??1);s.renderOrder=e.renderOrder??2,this.frameGroup.add(s)}setTransform(e){this.currentTransform={x:e.x??0,y:e.y??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,rotation:e.rotation??0}}resetTransform(){this.currentTransform={x:0,y:0,scaleX:1,scaleY:1,rotation:0}}transformPoint(e,t){const i=this.currentTransform.scaleX??1,n=this.currentTransform.scaleY??1,s=(this.currentTransform.x??0)+e*i,r=(this.currentTransform.y??0)+t*n,o=this.currentTransform.rotation??0;if(o===0)return{x:s,y:r};const c=Math.cos(o),l=Math.sin(o);return{x:s*c-r*l,y:s*l+r*c}}isYAxisUp(){return this.camera instanceof f.OrthographicCamera?this.camera.top>=this.camera.bottom:!0}createLineQuad(e,t,i,n,s){const r=t.x-e.x,o=t.y-e.y,c=Math.max(.001,Math.hypot(r,o)),l=Math.atan2(o,r),h=new f.PlaneGeometry(c,i),d=new f.MeshBasicMaterial({color:n,transparent:s<1,opacity:s,side:f.DoubleSide,depthTest:!1}),g=new f.Mesh(h,d);return g.position.set((e.x+t.x)/2,(e.y+t.y)/2,0),g.rotation.z=l,g}createQuadMesh(e,t,i,n,s,r=1){if(!s)return null;const o=new f.PlaneGeometry(i,n),c=ui(s),l=new f.MeshBasicMaterial({color:c.color,transparent:r*c.alpha<1,opacity:r*c.alpha,side:f.DoubleSide,depthTest:!1}),h=new f.Mesh(o,l);return h.position.set(e+i/2,t,0),h.renderOrder=1,h}createRectBorder(e,t,i,n,s,r,o){const c=ui(s),l=i/2,h=n/2,d=e+l,g=t,m=[new f.Vector3(d-l,g-h,0),new f.Vector3(d+l,g-h,0),new f.Vector3(d+l,g+h,0),new f.Vector3(d-l,g+h,0)],y=new f.BufferGeometry().setFromPoints(m),w=new f.LineBasicMaterial({color:c.color,transparent:o*c.alpha<1,opacity:o*c.alpha,linewidth:r,depthTest:!1});return new f.LineLoop(y,w)}clearFrame(){for(;this.frameGroup.children.length>0;){const e=this.frameGroup.children.pop();e&&this.disposeObject(e)}}disposeObject(e){if("geometry"in e&&e.geometry instanceof f.BufferGeometry&&e.geometry.dispose(),"material"in e){const t=e.material;Array.isArray(t)?t.forEach(i=>this.disposeMaterial(i)):t&&this.disposeMaterial(t)}"children"in e&&e.children.length>0&&[...e.children].forEach(t=>this.disposeObject(t)),e.removeFromParent()}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),e.dispose()}getResolution(){return this.canvas?{x:this.canvas.width||1,y:this.canvas.height||1}:typeof window<"u"?{x:window.innerWidth||1,y:window.innerHeight||1}:{x:1,y:1}}}function Za(a){return a===B.MTextLineAlignment.TOP?"superscript":a===B.MTextLineAlignment.BOTTOM?"subscript":"normal"}function Ja(a){return a==="superscript"?B.MTextLineAlignment.TOP:a==="subscript"?B.MTextLineAlignment.BOTTOM:B.MTextLineAlignment.MIDDLE}function vs(a){return{...a,align:Ja(a.script)}}function At(a){return{underline:a.underline,overline:a.overline,strikeThrough:a.strikeThrough,script:Za(a.align),aci:a.aci,rgb:a.rgb?[...a.rgb]:null,align:a.align,fontFace:{...a.fontFace},capHeight:{...a.capHeight},widthFactor:{...a.widthFactor},charTrackingFactor:{...a.charTrackingFactor},oblique:a.oblique,paragraph:{indent:a.paragraph.indent,left:a.paragraph.left,right:a.paragraph.right,align:a.paragraph.align,tabs:[...a.paragraph.tabs]}}}function q(a){return{underline:a.underline,overline:a.overline,strikeThrough:a.strikeThrough,script:a.script,aci:a.aci,rgb:a.rgb?[...a.rgb]:null,align:a.align,fontFace:{...a.fontFace},capHeight:{...a.capHeight},widthFactor:{...a.widthFactor},charTrackingFactor:{...a.charTrackingFactor},oblique:a.oblique,paragraph:{indent:a.paragraph.indent,left:a.paragraph.left,right:a.paragraph.right,align:a.paragraph.align,tabs:[...a.paragraph.tabs]}}}function Ct(a){return a.type==="char"||a.type==="stack"||a.type==="paragraphBreak"||a.type==="columnBreak"||a.type==="wrapAtDimLine"}function Qa(a,e){return a.underline===e.underline&&a.overline===e.overline&&a.strikeThrough===e.strikeThrough&&a.script===e.script&&a.aci===e.aci&&JSON.stringify(a.rgb)===JSON.stringify(e.rgb)&&a.align===e.align&&a.fontFace.family===e.fontFace.family&&a.fontFace.style===e.fontFace.style&&a.fontFace.weight===e.fontFace.weight&&a.capHeight.value===e.capHeight.value&&a.capHeight.isRelative===e.capHeight.isRelative&&a.widthFactor.value===e.widthFactor.value&&a.widthFactor.isRelative===e.widthFactor.isRelative&&a.charTrackingFactor.value===e.charTrackingFactor.value&&a.charTrackingFactor.isRelative===e.charTrackingFactor.isRelative&&a.oblique===e.oblique&&a.paragraph.indent===e.paragraph.indent&&a.paragraph.left===e.paragraph.left&&a.paragraph.right===e.paragraph.right&&a.paragraph.align===e.paragraph.align&&JSON.stringify(a.paragraph.tabs)===JSON.stringify(e.paragraph.tabs)}function Ss(a,e){const t=a??At(new B.MTextContext),i=vs(t),n=vs(e);if(Qa(i,n))return"";let s="";if(i.underline!==n.underline&&(s+=n.underline?"\\L":"\\l"),i.overline!==n.overline&&(s+=n.overline?"\\O":"\\o"),i.strikeThrough!==n.strikeThrough&&(s+=n.strikeThrough?"\\K":"\\k"),i.align!==n.align&&(s+=`\\A${n.align};`),(i.aci!==n.aci||JSON.stringify(i.rgb)!==JSON.stringify(n.rgb))&&(n.rgb?s+=`\\c${B.rgb2int(n.rgb)};`:s+=`\\C${n.aci??256};`),i.fontFace.family!==n.fontFace.family||i.fontFace.style!==n.fontFace.style||i.fontFace.weight!==n.fontFace.weight){const r=n.fontFace.weight>=700?1:0,o=n.fontFace.style==="Italic"?1:0;s+=`\\f${n.fontFace.family}|b${r}|i${o};`}return(i.capHeight.value!==n.capHeight.value||i.capHeight.isRelative!==n.capHeight.isRelative)&&(s+=`\\H${hn(n.capHeight)};`),(i.widthFactor.value!==n.widthFactor.value||i.widthFactor.isRelative!==n.widthFactor.isRelative)&&(s+=`\\W${hn(n.widthFactor)};`),(i.charTrackingFactor.value!==n.charTrackingFactor.value||i.charTrackingFactor.isRelative!==n.charTrackingFactor.isRelative)&&(s+=`\\T${hn(n.charTrackingFactor)};`),i.oblique!==n.oblique&&(s+=`\\Q${_t(n.oblique)};`),JSON.stringify(i.paragraph)!==JSON.stringify(n.paragraph)&&(s+=`\\p${ec(n.paragraph)};`),s}function hn(a){return`${_t(a.value)}${a.isRelative?"x":""}`}function _t(a){return Number.isInteger(a),a.toString()}function ec(a){const e=[`i${_t(a.indent)}`,`l${_t(a.left)}`,`r${_t(a.right)}`];return a.align!==B.MTextParagraphAlignment.DEFAULT&&e.push(`q${tc(a.align)}`),a.tabs.length>0&&e.push(`t${a.tabs.map(t=>String(t)).join(",")}`),e.join(",")}function tc(a){switch(a){case B.MTextParagraphAlignment.LEFT:return"l";case B.MTextParagraphAlignment.RIGHT:return"r";case B.MTextParagraphAlignment.CENTER:return"c";case B.MTextParagraphAlignment.JUSTIFIED:return"j";case B.MTextParagraphAlignment.DISTRIBUTED:return"d";default:return"x"}}function As(a,e,t={}){const i=new B.MTextParser(a,e,{...t,yieldPropertyCommands:!1}),n=[];for(const s of i.parse()){const r=At(s.ctx);switch(s.type){case B.TokenType.WORD:{const o=s.data;for(const c of o)n.push({type:"char",value:c,style:q(r)});break}case B.TokenType.SPACE:n.push({type:"char",value:" ",style:q(r)});break;case B.TokenType.NBSP:n.push({type:"char",value:" ",style:q(r)});break;case B.TokenType.TABULATOR:n.push({type:"char",value:" ",style:q(r)});break;case B.TokenType.STACK:{const[o,c,l]=s.data,h=q(r);l==="^"&&(o.length===0&&c.length>0?h.script="subscript":o.length>0&&c.length===0?h.script="superscript":h.script="normal"),n.push({type:"stack",numerator:o,denominator:c,divider:l,style:h});break}case B.TokenType.NEW_PARAGRAPH:n.push({type:"paragraphBreak",style:q(r)});break;case B.TokenType.NEW_COLUMN:n.push({type:"columnBreak",style:q(r)});break;case B.TokenType.WRAP_AT_DIMLINE:n.push({type:"wrapAtDimLine",style:q(r)});break}}return{nodes:n}}function ic(a){const e=At(new B.MTextContext);let t="",i=0;for(;i<a.nodes.length;){const n=a.nodes[i];if(!n)break;if(!Ct(n)){t+=Ls(n),i+=1;continue}const s=n.style;let r="",o=i;for(;o<a.nodes.length;){const c=a.nodes[o];if(!c||!Ct(c)||!Ps(s,c.style))break;r+=Ls(c),o+=1}Ps(s,e)?t+=r:t+=`{${Ss(null,s)}${r}}`,i=o}return t}function di(a,e,t){if(t<=0)return a;const i=pi(e,0,a.nodes.length),n=pi(t,0,a.nodes.length-i);return a.nodes.splice(i,n),a}function nc(a,e,t,i,n){const s=pi(e,0,a.nodes.length),r=pi(t,0,a.nodes.length-s),o=n??Cs(a,s)??At(new B.MTextContext),c=oc(i,o);return a.nodes.splice(s,r,...c),a}function Cs(a,e){for(let t=e-1;t>=0;t--){const i=a.nodes[t];if(i&&Ct(i))return q(i.style)}for(let t=e;t<a.nodes.length;t++){const i=a.nodes[t];if(i&&Ct(i))return q(i.style)}}function sc(a){return a===" "?"\\~":a===" "?"^I":a==="\\"?"\\\\":a==="{"?"\\{":a==="}"?"\\}":a==="^"?"\\U+005E":a==="%"?"\\U+0025":a===`
|
|
374
|
-
`?"\\P":a==="\r"?"":a}function _s(a){return a.replace(/[\\;/#^]/g,"\\$&")}function Ps(a,e){return Ss(a,e)===""}function Ls(a){switch(a.type){case"char":return sc(a.value);case"stack":return rc(a.numerator,a.denominator,a.divider);case"paragraphBreak":return"\\P";case"columnBreak":return"\\N";case"wrapAtDimLine":return"\\X"}}function rc(a,e,t){const i=_s(a),n=_s(e);if(t==="^"){if(i.length===0&&n.length>0)return`\\S^ ${n};`;if(i.length>0&&n.length===0)return`\\S${i}^ ;`;if(i.length===0&&n.length===0)return"\\S^ ;"}return`\\S${i}${t}${n};`}function oc(a,e){const t=[];for(const i of a){if(i===`
|
|
375
|
-
`){t.push({type:"paragraphBreak",style:q(e)});continue}t.push({type:"char",value:i,style:q(e)})}return t}function pi(a,e,t){return Math.max(e,Math.min(t,a))}class Z{constructor(e={nodes:[]}){I(this,"_ast");I(this,"_cursor");I(this,"_selection",null);this._ast=typeof e=="string"?As(e):Z.cloneAst(e),this._cursor=this._ast.nodes.length}static fromMText(e,t){return new Z(As(e,t))}get ast(){return this._ast}get length(){return this._ast.nodes.length}get cursor(){return this._cursor}set cursor(e){this._cursor=Z.clamp(e,0,this.length),this._selection=null}get selection(){return this._selection?{...this._selection}:null}setSelection(e,t){const i=Z.normalizeSelection(e,t,this.length);return this._selection=i.start===i.end?null:i,this._cursor=Z.clamp(t,0,this.length),this}clearSelection(){return this._selection=null,this}moveCursor(e,t=!1){const i=Z.clamp(this._cursor+e,0,this.length);if(t){const n=this._selection?this._selection.start:this._cursor;this.setSelection(n,i)}else this.cursor=i;return this}selectAll(){return this.setSelection(0,this.length),this}insertText(e,t){const{start:i,end:n}=this.getActiveRange();return nc(this._ast,i,n-i,e,t),this._cursor=i+e.length,this._selection=null,this}deleteBackward(e=1){if(this.hasSelection()){const{start:i,end:n}=this.getActiveRange();return di(this._ast,i,n-i),this._cursor=i,this._selection=null,this}if(e<=0||this._cursor<=0)return this;const t=Math.min(e,this._cursor);return di(this._ast,this._cursor-t,t),this._cursor-=t,this}deleteForward(e=1){if(this.hasSelection()){const{start:t,end:i}=this.getActiveRange();return di(this._ast,t,i-t),this._cursor=t,this._selection=null,this}return e<=0||this._cursor>=this.length?this:(di(this._ast,this._cursor,e),this)}replaceSelection(e,t){return this.insertText(e,t)}toMText(){return ic(this._ast)}transaction(e){const t={ast:Z.cloneAst(this._ast),cursor:this._cursor,selection:this._selection?{...this._selection}:null};try{e(this)}catch(i){throw this._ast=t.ast,this._cursor=t.cursor,this._selection=t.selection,i}return this}hasSelection(){return!!(this._selection&&this._selection.start!==this._selection.end)}getActiveRange(){return this._selection?{...this._selection}:{start:this._cursor,end:this._cursor}}getReferenceStyle(e){return Cs(this._ast,e)??At(new B.MTextContext)}static cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:q(t.style)}:t.type==="stack"?{...t,style:q(t.style)}:{...t,style:q(t.style)})}}static normalizeSelection(e,t,i){const n=Z.clamp(e,0,i),s=Z.clamp(t,0,i);return n<=s?{start:n,end:s}:{start:s,end:n}}static clamp(e,t,i){return Math.max(t,Math.min(i,e))}}class un{constructor(e){I(this,"document");I(this,"selectionAnchor",null);this.document=e}get anchor(){return this.selectionAnchor}execute(e){switch(e.type){case"setCursor":this.document.cursor=e.index,this.selectionAnchor=null;break;case"setSelection":this.document.setSelection(e.start,e.end),this.selectionAnchor=e.start;break;case"clearSelection":this.document.clearSelection(),this.selectionAnchor=null;break;case"moveLeft":this.moveCursorTo(this.document.cursor-1,e.extend??!1);break;case"moveRight":this.moveCursorTo(this.document.cursor+1,e.extend??!1);break;case"moveToStart":this.moveCursorTo(0,e.extend??!1);break;case"moveToEnd":this.moveCursorTo(this.document.length,e.extend??!1);break;case"selectAll":this.document.selectAll(),this.selectionAnchor=0;break;case"insertText":this.document.insertText(e.text,e.style),this.selectionAnchor=null;break;case"replaceSelection":this.document.replaceSelection(e.text,e.style),this.selectionAnchor=null;break;case"backspace":this.document.deleteBackward(e.count??1),this.selectionAnchor=null;break;case"delete":this.document.deleteForward(e.count??1),this.selectionAnchor=null;break}return this}handleKeyEvent(e){const t=!!(e.metaKey||e.ctrlKey);return t&&!e.altKey&&e.key.toLowerCase()==="a"?(this.execute({type:"selectAll"}),!0):e.key==="ArrowLeft"?(this.execute({type:"moveLeft",extend:!!e.shiftKey}),!0):e.key==="ArrowRight"?(this.execute({type:"moveRight",extend:!!e.shiftKey}),!0):e.key==="Home"?(this.execute({type:"moveToStart",extend:!!e.shiftKey}),!0):e.key==="End"?(this.execute({type:"moveToEnd",extend:!!e.shiftKey}),!0):e.key==="Backspace"?(this.execute({type:"backspace"}),!0):e.key==="Delete"?(this.execute({type:"delete"}),!0):e.key==="Enter"?(this.execute({type:"insertText",text:`
|
|
376
|
-
`}),!0):e.key==="Tab"?(this.execute({type:"insertText",text:" "}),!0):!t&&!e.altKey&&e.key.length===1?(this.execute({type:"insertText",text:e.key}),!0):!1}moveCursorTo(e,t){var n;const i=Math.max(0,Math.min(e,this.document.length));if(t){this.selectionAnchor===null&&(this.selectionAnchor=((n=this.document.selection)==null?void 0:n.start)??this.document.cursor),this.document.setSelection(this.selectionAnchor,i);return}this.document.cursor=i,this.selectionAnchor=null}}const ac={bold:'<svg viewBox="0 0 24 24"><path d="M7.8 19c-.3 0-.5 0-.6-.2l-.2-.5V5.7c0-.2 0-.4.2-.5l.6-.2h5c1.5 0 2.7.3 3.5 1 .7.6 1.1 1.4 1.1 2.5a3 3 0 0 1-.6 1.9c-.4.6-1 1-1.6 1.2.4.1.9.3 1.3.6s.8.7 1 1.2c.4.4.5 1 .5 1.6 0 1.3-.4 2.3-1.3 3-.8.7-2.1 1-3.8 1H7.8Zm5-8.3c.6 0 1.2-.1 1.6-.5.4-.3.6-.7.6-1.3 0-1.1-.8-1.7-2.3-1.7H9.3v3.5h3.4Zm.5 6c.7 0 1.3-.1 1.7-.4.4-.4.6-.9.6-1.5s-.2-1-.7-1.4c-.4-.3-1-.4-2-.4H9.4v3.8h4Z" fill-rule="evenodd"></path></svg>',italic:'<svg viewBox="0 0 24 24"><path d="m16.7 4.7-.1.9h-.3c-.6 0-1 0-1.4.3-.3.3-.4.6-.5 1.1l-2.1 9.8v.6c0 .5.4.8 1.4.8h.2l-.2.8H8l.2-.8h.2c1.1 0 1.8-.5 2-1.5l2-9.8.1-.5c0-.6-.4-.8-1.4-.8h-.3l.2-.9h5.8Z" fill-rule="evenodd"></path></svg>',underline:'<svg viewBox="0 0 24 24"><path d="M16 5c.6 0 1 .4 1 1v5.5a4 4 0 0 1-.4 1.8l-1 1.4a5.3 5.3 0 0 1-5.5 1 5 5 0 0 1-1.6-1c-.5-.4-.8-.9-1.1-1.4a4 4 0 0 1-.4-1.8V6c0-.6.4-1 1-1s1 .4 1 1v5.5c0 .3 0 .6.2 1l.6.7a3.3 3.3 0 0 0 2.2.8 3.4 3.4 0 0 0 2.2-.8c.3-.2.4-.5.6-.8l.2-.9V6c0-.6.4-1 1-1ZM8 17h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 0 1 0-2Z" fill-rule="evenodd"></path></svg>',overline:'<svg viewBox="0 0 24 24"><path d="M5 4h14v1.5H5V4zm7 3.5c3.04 0 5.5 2.46 5.5 5.5v4.5h-2.25v-4.5c0-1.79-1.46-3.25-3.25-3.25S8.75 11.21 8.75 13v4.5H6.5V13c0-3.04 2.46-5.5 5.5-5.5z"></path></svg>',strike:'<svg viewBox="0 0 24 24"><g fill-rule="evenodd"><path d="M15.6 8.5c-.5-.7-1-1.1-1.3-1.3-.6-.4-1.3-.6-2-.6-2.7 0-2.8 1.7-2.8 2.1 0 1.6 1.8 2 3.2 2.3 4.4.9 4.6 2.8 4.6 3.9 0 1.4-.7 4.1-5 4.1A6.2 6.2 0 0 1 7 16.4l1.5-1.1c.4.6 1.6 2 3.7 2 1.6 0 2.5-.4 3-1.2.4-.8.3-2-.8-2.6-.7-.4-1.6-.7-2.9-1-1-.2-3.9-.8-3.9-3.6C7.6 6 10.3 5 12.4 5c2.9 0 4.2 1.6 4.7 2.4l-1.5 1.1Z"></path><path d="M5 11h14a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Z" fill-rule="nonzero"></path></g></svg>',superscript:'<svg viewBox="0 0 24 24"><path d="M15 9.4 10.4 14l4.6 4.6-1.4 1.4L9 15.4 4.4 20 3 18.6 7.6 14 3 9.4 4.4 8 9 12.6 13.6 8 15 9.4Zm5.9 1.6h-5v-1l1-.8 1.7-1.6c.3-.5.5-.9.5-1.3 0-.3 0-.5-.2-.7-.2-.2-.5-.3-.9-.3l-.8.2-.7.4-.4-1.2c.2-.2.5-.4 1-.5.3-.2.8-.2 1.2-.2.8 0 1.4.2 1.8.6.4.4.6 1 .6 1.6 0 .5-.2 1-.5 1.5l-1.3 1.4-.6.5h2.6V11Z" fill-rule="nonzero"></path></svg>',subscript:'<svg viewBox="0 0 24 24"><path d="m10.4 10 4.6 4.6-1.4 1.4L9 11.4 4.4 16 3 14.6 7.6 10 3 5.4 4.4 4 9 8.6 13.6 4 15 5.4 10.4 10ZM21 19h-5v-1l1-.8 1.7-1.6c.3-.4.5-.8.5-1.2 0-.3 0-.6-.2-.7-.2-.2-.5-.3-.9-.3a2 2 0 0 0-.8.2l-.7.3-.4-1.1 1-.6 1.2-.2c.8 0 1.4.3 1.8.7.4.4.6.9.6 1.5s-.2 1.1-.5 1.6a8 8 0 0 1-1.3 1.3l-.6.6h2.6V19Z" fill-rule="nonzero"></path></svg>',stack:'<svg viewBox="0 0 24 24"><path d="M12.4065 5.44832C12.8151 5.44832 13.1994 5.56542 13.5595 5.7996C13.9265 6.0267 14.2208 6.36024 14.4424 6.80022C14.664 7.23312 14.7748 7.74407 14.7748 8.33309C14.7748 8.9292 14.664 9.44725 14.4424 9.88724C14.2208 10.3201 13.9265 10.6501 13.5595 10.8772C13.1994 11.1043 12.8151 11.2179 12.4065 11.2179C12.0464 11.2179 11.7037 11.1291 11.3782 10.9517C11.0527 10.7743 10.7931 10.5082 10.5992 10.1534C10.5715 10.4585 10.5507 10.7743 10.5368 11.1008H9.75781V3H10.6407V6.4383C10.8415 6.11185 11.0977 5.86702 11.4094 5.7038C11.721 5.53348 12.0534 5.44832 12.4065 5.44832ZM12.2923 10.3663C12.7631 10.3663 13.1405 10.1888 13.4245 9.83402C13.7084 9.47919 13.8503 8.97888 13.8503 8.33309C13.8503 7.69439 13.7084 7.19763 13.4245 6.8428C13.1405 6.48797 12.7631 6.31056 12.2923 6.31056C11.8422 6.31056 11.4544 6.47378 11.1289 6.80022C10.8034 7.12667 10.6407 7.63762 10.6407 8.33309C10.6407 8.80856 10.7203 9.19887 10.8796 9.50402C11.0389 9.80918 11.2432 10.0292 11.4925 10.164C11.7417 10.2988 12.0083 10.3663 12.2923 10.3663Z"></path><path d="M12.0949 14.9531C12.7043 14.9531 13.2029 15.1447 13.5906 15.5279C13.9784 15.9041 14.1723 16.4434 14.1723 17.146V20.6056H13.3933C13.3725 20.2436 13.3587 20.0094 13.3517 19.903C13.1856 20.1727 12.9605 20.3785 12.6766 20.5204C12.3996 20.6552 12.0811 20.7227 11.721 20.7227C11.3747 20.7227 11.0493 20.6588 10.7446 20.531C10.4468 20.3962 10.2079 20.2011 10.0279 19.9456C9.84783 19.683 9.75781 19.3708 9.75781 19.0088C9.75781 18.4624 9.97248 18.033 10.4018 17.7208C10.8381 17.4014 11.399 17.2418 12.0845 17.2418C12.4723 17.2418 12.8739 17.295 13.2894 17.4014V17.3056C13.2894 16.7876 13.1856 16.4044 12.9778 16.156C12.777 15.9005 12.4688 15.7728 12.0534 15.7728C11.721 15.7728 11.444 15.8437 11.2224 15.9857C11.0008 16.1276 10.8138 16.337 10.6615 16.6137L9.98633 16.2199C10.1525 15.8367 10.4226 15.5315 10.7965 15.3044C11.1774 15.0702 11.6102 14.9531 12.0949 14.9531ZM13.2894 18.1572C12.8532 18.0437 12.455 17.9869 12.0949 17.9869C11.6448 17.9869 11.2951 18.0756 11.0458 18.253C10.8034 18.4305 10.6823 18.6788 10.6823 18.9982C10.6823 19.2962 10.7861 19.5304 10.9939 19.7007C11.2016 19.864 11.4717 19.9456 11.8041 19.9456C12.2126 19.9456 12.5623 19.8249 12.8532 19.5836C13.144 19.3353 13.2894 18.9946 13.2894 18.5617V18.1572Z""></path><rect x="6.02344" y="12.7119" width="11.9532" height="0.747077"></rect></svg>'},Ts="mlightcad-mtext-toolbar-style",Is=["Arial","Helvetica","Verdana","Tahoma","Trebuchet MS","Times New Roman","Georgia","Courier New","system-ui","sans-serif","serif","monospace"];function cc(){if(document.getElementById(Ts))return;const a=document.createElement("style");a.id=Ts,a.textContent=`
|
|
377
|
-
.ml-mtext-toolbar {
|
|
378
|
-
position: fixed;
|
|
379
|
-
left: 0;
|
|
380
|
-
top: 0;
|
|
381
|
-
z-index: 2147483000;
|
|
382
|
-
display: inline-flex;
|
|
383
|
-
align-items: center;
|
|
384
|
-
gap: 10px;
|
|
385
|
-
border-radius: 8px;
|
|
386
|
-
border: 1px solid;
|
|
387
|
-
padding: 8px;
|
|
388
|
-
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
|
|
389
|
-
font-size: 12px;
|
|
390
|
-
line-height: 1;
|
|
391
|
-
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.24);
|
|
392
|
-
user-select: none;
|
|
393
|
-
}
|
|
394
|
-
.ml-mtext-toolbar[data-theme='dark'] {
|
|
395
|
-
background: linear-gradient(180deg, #2a2d33 0%, #1d2025 100%);
|
|
396
|
-
border-color: #444b58;
|
|
397
|
-
color: #e8ecf4;
|
|
398
|
-
}
|
|
399
|
-
.ml-mtext-toolbar[data-theme='light'] {
|
|
400
|
-
background: linear-gradient(180deg, #ffffff 0%, #f2f4f8 100%);
|
|
401
|
-
border-color: #cfd5df;
|
|
402
|
-
color: #1e2430;
|
|
403
|
-
}
|
|
404
|
-
.ml-mtext-toolbar__group {
|
|
405
|
-
display: inline-flex;
|
|
406
|
-
align-items: center;
|
|
407
|
-
gap: 4px;
|
|
408
|
-
}
|
|
409
|
-
.ml-mtext-toolbar__separator {
|
|
410
|
-
width: 1px;
|
|
411
|
-
height: 24px;
|
|
412
|
-
opacity: 0.35;
|
|
413
|
-
}
|
|
414
|
-
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__separator {
|
|
415
|
-
background: #576177;
|
|
416
|
-
}
|
|
417
|
-
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__separator {
|
|
418
|
-
background: #b8c0ce;
|
|
419
|
-
}
|
|
420
|
-
.ml-mtext-toolbar__select,
|
|
421
|
-
.ml-mtext-toolbar__input,
|
|
422
|
-
.ml-mtext-toolbar__color,
|
|
423
|
-
.ml-mtext-toolbar__btn {
|
|
424
|
-
border: 1px solid;
|
|
425
|
-
border-radius: 6px;
|
|
426
|
-
height: 34px;
|
|
427
|
-
}
|
|
428
|
-
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__select,
|
|
429
|
-
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__input,
|
|
430
|
-
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__color,
|
|
431
|
-
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn {
|
|
432
|
-
background: #12161d;
|
|
433
|
-
border-color: #454d5f;
|
|
434
|
-
color: #f2f5fb;
|
|
435
|
-
}
|
|
436
|
-
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__select,
|
|
437
|
-
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__input,
|
|
438
|
-
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__color,
|
|
439
|
-
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn {
|
|
440
|
-
background: #ffffff;
|
|
441
|
-
border-color: #c7cdd8;
|
|
442
|
-
color: #1f2632;
|
|
443
|
-
}
|
|
444
|
-
.ml-mtext-toolbar__select {
|
|
445
|
-
min-width: 140px;
|
|
446
|
-
padding: 0 8px;
|
|
447
|
-
}
|
|
448
|
-
.ml-mtext-toolbar__input {
|
|
449
|
-
width: 64px;
|
|
450
|
-
padding: 0 8px;
|
|
451
|
-
}
|
|
452
|
-
.ml-mtext-toolbar__color {
|
|
453
|
-
width: 40px;
|
|
454
|
-
padding: 2px;
|
|
455
|
-
display: flex;
|
|
456
|
-
align-items: center;
|
|
457
|
-
justify-content: center;
|
|
458
|
-
}
|
|
459
|
-
.ml-mtext-toolbar__btn {
|
|
460
|
-
width: 34px;
|
|
461
|
-
display: inline-flex;
|
|
462
|
-
align-items: center;
|
|
463
|
-
justify-content: center;
|
|
464
|
-
cursor: pointer;
|
|
465
|
-
transition: border-color 0.14s ease, background 0.14s ease, color 0.14s ease;
|
|
466
|
-
}
|
|
467
|
-
.ml-mtext-toolbar__btn svg {
|
|
468
|
-
width: 24px;
|
|
469
|
-
height: 24px;
|
|
470
|
-
fill: currentColor;
|
|
471
|
-
}
|
|
472
|
-
.ml-mtext-toolbar__btn.is-active {
|
|
473
|
-
border-color: #2f9dff;
|
|
474
|
-
color: #2f9dff;
|
|
475
|
-
}
|
|
476
|
-
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn.is-active {
|
|
477
|
-
background: linear-gradient(180deg, #123252 0%, #0c243d 100%);
|
|
478
|
-
color: #8fcbff;
|
|
479
|
-
box-shadow: inset 0 0 0 1px rgba(143, 203, 255, 0.18);
|
|
480
|
-
}
|
|
481
|
-
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn.is-active {
|
|
482
|
-
background: linear-gradient(180deg, #dcebff 0%, #cfe3ff 100%);
|
|
483
|
-
color: #1d67ad;
|
|
484
|
-
box-shadow: inset 0 0 0 1px rgba(29, 103, 173, 0.16);
|
|
485
|
-
}
|
|
486
|
-
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn:hover {
|
|
487
|
-
background: #1f2530;
|
|
488
|
-
}
|
|
489
|
-
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn:hover {
|
|
490
|
-
background: #edf3ff;
|
|
491
|
-
}
|
|
492
|
-
`,document.head.appendChild(a)}function dn(a){return Math.max(0,Math.min(16777215,Math.round(a)))}function Es(a){return`#${(a===null?16777215:dn(a)).toString(16).padStart(6,"0")}`}function lc(a){return/^#[0-9a-fA-F]{6}$/.test(a)?Number.parseInt(a.slice(1),16):16777215}function hc(a){return a.isRgb&&a.rgbValue!==null?Es(a.rgbValue):a.isAci&&a.aci!==null?Es(B.getColorByIndex(a.aci)):"#ffffff"}function ks(a){const e=new B.MTextColor;return e.rgbValue=lc(a),e}function Bs(a){const e=new B.MTextColor;return a.aci!==null&&Number.isFinite(a.aci)?(e.aci=a.aci,e):a.rgb!==null?(e.rgbValue=dn(a.rgb),e):(e.rgbValue=16777215,e)}function uc(a){const e=a.trim().toLowerCase();return/^#[0-9a-f]{6}$/.test(e)?e:/^[0-9a-f]{6}$/.test(e)?`#${e}`:null}function Ne(a,e){const t=document.createElement("button");return t.type="button",t.className="ml-mtext-toolbar__btn",t.title=a,t.setAttribute("aria-label",a),t.setAttribute("aria-pressed","false"),t.innerHTML=ac[e],t}function dc(a){const e=a&&a.length>0?a:Is,t=[],i=new Set;for(const n of e){const s=n.trim();!s||i.has(s)||(i.add(s),t.push(s))}return t.length>0?t:[...Is]}class pc{constructor(e){I(this,"anchorElement");I(this,"root");I(this,"controls");I(this,"onFormatChange");I(this,"onToggleStack");I(this,"onToggleSuperscript");I(this,"onToggleSubscript");I(this,"theme");I(this,"colorPicker");cc(),this.anchorElement=e.anchorElement,this.onFormatChange=e.onFormatChange,this.onToggleStack=e.onToggleStack??(()=>{}),this.onToggleSuperscript=e.onToggleSuperscript??(()=>!1),this.onToggleSubscript=e.onToggleSubscript??(()=>!1),this.theme=e.theme,this.root=document.createElement("div"),this.root.className="ml-mtext-toolbar";const t=document.createElement("div");t.className="ml-mtext-toolbar__group";const i=document.createElement("select");i.className="ml-mtext-toolbar__select";for(const w of dc(e.fontFamilies)){const C=document.createElement("option");C.value=w,C.textContent=w,i.appendChild(C)}const n=document.createElement("input");n.className="ml-mtext-toolbar__input",n.type="number",n.min="1",n.max="1024",n.step="1",this.colorPicker=this.createColorPicker(e.colorPicker,e.initialFormat),t.append(i,n,this.colorPicker.host);const s=document.createElement("div");s.className="ml-mtext-toolbar__separator";const r=document.createElement("div");r.className="ml-mtext-toolbar__group";const o=Ne("Bold","bold"),c=Ne("Italic","italic"),l=Ne("Underline","underline"),h=Ne("Overline","overline"),d=Ne("Strike Through","strike"),g=Ne("Superscript","superscript"),m=Ne("Subscript","subscript"),y=Ne("Stack","stack");r.append(o,c,l,h,d,g,m,y),this.root.append(t,s,r),this.controls={fontFamily:i,fontSize:n,boldBtn:o,italicBtn:c,underlineBtn:l,overlineBtn:h,strikeBtn:d,superscriptBtn:g,subscriptBtn:m,stackBtn:y},this.setTheme(this.theme),this.bindEvents(),(e.container??document.body).appendChild(this.root)}setTheme(e){this.theme=e,this.root.dataset.theme=e,this.colorPicker.setTheme(e)}getTheme(){return this.theme}setVisible(e){this.root.style.display=e?"inline-flex":"none"}setSession(e){this.anchorElement=e.anchorElement,this.onFormatChange=e.onFormatChange,this.onToggleStack=e.onToggleStack,this.onToggleSuperscript=e.onToggleSuperscript??(()=>!1),this.onToggleSubscript=e.onToggleSubscript??(()=>!1)}setAnchor(e,t){const i=this.root.offsetWidth||0,n=this.root.offsetHeight||0,s=8,r=8,o=Math.max(s,window.innerWidth-i-8),c=Math.max(r,window.innerHeight-n-8),l=Math.max(s,Math.min(o,Math.round(e))),h=Math.max(r,Math.min(c,Math.round(t-n)));this.root.style.left=`${l}px`,this.root.style.top=`${h}px`}setFormat(e){this.ensureSelectValue(e.fontFamily),this.controls.fontSize.value=String(Math.max(1,Math.round(e.fontSize)));const t=Bs(e);this.colorPicker.setValue(t),this.setToggleState(this.controls.boldBtn,e.bold),this.setToggleState(this.controls.italicBtn,e.italic),this.setToggleState(this.controls.underlineBtn,e.underline),this.setToggleState(this.controls.overlineBtn,e.overline),this.setToggleState(this.controls.strikeBtn,e.strike),this.setToggleState(this.controls.superscriptBtn,e.script==="superscript"),this.setToggleState(this.controls.subscriptBtn,e.script==="subscript")}dispose(){this.colorPicker.dispose(),this.root.remove()}setStackActive(e){this.setToggleState(this.controls.stackBtn,e)}setToggleState(e,t){e.classList.toggle("is-active",t),e.setAttribute("aria-pressed",t?"true":"false")}ensureSelectValue(e){if(!Array.from(this.controls.fontFamily.options).some(i=>i.value===e)){const i=document.createElement("option");i.value=e,i.textContent=e,this.controls.fontFamily.appendChild(i)}this.controls.fontFamily.value=e}bindEvents(){const e=()=>{const t=Math.max(1,Number(this.controls.fontSize.value)||1);this.controls.fontSize.value=String(Math.round(t)),this.onFormatChange({fontSize:t})};this.controls.fontFamily.addEventListener("change",()=>{this.onFormatChange({fontFamily:this.controls.fontFamily.value})}),this.controls.fontSize.addEventListener("input",e),this.controls.fontSize.addEventListener("change",e),this.controls.fontSize.addEventListener("blur",e),this.controls.fontSize.addEventListener("keydown",t=>{t.key==="Enter"&&(e(),this.anchorElement.focus({preventScroll:!0}))}),this.controls.boldBtn.addEventListener("click",()=>{this.onFormatChange({bold:!this.controls.boldBtn.classList.contains("is-active")})}),this.controls.italicBtn.addEventListener("click",()=>{this.onFormatChange({italic:!this.controls.italicBtn.classList.contains("is-active")})}),this.controls.underlineBtn.addEventListener("click",()=>{this.onFormatChange({underline:!this.controls.underlineBtn.classList.contains("is-active")})}),this.controls.overlineBtn.addEventListener("click",()=>{this.onFormatChange({overline:!this.controls.overlineBtn.classList.contains("is-active")})}),this.controls.strikeBtn.addEventListener("click",()=>{this.onFormatChange({strike:!this.controls.strikeBtn.classList.contains("is-active")})}),this.controls.superscriptBtn.addEventListener("click",()=>{if(this.onToggleSuperscript())return;const t=this.controls.superscriptBtn.classList.contains("is-active");this.onFormatChange({script:t?"normal":"superscript"})}),this.controls.subscriptBtn.addEventListener("click",()=>{if(this.onToggleSubscript())return;const t=this.controls.subscriptBtn.classList.contains("is-active");this.onFormatChange({script:t?"normal":"subscript"})}),this.controls.stackBtn.addEventListener("click",()=>{this.onToggleStack()}),this.root.addEventListener("mousedown",t=>{const i=t.target;i&&(i.closest('[data-ml-mtext-toolbar-interactive="true"]')||i.tagName==="INPUT"||i.tagName==="SELECT"||i.tagName==="OPTION"||(t.preventDefault(),this.anchorElement.focus({preventScroll:!0})))})}createColorPicker(e,t){if(!e){const o=document.createElement("input");return o.className="ml-mtext-toolbar__color",o.type="color",o.dataset.mlMtextToolbarInteractive="true",o.addEventListener("input",()=>{this.applyColorChange(ks(o.value))}),{host:o,setValue:c=>{const l=uc(hc(c));l&&(o.value=l)},setTheme:()=>{},dispose:()=>{}}}const i=document.createElement("div");i.className="ml-mtext-toolbar__color",i.dataset.mlMtextToolbarInteractive="true";const n=t?Bs(t):ks("#ffffff"),r=e({container:i,theme:this.theme,initialColor:n,onChange:o=>{this.applyColorChange(o)}})??{};return{host:i,setValue:o=>{var c;(c=r.setValue)==null||c.call(r,o)},setTheme:o=>{var c;(c=r.setTheme)==null||c.call(r,o)},dispose:()=>{var o;(o=r.dispose)==null||o.call(r)}}}applyColorChange(e){if(e.isAci&&e.aci!==null){this.onFormatChange({aci:e.aci});return}if(e.isRgb&&e.rgbValue!==null){this.onFormatChange({aci:null,rgb:dn(e.rgbValue)});return}this.onFormatChange({aci:null,rgb:16777215})}}function Ds(a,e){const t=Math.max(1,a),i=e;return i===void 0||i===1||i===4||i===7||i===10?0:i===2||i===5||i===8||i===11?-t/2:i===3||i===6||i===9||i===12?-t:0}const gi="__mlightcadMTextInputBoxSceneRoot",R=class R{constructor(e){I(this,"scene");I(this,"camera");I(this,"mtextRenderer");I(this,"cursorRenderer");I(this,"width");I(this,"position");I(this,"mtextInsertionOffset",new f.Vector3(0,0,0));I(this,"enableWordWrap");I(this,"mtextString","");I(this,"editorLineSpaceFactor",null);I(this,"editorAttachmentPoint",B.MTextAttachmentPoint.TopLeft);I(this,"cursorIndex",0);I(this,"selectionStart",0);I(this,"selectionEnd",0);I(this,"baseFormat");I(this,"currentFormat");I(this,"defaultTextStyle");I(this,"cursorLogic");I(this,"layoutContainer",{x:0,y:0,width:1,height:1});I(this,"isDragging",!1);I(this,"pendingCursorLineHint",null);I(this,"latestCursorLayoutData",{containerBox:{x:0,y:0,width:1,height:1},charBoxes:[]});I(this,"renderedObject",null);I(this,"boundingBoxObject",null);I(this,"boundingBoxPadding",1);I(this,"boundingBoxZOffset",.01);I(this,"rendererReady",!1);I(this,"pendingFontLoad",null);I(this,"lastFontKey","");I(this,"toolbarTheme","dark");I(this,"toolbarOffsetY",10);I(this,"debugMode",!1);I(this,"colorSettings");I(this,"debugVisibility",{showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0});I(this,"maxHistorySize",100);I(this,"undoStack",[]);I(this,"redoStack",[]);I(this,"document");I(this,"uiAdapter");I(this,"imeInput",null);I(this,"imeTarget",null);I(this,"lastImeTarget",null);I(this,"reopenTarget",null);I(this,"pointerTarget",null);I(this,"imeComposing",!1);I(this,"imeFocusTimer",null);I(this,"closed",!1);I(this,"toolbarEnabled",!0);I(this,"toolbarContainer",null);I(this,"toolbarFontFamilies",null);I(this,"toolbarColorPicker");I(this,"onImeKeyDown",e=>{if(!this.isActiveEditor()||!(e.ctrlKey||e.metaKey)&&!e.altKey&&e.key.length===1||e.isComposing||e.key==="Process")return;this.handleKeyDown(e)&&e.preventDefault()});I(this,"onWindowKeyDown",e=>{if(!this.isActiveEditor()||e.defaultPrevented)return;const t=e.target,i=(t==null?void 0:t.tagName)??"";if((i==="INPUT"||i==="TEXTAREA"||i==="SELECT"||!!(t!=null&&t.isContentEditable))&&t!==this.imeInput)return;if(!(e.ctrlKey||e.metaKey)&&!e.altKey&&e.key.length===1||this.imeComposing||e.isComposing||e.key==="Process"){this.refocusImeInputSoon();return}this.handleKeyDown(e)&&(e.preventDefault(),this.refocusImeInputSoon())});I(this,"onImeBeforeInput",e=>{if(!this.isActiveEditor()||e.isComposing)return;const t=e.inputType;if(t==="insertText"||t==="insertCompositionText"){this.handleTextInput(e.data??"")&&e.preventDefault();return}t==="insertParagraph"&&this.handleTextInput(`
|
|
493
|
-
`)&&e.preventDefault()});I(this,"onImeCompositionStart",()=>{this.isActiveEditor()&&(this.imeComposing=!0,this.updateImeAnchorPosition(),this.refocusImeInputSoon())});I(this,"onImeCompositionEnd",e=>{if(!this.isActiveEditor())return;this.imeComposing=!1;const t=e.data??"";this.handleTextInput(t)&&this.imeInput&&(this.imeInput.value=""),this.refocusImeInputSoon()});I(this,"onImeTargetMouseDown",()=>{this.isActiveEditor()&&this.refocusImeInputSoon()});I(this,"onPointerMouseDown",e=>{if(this.closed||e.altKey||e.button===1)return;const t=this.pointerEventToEditorLocal(e);if(!t)return;if(!this.isPointInContainer(t.x,t.y)){this.isActiveEditor()&&this.closeEditor();return}this.activateEditor(),this.handleMouseDown(t.x,t.y,e.shiftKey),this.refocusImeInputSoon()});I(this,"onPointerMouseMove",e=>{if(!this.isActiveEditor()||e.buttons===0||!this.isDragging)return;const t=this.pointerEventToEditorLocal(e);t&&this.handleMouseMove(t.x,t.y)});I(this,"onPointerMouseUp",()=>{this.isActiveEditor()&&this.handleMouseUp()});I(this,"onPointerDoubleClick",e=>{if(!this.isActiveEditor())return;const t=this.pointerEventToEditorLocal(e);t&&(this.handleDoubleClick(t.x,t.y),this.refocusImeInputSoon())});I(this,"onReopenDoubleClick",e=>{this.closed&&this.shouldReopenFromDoubleClick(e)&&this.showEditor()});I(this,"handlers",{change:new Set,selectionChange:new Set,cursorMove:new Set,show:new Set,close:new Set});var r,o,c,l,h,d,g,m;R.instances.add(this),this.scene=e.scene,this.camera=e.camera,this.toolbarTheme=((r=e.toolbar)==null?void 0:r.theme)??"dark",this.toolbarOffsetY=Math.max(0,((o=e.toolbar)==null?void 0:o.offsetY)??10),this.toolbarEnabled=((c=e.toolbar)==null?void 0:c.enabled)??!0,this.toolbarContainer=((l=e.toolbar)==null?void 0:l.container)??null,this.toolbarFontFamilies=((h=e.toolbar)==null?void 0:h.fontFamilies)??null,this.toolbarColorPicker=(d=e.toolbar)==null?void 0:d.colorPicker,this.colorSettings=e.colorSettings,this.width=Math.max(1,e.width),this.position=((g=e.position)==null?void 0:g.clone())??new f.Vector3(0,0,0),e.initialAttachmentPoint!==void 0&&(this.editorAttachmentPoint=e.initialAttachmentPoint),this.enableWordWrap=e.enableWordWrap??!0;const t=e.textStyle??R.DEFAULT_TEXT_STYLE,i=Math.max(1,Number.isFinite(t.fixedTextHeight)?t.fixedTextHeight:R.DEFAULT_TEXT_STYLE.fixedTextHeight),n=Math.max(1,Number.isFinite(t.lastHeight)?t.lastHeight:i);this.defaultTextStyle={...t,fixedTextHeight:i,lastHeight:n,widthFactor:Number.isFinite(t.widthFactor)?t.widthFactor:1,obliqueAngle:Number.isFinite(t.obliqueAngle)?t.obliqueAngle:0,textGenerationFlag:Number.isFinite(t.textGenerationFlag)?t.textGenerationFlag:0,standardFlag:Number.isFinite(t.standardFlag)?t.standardFlag:0,font:t.font||R.DEFAULT_TEXT_STYLE.font,bigFont:t.bigFont??""},this.baseFormat=this.createBaseFormatFromTextStyle(this.defaultTextStyle,this.resolveRenderColorSettings()),this.currentFormat={...this.baseFormat},this.document=new Z,this.uiAdapter=new un(this.document),this.mtextRenderer=new B.UnifiedRenderer("main",{workerUrl:typeof e.workerUrl=="string"?e.workerUrl:((m=e.workerUrl)==null?void 0:m.toString())??"./assets/mtext-renderer-worker.js"}),e.fontUrl&&this.mtextRenderer.setFontUrl(e.fontUrl),this.cursorLogic=new Ka({containerBox:{x:0,y:0,width:this.width,height:1},charBoxes:[],lineTolerance:4});const s={...e.cursorStyle??{}};s.height===void 0&&s.heightMode!=="fixed"&&(s.height=0),s.color??(s.color="#ffffff"),s.glowColor??(s.glowColor="#ffffff"),this.cursorRenderer=new Xa({renderer:new qa({scene:this.scene,camera:this.camera}),cursorStyle:s,selectionStyle:e.selectionStyle,enableDebug:!1,enableSelection:!0,debugYAxisUp:this.camera instanceof f.OrthographicCamera?this.camera.top>=this.camera.bottom:!0,debugVisibility:this.debugVisibility}),this.cursorRenderer.setViewTransform({x:this.position.x,y:this.position.y,scaleX:1,scaleY:1}),this.createBoundingBox(e.showBoundingBox??!0,e.boundingBoxStyle),this.setText(e.initialText??""),this.attachIme(e.imeTarget),this.initializeRenderer()}setText(e){this.document=this.createNormalizedDocument(e),this.document.cursor=0,this.uiAdapter=new un(this.document),this.clearHistory(),this.syncUiStateFromDocument(),this.relayout(),this.emit("change")}getText(){return this.syncUiStateFromDocument(),this.mtextString}getPlainText(){return this.getChars().join("")}insertText(e){if(e.length!==0){if(e===`
|
|
494
|
-
`){const t=this.cursorLogic.getCursorState().lineIndex;this.pendingCursorLineHint=t>=0?t+1:0}this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"insertText",text:e,style:this.toDocumentStyle(this.currentFormat)}),this.syncUiStateFromDocument(),this.relayout()})}}deleteBackward(){this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"backspace"}),this.syncUiStateFromDocument(),this.relayout()})}deleteForward(){this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"delete"}),this.syncUiStateFromDocument(),this.relayout()})}undo(){const e=this.undoStack.pop();return e?(this.redoStack.push(this.createHistorySnapshot()),this.restoreHistorySnapshot(e),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.undoStack.push(this.createHistorySnapshot()),this.restoreHistorySnapshot(e),!0):!1}moveCursor(e){switch(e){case"left":this.cursorLogic.moveLeft();break;case"right":this.cursorLogic.moveRight();break;case"up":this.cursorLogic.moveUp();break;case"down":this.cursorLogic.moveDown();break;case"lineStart":this.cursorLogic.moveToLineStart();break;case"lineEnd":this.cursorLogic.moveToLineEnd();break;case"wordPrev":this.cursorLogic.moveTo(this.findPrevWordStart(this.cursorLogic.getCurrentIndex()));break;case"wordNext":this.cursorLogic.moveTo(this.findNextWordStart(this.cursorLogic.getCurrentIndex()));break}this.cursorLogic.clearSelection(),this.syncStateFromCursor(),this.emit("cursorMove"),this.emit("selectionChange")}extendSelection(e){const t=this.cursorLogic.getSelection(),i=t?t.anchor:this.cursorLogic.getCurrentIndex();switch(this.cursorLogic.clearSelection(),this.cursorLogic.moveTo(this.cursorIndex),e){case"left":this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex()-1);break;case"right":this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex()+1);break;case"up":this.cursorLogic.moveUp();break;case"down":this.cursorLogic.moveDown();break;case"lineStart":this.cursorLogic.moveToLineStart();break;case"lineEnd":this.cursorLogic.moveToLineEnd();break}this.cursorLogic.setSelectionWithDirection(i,this.cursorLogic.getCurrentIndex()),this.syncStateFromCursor(),this.emit("selectionChange")}selectAll(){this.cursorLogic.selectAll(),this.syncStateFromCursor(),this.emit("selectionChange")}clearSelection(){this.cursorLogic.clearSelection(),this.syncStateFromCursor(),this.emit("selectionChange")}setDebugMode(e){this.debugMode=e,this.cursorRenderer.setDebugMode(e)}isDebugMode(){return this.debugMode}setDebugVisibility(e){this.debugVisibility={...this.debugVisibility,...e},this.cursorRenderer.setDebugVisibility(e)}getDebugVisibility(){return{...this.debugVisibility}}setToolbarTheme(e){var t;this.toolbarTheme=e,this.isActiveEditor()&&((t=this.getActiveToolbar())==null||t.setTheme(e))}getToolbarTheme(){return this.toolbarTheme}attachIme(e){const t=this.closed;this.lastImeTarget=e,this.bindReopenDoubleClick(e),this.imeTarget=e,this.attachPointerInteractions(e),this.closed=!1,R.activeEditor?R.activeEditor===this?this.activateEditor():(this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1)):this.activateEditor(),t&&this.emit("show")}detachIme(){this.imeInput&&(this.imeInput.removeEventListener("keydown",this.onImeKeyDown),this.imeInput.removeEventListener("beforeinput",this.onImeBeforeInput),this.imeInput.removeEventListener("compositionstart",this.onImeCompositionStart),this.imeInput.removeEventListener("compositionend",this.onImeCompositionEnd),window.removeEventListener("keydown",this.onWindowKeyDown),this.imeTarget&&this.imeTarget.removeEventListener("mousedown",this.onImeTargetMouseDown),this.imeInput.remove(),this.imeInput=null,this.imeComposing=!1,this.imeFocusTimer!==null&&(window.clearTimeout(this.imeFocusTimer),this.imeFocusTimer=null))}getCursorIndex(){return this.cursorIndex}getSelectionRange(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return{start:e,end:t,isCollapsed:e===t}}getCursorLayoutData(){const e={containerBox:{...this.latestCursorLayoutData.containerBox},charBoxes:this.latestCursorLayoutData.charBoxes.map(t=>({...t}))};return this.latestCursorLayoutData.lineBreakIndices&&(e.lineBreakIndices=[...this.latestCursorLayoutData.lineBreakIndices]),this.latestCursorLayoutData.lineLayouts&&(e.lineLayouts=this.latestCursorLayoutData.lineLayouts.map(t=>({...t}))),e}setCurrentFormat(e){var n;const t=this.mergeCharFormat(this.currentFormat,e);this.currentFormat=t;const i=this.getSelectionRange();i.isCollapsed||this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const s=this.getNodesByLogicalRange(i.start,i.end);for(const r of s){const o=this.toCharFormat(r.style),c=this.mergeCharFormat(o,e);r.style=this.toDocumentStyle(c,r.style)}this.syncUiStateFromDocument(),this.relayout()}),(n=this.getActiveToolbar())==null||n.setFormat(this.currentFormat)}getCurrentFormat(){return{...this.currentFormat}}setParagraphAlignment(e){const t=this.mapRibbonParagraphAlignment(e);t!==void 0&&this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const i=this.getSelectionRange(),n=this.toDocumentIndexFromLogicalIndex(Math.min(i.start,i.end),!0),s=this.toDocumentIndexFromLogicalIndex(Math.max(i.start,i.end),!1),r=this.document.ast.nodes;if(r.length===0)return;const o=g=>{var y;const m=Math.max(0,Math.min(g,r.length-1));return((y=r[m])==null?void 0:y.type)==="paragraphBreak"?Math.min(m+1,r.length):Math.min(g,r.length-1)},c=g=>{var y;const m=o(g);for(let w=m;w>=0;w--)if(((y=r[w])==null?void 0:y.type)==="paragraphBreak")return w+1;return 0},l=g=>{var y;const m=Math.min(Math.max(0,g),r.length-1);for(let w=m;w<r.length;w++)if(((y=r[w])==null?void 0:y.type)==="paragraphBreak")return w;return r.length},h=c(Math.min(n,s)),d=l(Math.max(n,s));if(!(h>=d)){for(let g=h;g<d;g++){const m=r[g];m&&Ct(m)&&(m.style.paragraph.align=t)}this.syncUiStateFromDocument(),this.relayout()}})}setAttachmentPoint(e){const t=this.mapRibbonAttachmentCode(e);if(!(t===void 0||t===this.editorAttachmentPoint)){if(Number.isFinite(this.layoutContainer.width)&&Number.isFinite(this.layoutContainer.height)){const i=this.position.x+this.layoutContainer.x,n=i+this.layoutContainer.width,s=this.position.y+this.layoutContainer.y,r=s+this.layoutContainer.height;if(Number.isFinite(i)&&Number.isFinite(n)&&Number.isFinite(s)&&Number.isFinite(r)&&n>=i-1e-9&&r>=s-1e-9){const o=this.computeAttachmentAnchorOnBounds(i,n,s,r,this.editorAttachmentPoint),c=this.computeAttachmentAnchorOnBounds(i,n,s,r,t);this.position.x+=c.x-o.x,this.position.y+=c.y-o.y,this.cursorRenderer.setViewTransform({x:this.position.x,y:this.position.y,scaleX:1,scaleY:1})}}this.editorAttachmentPoint=t,this.relayout(),this.emit("change")}}getAttachmentPointCode(){return this.attachmentPointToRibbonCode(this.editorAttachmentPoint)}getMTextAttachmentPoint(){return this.editorAttachmentPoint}toggleCase(){const e=this.getSelectionRange();e.isCollapsed||this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const t=this.toDocumentIndexFromLogicalIndex(e.start,!0),i=this.toDocumentIndexFromLogicalIndex(e.end,!1);if(i<=t)return;const n=this.document.ast.nodes.slice(t,i),s=n.map(c=>c.type==="char"?c.value:c.type==="stack"?`${c.numerator}${c.denominator}`:"").join("");if(!/[a-zA-Z]/.test(s))return;const r=/[a-z]/.test(s),o=c=>r?c.toUpperCase():c.toLowerCase();this.document.transaction(()=>{for(const c of n)c.type==="char"?c.value=o(c.value):c.type==="stack"&&(c.numerator=o(c.numerator),c.denominator=o(c.denominator));this.document.setSelection(t,i)}),this.syncUiStateFromDocument(),this.relayout()})}getDefaultTextStyle(){return{...this.defaultTextStyle}}handleKeyDown(e){if(e.isComposing||e.key==="Process")return!1;if(e.key==="Escape")return this.closeEditor(),!0;const t=this.isMacPlatform(),i=t?e.metaKey:e.ctrlKey,n=t?e.altKey:e.ctrlKey;if(i&&e.key.toLowerCase()==="a")return this.selectAll(),!0;if(i&&e.key.toLowerCase()==="z")return e.shiftKey?this.redo():this.undo();if(!t&&i&&e.key.toLowerCase()==="y")return this.redo();if(e.shiftKey){if(e.key==="ArrowLeft")return this.consumeExtend("left");if(e.key==="ArrowRight")return this.consumeExtend("right");if(e.key==="ArrowUp")return this.consumeExtend("up");if(e.key==="ArrowDown")return this.consumeExtend("down");if(e.key==="Home")return this.consumeExtend("lineStart");if(e.key==="End")return this.consumeExtend("lineEnd")}return t&&e.metaKey&&e.key==="ArrowLeft"?this.consumeMove("lineStart"):t&&e.metaKey&&e.key==="ArrowRight"?this.consumeMove("lineEnd"):e.key==="ArrowLeft"?this.consumeMove(n?"wordPrev":"left"):e.key==="ArrowRight"?this.consumeMove(n?"wordNext":"right"):e.key==="ArrowUp"?this.consumeMove("up"):e.key==="ArrowDown"?this.consumeMove("down"):e.key==="Home"?this.consumeMove("lineStart"):e.key==="End"?this.consumeMove("lineEnd"):e.key==="Backspace"?(this.deleteBackward(),!0):e.key==="Delete"?(this.deleteForward(),!0):e.key==="Enter"?(this.insertText(`
|
|
495
|
-
`),!0):!i&&!e.altKey&&e.key.length===1?(this.insertText(e.key),!0):!1}handleTextInput(e){return e?(this.insertText(e),!0):!1}handleMouseDown(e,t,i){if(i){const n=this.cursorLogic.hitTest(e,t);if(n<0)return;this.cursorLogic.setSelectionWithDirection(this.selectionStart,n)}else if(!this.cursorLogic.moveToClick(e,t))return;this.isDragging=!0,this.syncStateFromCursor(),this.emit("cursorMove"),this.emit("selectionChange")}handleMouseMove(e,t){this.isDragging&&(this.cursorLogic.updateSelectionDrag(e,t),this.syncStateFromCursor(),this.emit("selectionChange"))}handleMouseUp(){this.isDragging=!1}handleDoubleClick(e,t){const i=this.cursorLogic.hitTest(e,t);if(i<0)return;const n=this.getChars();let s=i,r=i;for(;s>0&&!/\s/.test(n[s-1]??"");)s-=1;for(;r<n.length&&!/\s/.test(n[r]??"");)r+=1;this.cursorLogic.setSelection(s,r),this.cursorLogic.moveTo(r),this.syncStateFromCursor(),this.emit("selectionChange")}update(){const e=this.cursorLogic.getCursorState(),t=this.cursorLogic.getSelection(),i=this.getActiveCursorRenderState(e.position,e.lineInfo.height),n=this.cursorLogic.getSelectedCharBoxes();this.cursorRenderer.updateCursor(i.position,i.height),this.cursorRenderer.updateSelection(n),this.cursorRenderer.updateDebugInfo({containerBox:this.layoutContainer,charBoxes:this.cursorLogic.getCharBoxes(),chars:this.getChars(),lines:this.cursorLogic.getLines()}),this.cursorRenderer.setSelectionStyle({fillColor:t!=null&&t.isBackwards?"rgba(150,0,255,0.25)":"rgba(0,120,255,0.30)"}),this.cursorRenderer.render(),this.updateImeAnchorPosition(),this.updateToolbarPosition()}dispose(){var e;R.activeEditor===this?this.deactivateEditor():this.detachIme(),this.detachPointerInteractions(),this.unbindReopenDoubleClick(),this.disposeRenderedObject(this.renderedObject),this.renderedObject=null,this.disposeBoundingBox(),this.mtextRenderer.destroy(),this.cursorRenderer.dispose(),this.cursorLogic.destroy(),this.handlers.change.clear(),this.handlers.selectionChange.clear(),this.handlers.cursorMove.clear(),this.handlers.show.clear(),this.handlers.close.clear(),R.instances.delete(this),R.instances.size===0&&((e=R.sharedToolbar)==null||e.dispose(),R.sharedToolbar=null,R.sharedToolbarContainer=null,R.sharedToolbarFontFamiliesKey="",R.sharedToolbarColorPickerFactory=null,R.activeEditor=null)}closeEditor(){this.closed||(this.closed=!0,this.detachPointerInteractions(),this.deactivateEditor(),this.emit("close"))}showEditor(){const e=this.lastImeTarget;if(!e)return!1;const t=this.closed;return this.closed=!1,this.attachPointerInteractions(e),this.activateEditor(),t&&this.emit("show"),!0}attachPointerInteractions(e){this.detachPointerInteractions(),this.pointerTarget=e,e.addEventListener("mousedown",this.onPointerMouseDown),e.addEventListener("mousemove",this.onPointerMouseMove),e.addEventListener("dblclick",this.onPointerDoubleClick),window.addEventListener("mouseup",this.onPointerMouseUp)}detachPointerInteractions(){this.pointerTarget&&(this.pointerTarget.removeEventListener("mousedown",this.onPointerMouseDown),this.pointerTarget.removeEventListener("mousemove",this.onPointerMouseMove),this.pointerTarget.removeEventListener("dblclick",this.onPointerDoubleClick),window.removeEventListener("mouseup",this.onPointerMouseUp),this.pointerTarget=null)}on(e,t){this.handlers[e].add(t)}off(e,t){(e==="change"||e==="selectionChange"||e==="cursorMove"||e==="show"||e==="close")&&this.handlers[e].delete(t)}getCursorWorldPosition(){const e=this.cursorLogic.getCursorState(),t=this.getActiveCursorRenderState(e.position,e.lineInfo.height).position;return{x:this.position.x+t.x,y:this.position.y+t.y,z:this.position.z}}getMTextInsertionPoint(){return this.position.clone()}getState(){return{mtextString:this.getText(),cursorIndex:this.cursorIndex,selectionStart:this.selectionStart,selectionEnd:this.selectionEnd,currentFormat:this.getCurrentFormat()}}isActiveEditor(){return R.activeEditor===this}activateEditor(){var i;if(this.closed)return;const e=R.activeEditor;e&&e!==this&&e.deactivateEditor(),R.activeEditor=this;const t=this.imeTarget??this.lastImeTarget;t&&this.attachImeBridge(t),this.cursorRenderer.show(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!0),t&&this.toolbarEnabled?this.mountToolbar(t):(i=R.sharedToolbar)==null||i.setVisible(!1)}deactivateEditor(){var e;this.isDragging=!1,this.detachIme(),this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1),R.activeEditor===this&&(R.activeEditor=null,(e=R.sharedToolbar)==null||e.setVisible(!1))}attachImeBridge(e){this.detachIme(),this.imeTarget=e;const t=document.createElement("textarea");t.setAttribute("aria-hidden","true"),t.autocapitalize="off",t.autocomplete="off",t.spellcheck=!1,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.style.width="2px",t.style.height="2px",t.style.opacity="0",t.style.pointerEvents="none",t.style.zIndex="2147483647",document.body.appendChild(t),this.imeInput=t,t.addEventListener("keydown",this.onImeKeyDown),t.addEventListener("beforeinput",this.onImeBeforeInput),t.addEventListener("compositionstart",this.onImeCompositionStart),t.addEventListener("compositionend",this.onImeCompositionEnd),window.addEventListener("keydown",this.onWindowKeyDown),e.addEventListener("mousedown",this.onImeTargetMouseDown),this.updateImeAnchorPosition(),this.focusImeInput()}getActiveToolbar(){if(!this.isActiveEditor())return null;const e=R.sharedToolbar;if(!e)throw new Error("[mtext-input-box] Failed to create shared toolbar");return e}createToolbarSessionOptions(e){return{anchorElement:e,onFormatChange:t=>{this.setCurrentFormat(t)},onToggleStack:()=>{this.toggleStackSelection()},onToggleSuperscript:()=>this.toggleScriptSelection("superscript"),onToggleSubscript:()=>this.toggleScriptSelection("subscript")}}ensureSharedToolbar(e){var r,o;const t=this.toolbarContainer??document.body,i=((r=this.toolbarFontFamilies)==null?void 0:r.join("\0"))??"";if(!R.sharedToolbar||R.sharedToolbarContainer!==t||R.sharedToolbarFontFamiliesKey!==i||R.sharedToolbarColorPickerFactory!==(this.toolbarColorPicker??null)){(o=R.sharedToolbar)==null||o.dispose();const c={...this.createToolbarSessionOptions(e),container:t,theme:this.toolbarTheme,initialFormat:this.currentFormat};this.toolbarFontFamilies&&(c.fontFamilies=this.toolbarFontFamilies),this.toolbarColorPicker&&(c.colorPicker=this.toolbarColorPicker),R.sharedToolbar=new pc(c),R.sharedToolbarContainer=t,R.sharedToolbarFontFamiliesKey=i,R.sharedToolbarColorPickerFactory=this.toolbarColorPicker??null}const s=R.sharedToolbar;if(!s)throw new Error("[mtext-input-box] Failed to create shared toolbar");return s}mountToolbar(e){if(!this.toolbarEnabled||!this.isActiveEditor())return;const t=this.ensureSharedToolbar(e);t.setTheme(this.toolbarTheme),t.setSession(this.createToolbarSessionOptions(e)),t.setVisible(!0),t.setFormat(this.currentFormat),this.updateToolbarStackState(),this.updateToolbarPosition()}updateToolbarPosition(){if(!this.toolbarEnabled||!this.isActiveEditor()||!this.imeTarget)return;const e=this.getActiveToolbar();if(!e)return;const t=this.getEditorScreenBounds();t&&e.setAnchor(t.minX,t.minY-this.toolbarOffsetY)}getEditorScreenBounds(){if(!this.imeTarget)return null;const e=this.imeTarget.getBoundingClientRect(),t=this.position.x+this.layoutContainer.x,i=t+this.layoutContainer.width,n=this.position.y+this.layoutContainer.y,s=n+this.layoutContainer.height,r=[new f.Vector3(t,n,this.position.z),new f.Vector3(i,n,this.position.z),new f.Vector3(t,s,this.position.z),new f.Vector3(i,s,this.position.z)];let o=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY,l=Number.POSITIVE_INFINITY,h=Number.NEGATIVE_INFINITY;for(const d of r){const g=d.clone().project(this.camera),m=e.left+(g.x+1)*.5*e.width,y=e.top+(1-g.y)*.5*e.height;o=Math.min(o,m),c=Math.max(c,m),l=Math.min(l,y),h=Math.max(h,y)}return!Number.isFinite(o)||!Number.isFinite(l)?null:{minX:o,maxX:c,minY:l,maxY:h}}pointerEventToEditorLocal(e){const t=this.pointerTarget??this.imeTarget;return this.pointerEventToEditorLocalByTarget(e,t)}pointerEventToEditorLocalByTarget(e,t){if(!t)return null;const i=t.getBoundingClientRect();if(i.width<=0||i.height<=0)return null;const n=(e.clientX-i.left)/i.width*2-1,s=-((e.clientY-i.top)/i.height)*2+1,r=new f.Vector3(n,s,-1).unproject(this.camera),c=new f.Vector3(n,s,1).unproject(this.camera).sub(r);if(Math.abs(c.z)<1e-8)return null;const l=(this.position.z-r.z)/c.z,h=r.add(c.multiplyScalar(l));return{x:h.x-this.position.x,y:h.y-this.position.y}}shouldReopenFromDoubleClick(e){return this.hitTestRenderedObject(e)}hitTestRenderedObject(e){if(!this.renderedObject||!this.reopenTarget)return!1;const t=this.reopenTarget.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const i=(e.clientX-t.left)/t.width*2-1,n=-((e.clientY-t.top)/t.height)*2+1,s=new f.Raycaster;return s.setFromCamera(new f.Vector2(i,n),this.camera),s.intersectObject(this.renderedObject,!0).length>0}bindReopenDoubleClick(e){this.reopenTarget!==e&&(this.unbindReopenDoubleClick(),this.reopenTarget=e,e.addEventListener("dblclick",this.onReopenDoubleClick))}unbindReopenDoubleClick(){this.reopenTarget&&(this.reopenTarget.removeEventListener("dblclick",this.onReopenDoubleClick),this.reopenTarget=null)}isPointInContainer(e,t){const i=this.layoutContainer,n=i.x+i.width,s=i.y+i.height;return e>=i.x&&e<=n&&t>=i.y&&t<=s}async initializeRenderer(){try{await this.mtextRenderer.loadFonts([hi]),this.rendererReady=!0,this.ensureFontsLoaded(),this.relayout()}catch(e){console.error("[mtext-input-box] Failed to initialize mtext renderer fonts",e)}}relayout(){if(!this.rendererReady){this.mtextInsertionOffset.set(0,0,0);const e=this.createFallbackCharBoxes();this.layoutContainer=e.containerBox,this.updateCursorData(e.charBoxes,e.lineBreakIndices,e.lineLayouts),this.updateBoundingBoxGeometry();return}this.ensureFontsLoaded();try{const e=this.createMTextData(),t=this.createTextStyle(),i=this.resolveRenderColorSettings(),n=this.mtextRenderer.syncRenderMText(e,t,i);this.pruneExtraMTextLayoutRoots(n),this.replaceRenderedObject(n);const s=this.extractBoxesFromRenderedObject(n);this.mtextInsertionOffset.set(0,0,0),this.normalizeRenderedTopAlignment(n,s),this.layoutContainer=s.containerBox,this.updateCursorData(s.charBoxes,s.lineBreakIndices,s.lineLayouts),this.updateBoundingBoxGeometry()}catch(e){console.error("[mtext-input-box] Failed to sync render MTEXT",e),this.mtextInsertionOffset.set(0,0,0);const t=this.createFallbackCharBoxes();this.layoutContainer=t.containerBox,this.updateCursorData(t.charBoxes,t.lineBreakIndices,t.lineLayouts),this.updateBoundingBoxGeometry()}}ensureFontsLoaded(){if(this.pendingFontLoad)return;const e=this.collectFontNamesForText(),t=e.map(i=>i.toLowerCase()).sort().join("|");!t||t===this.lastFontKey||(this.lastFontKey=t,this.pendingFontLoad=this.mtextRenderer.loadFonts(e).then(()=>{}).catch(i=>{console.warn("[mtext-input-box] Failed to load fonts for MTEXT",i)}).finally(()=>{this.pendingFontLoad=null,this.rendererReady&&this.relayout()}))}collectFontNamesForText(){const e=new Set,t=i=>{if(!i)return;const n=i.trim();n&&e.add(n)};t(this.defaultTextStyle.font),t(this.defaultTextStyle.bigFont);try{const i=B.MText.getFonts(this.mtextString||"",!0);for(const n of i)t(n)}catch(i){console.warn("[mtext-input-box] Failed to parse fonts from MTEXT",i)}return e.size===0&&e.add(hi),[...e]}updateCursorData(e,t,i){this.latestCursorLayoutData={containerBox:{...this.layoutContainer},charBoxes:e.map(c=>({...c})),...t?{lineBreakIndices:[...t]}:{},...i?{lineLayouts:i.map(c=>({...c}))}:{}},this.cursorLogic.updateData(this.layoutContainer,e,t,i);const n=Math.min(this.cursorIndex,this.charCount()),s=Math.max(0,this.cursorLogic.getLineCount()-1),r=this.pendingCursorLineHint===null?null:Math.max(0,Math.min(this.pendingCursorLineHint,s));this.pendingCursorLineHint=null,this.cursorLogic.moveTo(n,r),this.selectionStart!==this.selectionEnd?this.cursorLogic.setSelection(this.selectionStart,this.selectionEnd):this.cursorLogic.clearSelection(),this.syncStateFromCursor();const o=this.unionLayoutContainerWithCursorLines(this.layoutContainer);(Math.abs(o.y-this.layoutContainer.y)>1e-6||Math.abs(o.height-this.layoutContainer.height)>1e-6)&&(this.layoutContainer=o,this.latestCursorLayoutData.containerBox={...this.layoutContainer},this.cursorLogic.updateData(this.layoutContainer,e,t,i),this.cursorLogic.moveTo(n,r),this.selectionStart!==this.selectionEnd?this.cursorLogic.setSelection(this.selectionStart,this.selectionEnd):this.cursorLogic.clearSelection(),this.syncStateFromCursor())}unionLayoutContainerWithCursorLines(e){const t=this.cursorLogic.getLines();if(t.length===0)return e;let i=e.y,n=e.y+e.height;for(const s of t){if(s.charCount!==0)continue;const r=s.y-s.height/2,o=s.y+s.height/2;Number.isFinite(r)&&(i=Math.min(i,r)),Number.isFinite(o)&&(n=Math.max(n,o))}return!Number.isFinite(i)||!Number.isFinite(n)||n<i?e:{...e,y:i,height:n-i}}computeEditorVerticalBounds(e,t,i){const n=()=>({minY:i.y-i.height/2,maxY:i.y+i.height/2}),s=(c,l,h,d)=>c<d+1e-4&&l>h-1e-4;if(e.length===0&&t.length===0)return n();if(e.length===0){let c=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const h of t)c=Math.min(c,h.y-h.height/2),l=Math.max(l,h.y+h.height/2);return Number.isFinite(c)&&Number.isFinite(l)&&l>=c?{minY:c,maxY:l}:n()}if(t.length===0){let c=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const h of e){const d=h.y-h.height/2,g=h.y+h.height/2;c=Math.min(c,d),l=Math.max(l,g)}return Number.isFinite(c)&&Number.isFinite(l)&&l>=c?{minY:c,maxY:l}:n()}let r=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(const c of e){const l=c.y-c.height/2,h=c.y+c.height/2,d=t.filter(g=>{const m=g.y-g.height/2,y=g.y+g.height/2;return s(m,y,l,h)});if(d.length===0)r=Math.min(r,l),o=Math.max(o,h);else for(const g of d)r=Math.min(r,g.y-g.height/2),o=Math.max(o,g.y+g.height/2)}for(const c of t){const l=c.y-c.height/2,h=c.y+c.height/2;e.some(g=>{const m=g.y-g.height/2,y=g.y+g.height/2;return s(l,h,m,y)})||(r=Math.min(r,l),o=Math.max(o,h))}return!Number.isFinite(r)||!Number.isFinite(o)||o<r?n():{minY:r,maxY:o}}extractBoxesFromRenderedObject(e){const t=e.createLayoutData(),i=[],n=((t==null?void 0:t.lines)??[]).filter(d=>Number.isFinite(d.y)&&Number.isFinite(d.height)).map(d=>({y:d.y-this.position.y,height:Math.max(1,d.height)}));for(const d of(t==null?void 0:t.chars)??[]){const g=d.box?this.toLocalBox(d.box):void 0;!g||!(Number.isFinite(g.x)&&Number.isFinite(g.y)&&Number.isFinite(g.width)&&Number.isFinite(g.height))||i.push(g)}const s=(t.lines??[]).map(d=>d.breakIndex).filter(d=>Number.isInteger(d)).filter(d=>d>=0&&d<=i.length),r=this.toLocalBox(e.box),{minY:o,maxY:c}=this.computeEditorVerticalBounds(n,i,r),l={x:Ds(this.width,this.editorAttachmentPoint),y:o,width:Math.max(1,this.width),height:Math.max(0,c-o)},h=this.getFallbackLineAdvance();if(l.height<h){const d=h-l.height;l.y-=d,l.height=h}return{containerBox:l,charBoxes:i,...s.length>0?{lineBreakIndices:s}:{},...n.length>0?{lineLayouts:n}:{}}}normalizeRenderedTopAlignment(e,t){var s;const n=-(t.containerBox.y+t.containerBox.height);!Number.isFinite(n)||Math.abs(n)<1e-8||(this.mtextInsertionOffset.set(0,n,0),e.position.y+=n,e.updateMatrixWorld(!0),t.containerBox.y+=n,t.charBoxes.forEach(r=>{r.y+=n}),(s=t.lineLayouts)==null||s.forEach(r=>{r.y+=n}))}toLocalBox(e){const t=e.min.x-this.position.x,i=e.max.x-this.position.x,n=e.min.y-this.position.y,s=e.max.y-this.position.y,r=Math.max(0,i-t),o=Math.max(0,s-n);return{x:t,y:n+o/2,width:r,height:o}}createFallbackCharBoxes(){const e=this.getFallbackLineAdvance(),t=[],i=[],n=[];let s=0,r=0,o=-e;n.push({y:r-e/2,height:e});for(const c of this.getChars()){if(c===`
|
|
496
|
-
`){i.push(t.length),s=0,r-=e,o=Math.min(o,r-e),n.push({y:r-e/2,height:e});continue}const l=Math.max(1,this.currentFormat.fontSize*.6);this.enableWordWrap&&s>0&&s+l>this.width&&(i.push(t.length),s=0,r-=e,o=Math.min(o,r-e),n.push({y:r-e/2,height:e})),t.push({x:s,y:r-e/2,width:l,height:e}),s+=l}return{containerBox:{x:Ds(this.width,this.editorAttachmentPoint),y:o,width:this.width,height:Math.max(1,-o)},charBoxes:t,lineBreakIndices:i,lineLayouts:n}}createBoundingBox(e,t){if(!e)return;const i=typeof(t==null?void 0:t.color)=="number"?t.color:new f.Color((t==null?void 0:t.color)??"#58a6ff");this.boundingBoxPadding=Math.max(0,(t==null?void 0:t.padding)??1),this.boundingBoxZOffset=(t==null?void 0:t.zOffset)??.01;const n=new f.LineBasicMaterial({color:i,transparent:!0,opacity:(t==null?void 0:t.opacity)??.9,depthTest:!1,depthWrite:!1}),s=new f.BufferGeometry;this.boundingBoxObject=new f.LineLoop(s,n),this.boundingBoxObject.position.z=this.boundingBoxZOffset,this.scene.add(this.boundingBoxObject)}updateBoundingBoxGeometry(){if(!this.boundingBoxObject)return;this.boundingBoxObject.geometry.dispose();const t=this.boundingBoxPadding,i=this.position.x+this.layoutContainer.x-t,n=this.position.y+this.layoutContainer.y-t,s=this.position.x+this.layoutContainer.x+this.layoutContainer.width+t,r=this.position.y+this.layoutContainer.y+this.layoutContainer.height+t,o=this.position.z;this.boundingBoxObject.geometry=new f.BufferGeometry().setFromPoints([new f.Vector3(i,n,o),new f.Vector3(s,n,o),new f.Vector3(s,r,o),new f.Vector3(i,r,o)])}disposeBoundingBox(){if(!this.boundingBoxObject)return;this.boundingBoxObject.removeFromParent(),this.boundingBoxObject.geometry.dispose();const e=Array.isArray(this.boundingBoxObject.material)?this.boundingBoxObject.material:[this.boundingBoxObject.material];for(const t of e)t.dispose();this.boundingBoxObject=null}replaceRenderedObject(e){this.disposeRenderedObject(this.renderedObject),this.removeStrayInputBoxSceneRootsExcept(e),this.forceVisibleMaterialState(e),e.userData[gi]=this,this.renderedObject=e,this.scene.add(e)}removeStrayInputBoxSceneRootsExcept(e){const t=e;for(let i=this.scene.children.length-1;i>=0;i--){const n=this.scene.children[i];if(!n||n===t)continue;n.userData[gi]===this&&(this.scene.remove(n),this.disposeMTextRootResources(n),delete n.userData[gi])}}forceVisibleMaterialState(e){e.traverse(t=>{const i=t,n=i.material?Array.isArray(i.material)?i.material:[i.material]:[];for(const s of n){const r=s;typeof r.side<"u"&&(r.side=f.DoubleSide),typeof r.depthTest<"u"&&(r.depthTest=!1),typeof r.depthWrite<"u"&&(r.depthWrite=!1),typeof r.transparent<"u"&&typeof r.opacity<"u"&&(r.transparent=r.opacity<1),r.needsUpdate=!0}})}disposeDetachedThreeSubtree(e){e.traverse(t=>{const i=t;i.geometry&&i.geometry.dispose();const n=i.material?Array.isArray(i.material)?i.material:[i.material]:[];for(const s of n){const r=s;r.map&&r.map.dispose(),s.dispose()}})}pruneExtraMTextLayoutRoots(e){for(;e.children.length>1;){const t=e.children[0];if(!t)break;e.remove(t),this.disposeDetachedThreeSubtree(t)}}disposeMTextRootResources(e){const t=e;if(typeof t.dispose=="function"){t.dispose();return}this.disposeDetachedThreeSubtree(e)}disposeRenderedObject(e){e&&(e.removeFromParent(),delete e.userData[gi],this.disposeMTextRootResources(e))}isExplicitAci(e){return e!==null&&Number.isInteger(e)&&e>0&&e<256}normalizeColorNumber(e){return Math.max(0,Math.min(16777215,Math.round(e)))}resolveAciColor(e){const t=B.getColorByIndex(e);return this.normalizeColorNumber(Number.isFinite(t)?t:16777215)}resolveBaseColor(){return this.isExplicitAci(this.baseFormat.aci)?this.resolveAciColor(this.baseFormat.aci):this.baseFormat.rgb!==null?this.normalizeColorNumber(this.baseFormat.rgb):16777215}resolveBaseFormatColor(e){const t=e.color;if(t.isRgb&&t.rgbValue!==null)return{aci:null,rgb:this.normalizeColorNumber(t.rgbValue)};if(t.isAci&&t.aci!==null){const i=t.aci;return Number.isInteger(i)&&i>=1&&i<=255?{aci:i,rgb:null}:i===0?{aci:null,rgb:this.normalizeColorNumber(e.byBlockColor)}:{aci:null,rgb:this.normalizeColorNumber(e.byLayerColor)}}return{aci:null,rgb:this.normalizeColorNumber(e.byLayerColor)}}createBaseFormatFromTextStyle(e,t){const i=Ga();i.fontFamily=e.font||i.fontFamily,i.fontSize=Math.max(1,e.fixedTextHeight);const n=this.resolveBaseFormatColor(t);i.aci=n.aci,i.rgb=n.rgb;const s=e.widthFactor;i.widthFactor=typeof s=="number"&&Number.isFinite(s)?Math.max(.01,s):1;const r=e.obliqueAngle;return i.obliqueAngle=typeof r=="number"&&Number.isFinite(r)?r:0,i.tracking=1,i}createMTextData(){const e={text:this.mtextString,height:Math.max(1,this.defaultTextStyle.fixedTextHeight),width:this.width,position:{x:this.position.x,y:this.position.y,z:this.position.z},attachmentPoint:this.editorAttachmentPoint,drawingDirection:B.MTextFlowDirection.LEFT_TO_RIGHT,widthFactor:1,collectCharBoxes:!0};return this.editorLineSpaceFactor!=null&&Number.isFinite(this.editorLineSpaceFactor)&&(e.lineSpaceFactor=this.editorLineSpaceFactor),e}getLineSpacingFactor(){return this.editorLineSpaceFactor??R.DEFAULT_LINE_SPACE_FACTOR}setLineSpacingFactor(e){if(!Number.isFinite(e)||e<=0)return;const t=R.DEFAULT_LINE_SPACE_FACTOR,i=e>=1?Math.max(.01,t+(e-1)/B.LINE_SPACING_SCALE_FACTOR):e;this.editorLineSpaceFactor=i,this.relayout(),this.emit("change")}clearLineSpacing(){this.editorLineSpaceFactor=null,this.relayout(),this.emit("change")}getFallbackLineAdvance(){return Math.max(1,this.currentFormat.fontSize*R.FALLBACK_LINE_ADVANCE_RATIO)}createTextStyle(){return{...this.defaultTextStyle}}resolveRenderColorSettings(){if(this.colorSettings)return this.colorSettings;const e=this.toolbarTheme==="light"?0:16777215;return{byLayerColor:e,byBlockColor:e,color:new B.MTextColor(256)}}focusImeInput(){this.imeInput&&this.imeInput.focus({preventScroll:!0})}refocusImeInputSoon(){this.imeInput&&(this.imeFocusTimer!==null&&window.clearTimeout(this.imeFocusTimer),this.imeFocusTimer=window.setTimeout(()=>{this.focusImeInput(),this.imeFocusTimer=null},0))}updateImeAnchorPosition(){if(!this.imeInput||!this.imeTarget)return;const e=this.getCursorWorldPosition(),i=new f.Vector3(e.x,e.y,e.z).project(this.camera),n=this.imeTarget.getBoundingClientRect(),s=n.left+(i.x+1)*.5*n.width,r=n.top+(1-i.y)*.5*n.height;this.imeInput.style.left=`${Math.round(s)}px`,this.imeInput.style.top=`${Math.round(r)}px`}syncStateFromCursor(){this.cursorIndex=this.cursorLogic.getCurrentIndex();const e=this.cursorLogic.getSelection();e?(this.selectionStart=e.start,this.selectionEnd=e.end):(this.selectionStart=this.cursorIndex,this.selectionEnd=this.cursorIndex),this.syncDocumentFromUiState(),this.refreshCurrentFormatFromDocument()}consumeMove(e){return this.moveCursor(e),!0}consumeExtend(e){return this.extendSelection(e),!0}isMacPlatform(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}emit(e){for(const t of this.handlers[e])t()}findPrevWordStart(e){const t=this.getChars();let i=Math.max(0,e-1);for(;i>0&&/\s/.test(t[i]??"");)i-=1;for(;i>0&&!/\s/.test(t[i-1]??"");)i-=1;return i}findNextWordStart(e){const t=this.getChars();let i=Math.min(t.length,e);for(;i<t.length&&!/\s/.test(t[i]??"");)i+=1;for(;i<t.length&&/\s/.test(t[i]??"");)i+=1;return i}getChars(){const e=[];for(const t of this.document.ast.nodes){if(t.type==="char"){e.push(t.value);continue}if(t.type==="stack"){e.push("");continue}(t.type==="paragraphBreak"||t.type==="columnBreak"||t.type==="wrapAtDimLine")&&e.push(`
|
|
497
|
-
`)}return e}charCount(){return this.getChars().length}getActiveCursorRenderState(e,t){var o;const i=this.cursorLogic.getCharBoxes(),n=this.cursorLogic.getCurrentIndex(),s=this.cursorLogic.getCurrentLineInfo();if(i.length===0){const c=(o=this.latestCursorLayoutData.lineLayouts)==null?void 0:o[0];if(c&&Number.isFinite(c.y)&&Number.isFinite(c.height)){const h=Math.max(1,c.height);return{position:{x:e.x,y:c.y},height:h}}const l=Math.max(1,this.getFallbackLineAdvance());return{position:{x:e.x,y:this.layoutContainer.y+l/2},height:l}}if(n<=0||n===s.startIndex){if(!(s.charCount<=0||s.endIndex<s.startIndex)){const h=Math.max(0,Math.min(s.startIndex,i.length-1)),d=i[h];if(d)return{position:{x:e.x,y:d.y},height:Math.max(1,d.height)}}const l=s.height??t;return{position:{x:e.x,y:s.y??e.y},height:Math.max(1,l)}}const r=i[Math.min(n-1,i.length-1)];return r?{position:{x:r.x+r.width,y:r.y},height:Math.max(1,r.height)}:{position:e,height:Math.max(1,t)}}getNodeLogicalSpan(e){switch(e.type){case"char":return 1;case"stack":return 1;case"paragraphBreak":case"columnBreak":case"wrapAtDimLine":return 0;default:return 0}}toLogicalIndexFromDocumentIndex(e){const t=Math.max(0,Math.min(e,this.document.ast.nodes.length));let i=0;for(let n=0;n<t;n+=1){const s=this.document.ast.nodes[n];s&&(i+=this.getNodeLogicalSpan(s))}return i}toDocumentIndexFromLogicalIndex(e,t=!0,i){var h,d;const n=this.document.ast.nodes;if(n.length===0)return 0;const s=this.charCount(),r=Math.max(0,Math.min(e,s)),o=[];let c=0,l=0;for(let g=0;g<=n.length&&(c===r&&o.push({index:g,lineIndex:l}),g!==n.length);g+=1){const m=n[g];if(!m)continue;const y=this.getNodeLogicalSpan(m);y===0?l+=1:c+=y}if(o.length===0)return n.length;if(i!==void 0&&Number.isFinite(i)){const g=this,y=(typeof g.resolveCandidateByVisualLineHint=="function"?g.resolveCandidateByVisualLineHint:R.prototype.resolveCandidateByVisualLineHint).call(this,o,r,i);if(y!==void 0)return y;const w=((h=o[0])==null?void 0:h.lineIndex)??0,C=((d=o[o.length-1])==null?void 0:d.lineIndex)??0;if(i<w||i>C)return t?o[o.length-1].index:o[0].index;let b=o[0],x=Math.abs(b.lineIndex-i);for(let A=1;A<o.length;A+=1){const _=o[A],L=Math.abs(_.lineIndex-i);L<x&&(b=_,x=L)}return b.index}return t?o[o.length-1].index:o[0].index}resolveCandidateByVisualLineHint(e,t,i){if(e.length<=1||this.cursorLogic==null||typeof this.cursorLogic.getLines!="function")return;const n=this.cursorLogic.getLines();if(!Array.isArray(n)||n.length===0)return;const s=[];for(let c=0;c<n.length;c+=1){const l=n[c];l&&t>=l.startIndex&&t<=l.endIndex+1&&s.push(c)}if(s.length!==e.length)return;const r=s.indexOf(i);if(r<0)return;const o=e[r];return o==null?void 0:o.index}syncUiStateFromDocument(){this.mtextString=this.document.toMText();const e=this.charCount();this.cursorIndex=Math.min(this.toLogicalIndexFromDocumentIndex(this.document.cursor),e);const t=this.document.selection;t?(this.selectionStart=this.toLogicalIndexFromDocumentIndex(t.start),this.selectionEnd=this.toLogicalIndexFromDocumentIndex(t.end)):(this.selectionStart=this.cursorIndex,this.selectionEnd=this.cursorIndex),this.refreshCurrentFormatFromDocument()}syncDocumentFromUiState(){const e=this.getSelectionRange();if(!e.isCollapsed){const s=this.toDocumentIndexFromLogicalIndex(e.start,!0),r=this.toDocumentIndexFromLogicalIndex(e.end,!1);this.document.setSelection(s,r);return}this.document.clearSelection();const t=this.cursorLogic.getCursorState(),i=t.lineIndex,n=!(t.isAtLineEnd&&!t.isAtLineStart);this.document.cursor=this.toDocumentIndexFromLogicalIndex(this.cursorIndex,n,i>=0?i:void 0)}refreshCurrentFormatFromDocument(){var t,i;const e=this.inferCurrentFormatFromDocument();if(this.updateToolbarStackState(),!e){(t=this.getActiveToolbar())==null||t.setFormat(this.currentFormat);return}xs(this.currentFormat,e)||(this.currentFormat=e),(i=this.getActiveToolbar())==null||i.setFormat(this.currentFormat)}toggleStackSelection(){const e=this.getSelectionRange();e.isCollapsed||this.commitHistoryEdit(()=>{var l;this.syncDocumentFromUiState();const t=this.toDocumentIndexFromLogicalIndex(e.start,!0),i=this.toDocumentIndexFromLogicalIndex(e.end,!1);if(i<=t)return;const n=this.document.ast.nodes.slice(t,i);if(n.length===1&&((l=n[0])==null?void 0:l.type)==="stack"){const h=n[0],d=this.stackNodeToPlainText(h.numerator,h.denominator,h.divider),g=Array.from(d).map(m=>({type:"char",value:m,style:this.cloneDocumentStyle(h.style)}));if(g.length===0)return;this.document.transaction(m=>{m.ast.nodes.splice(t,1,...g),m.setSelection(t,t+g.length)}),this.syncUiStateFromDocument(),this.relayout();return}if(!n.every(h=>(h==null?void 0:h.type)==="char"))return;const s=n.map(h=>h.value).join(""),r=this.parseStackParts(s);if(!r)return;const o=n[0];if(!o)return;const c={type:"stack",numerator:r.numerator,denominator:r.denominator,divider:r.divider,style:this.cloneDocumentStyle(o.style)};this.document.transaction(h=>{h.ast.nodes.splice(t,i-t,c),h.setSelection(t,t+1)}),this.syncUiStateFromDocument(),this.relayout()})}toggleScriptSelection(e){const t=this.getSelectionRange();if(t.isCollapsed)return!1;let i=!1;return this.commitHistoryEdit(()=>{var d;this.syncDocumentFromUiState();const n=this.toDocumentIndexFromLogicalIndex(t.start,!0),s=this.toDocumentIndexFromLogicalIndex(t.end,!1);if(s<=n)return;const r=this.document.ast.nodes.slice(n,s);if(r.length===1&&((d=r[0])==null?void 0:d.type)==="stack"){const g=r[0],m=this.scriptStackToPlainText(g.numerator,g.denominator,g.divider);if(!m)return;const y=this.cloneDocumentStyle(g.style);y.script="normal",y.align=B.MTextLineAlignment.MIDDLE;const w=Array.from(m).map(C=>({type:"char",value:C,style:this.cloneDocumentStyle(y)}));if(w.length===0)return;this.document.transaction(C=>{C.ast.nodes.splice(n,1,...w),C.setSelection(n,n+w.length)}),this.syncUiStateFromDocument(),this.relayout(),i=!0;return}if(!r.every(g=>(g==null?void 0:g.type)==="char"))return;const o=r.map(g=>g.value).join("");if(o.length===0)return;const c=r[0];if(!c)return;const l=this.cloneDocumentStyle(c.style);l.script=e,l.align=e==="superscript"?B.MTextLineAlignment.TOP:B.MTextLineAlignment.BOTTOM;const h={type:"stack",numerator:e==="superscript"?o:"",denominator:e==="subscript"?o:"",divider:"^",style:this.cloneDocumentStyle(l)};this.document.transaction(g=>{g.ast.nodes.splice(n,s-n,h),g.setSelection(n,n+1)}),this.syncUiStateFromDocument(),this.relayout(),i=!0}),i}commitHistoryEdit(e){const t=this.createHistorySnapshot();e(),!this.isSameAsCurrent(t)&&(this.undoStack.push(t),this.undoStack.length>this.maxHistorySize&&this.undoStack.splice(0,this.undoStack.length-this.maxHistorySize),this.redoStack=[],this.emit("change"),this.emit("selectionChange"),this.emit("cursorMove"))}createHistorySnapshot(){return{ast:this.cloneAst(this.document.ast),cursor:this.document.cursor,selection:this.document.selection?{...this.document.selection}:null,currentFormat:{...this.currentFormat}}}restoreHistorySnapshot(e){this.document=new Z(this.cloneAst(e.ast)),e.selection?this.document.setSelection(e.selection.start,e.selection.end):(this.document.cursor=e.cursor,this.document.clearSelection()),this.uiAdapter=new un(this.document),this.currentFormat={...e.currentFormat},this.syncUiStateFromDocument(),this.relayout(),this.emit("change"),this.emit("selectionChange"),this.emit("cursorMove")}isSameAsCurrent(e){if(e.cursor!==this.document.cursor)return!1;const t=this.document.selection;return!!e.selection!=!!t||e.selection&&t&&(e.selection.start!==t.start||e.selection.end!==t.end)||!xs(e.currentFormat,this.currentFormat)?!1:this.document.toMText()===this.buildMTextFromAst(e.ast)}buildMTextFromAst(e){return new Z(this.cloneAst(e)).toMText()}clearHistory(){this.undoStack=[],this.redoStack=[]}cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:this.cloneDocumentStyle(t.style)}:t.type==="stack"?{...t,style:this.cloneDocumentStyle(t.style)}:{...t,style:this.cloneDocumentStyle(t.style)})}}stackNodeToPlainText(e,t,i){if(i==="^"){if(e.length===0&&t.length>0)return`^${t.trimStart()}`;if(e.length>0&&t.length===0)return`${e.trimEnd()}^`}return`${e}${i}${t}`}scriptStackToPlainText(e,t,i){if(i!=="^")return null;const n=e.trim().length>0,s=t.trim().length>0;return n===s?null:n?e.trim():t.trim()}parseStackParts(e){const t=[];for(let c=0;c<e.length;c+=1){const l=e[c];(l==="/"||l==="#"||l==="^")&&t.push({index:c,divider:l})}if(t.length!==1)return null;const i=t[0];if(!i)return null;const{index:n,divider:s}=i,r=e.slice(0,n),o=e.slice(n+1);if(s==="^"){const c=r.trim().length>0,l=o.trim().length>0;return!c&&!l?null:{numerator:r,denominator:o,divider:s}}return r.trim().length===0||o.trim().length===0?null:{numerator:r,denominator:o,divider:s}}updateToolbarStackState(){var o;const e=this.getActiveToolbar();if(!e)return;const t=this.getSelectionRange();if(t.isCollapsed){e.setStackActive(!1);return}const i=this.toDocumentIndexFromLogicalIndex(t.start,!0),n=this.toDocumentIndexFromLogicalIndex(t.end,!1),s=this.document.ast.nodes.slice(i,n),r=s.length===1&&((o=s[0])==null?void 0:o.type)==="stack"&&!this.isScriptOnlyStack(s[0]);e.setStackActive(r)}isScriptOnlyStack(e){if(e.divider!=="^")return!1;const t=e.numerator.trim().length>0,i=e.denominator.trim().length>0;return t!==i}inferCurrentFormatFromDocument(){if(this.document.ast.nodes.length===0||this.getChars().length===0)return null;const n=this.selectionStart!==this.selectionEnd?Math.min(this.selectionStart,this.selectionEnd):this.cursorIndex>0?this.cursorIndex-1:0,s=this.getNodeByLogicalCharIndex(n);if(!s)return null;if(s.type==="stack"&&this.isScriptOnlyStack(s)){const r=s.numerator.trim().length>0?"superscript":"subscript";return{...this.toCharFormat(s.style),script:r}}return this.toCharFormat(s.style)}getNodeByLogicalCharIndex(e){const t=this.document.ast.nodes;if(t.length===0)return null;let i=0;const n=Math.max(0,e);for(const s of t){const r=this.getNodeLogicalSpan(s);if(n<i+r)return s;i+=r}return t[t.length-1]??null}getNodesByLogicalRange(e,t){const i=this.document.ast.nodes;if(i.length===0)return[];const n=Math.max(0,Math.min(e,t)),s=Math.max(n,Math.max(e,t));if(n===s)return[];const r=[];let o=0;for(const c of i){const l=this.getNodeLogicalSpan(c),h=o,d=o+l;l>0&&h<s&&d>n&&r.push(c),o=d}return r}toCharFormat(e){var C,b;const t=Math.max(1,this.defaultTextStyle.fixedTextHeight),i=e.capHeight.isRelative?t*Math.max(0,e.capHeight.value):e.capHeight.value,n=this.defaultTextStyle.font||this.baseFormat.fontFamily,s=e.rgb?this.rgbArrayToColorNumber(e.rgb):this.isExplicitAci(e.aci)?this.resolveAciColor(e.aci):this.resolveBaseColor(),r=this.isExplicitAci(e.aci)?e.aci:this.isExplicitAci(this.baseFormat.aci)?this.baseFormat.aci:null,o=this.toScriptFromStyle(e,t,i),c=Math.max(1,t)*.9,l=i<=c,h=o==="normal"?i:l?i/.7:i,d=(C=e.widthFactor)==null?void 0:C.value,g=typeof d=="number"&&Number.isFinite(d)?Math.max(.01,d):1,m=(b=e.charTrackingFactor)==null?void 0:b.value,y=typeof m=="number"&&Number.isFinite(m)?Math.max(.01,m):1,w=typeof e.oblique=="number"&&Number.isFinite(e.oblique)?e.oblique:0;return{fontFamily:e.fontFace.family||n,fontSize:Math.max(1,h||t),bold:e.fontFace.weight>=700,italic:e.fontFace.style==="Italic",underline:e.underline,overline:e.overline,strike:e.strikeThrough,script:o,aci:r,rgb:s,obliqueAngle:w,widthFactor:g,tracking:y,paragraphAlignment:e.paragraph.align}}toScriptFromStyle(e,t,i){const n=Math.max(1,t)*.9,s=i<=n;return e.script&&e.script!=="normal"?s?e.script:"normal":s&&e.align===B.MTextLineAlignment.TOP?"superscript":s&&e.align===B.MTextLineAlignment.BOTTOM?"subscript":"normal"}createDefaultParseContext(){const e=new B.MTextContext;if(e.fontFace.family=this.defaultTextStyle.font||this.baseFormat.fontFamily,e.fontFace.style=this.baseFormat.italic?"Italic":"Regular",e.fontFace.weight=this.baseFormat.bold?700:400,e.capHeight={value:this.defaultTextStyle.fixedTextHeight,isRelative:!1},e.align=B.MTextLineAlignment.BOTTOM,e.widthFactor={value:this.defaultTextStyle.widthFactor??1,isRelative:!1},this.isExplicitAci(this.baseFormat.aci))e.aci=this.baseFormat.aci,e.rgb=null;else{const t=this.resolveBaseColor();e.rgb=this.colorNumberToRgbArray(t),e.aci=256}return e}createNormalizedDocument(e){const t=Z.fromMText(e,this.createDefaultParseContext()),i={nodes:[]};for(const n of t.ast.nodes)switch(n.type){case"char":i.nodes.push({type:"char",value:n.value,style:this.cloneDocumentStyle(n.style)});break;case"stack":i.nodes.push({type:"stack",numerator:n.numerator,denominator:n.denominator,divider:n.divider,style:this.cloneDocumentStyle(n.style)});break;case"paragraphBreak":i.nodes.push({type:"paragraphBreak",style:this.cloneDocumentStyle(n.style)});break;case"columnBreak":case"wrapAtDimLine":i.nodes.push({type:"paragraphBreak",style:this.cloneDocumentStyle(n.style)});break}return new Z(i)}computeAttachmentAnchorOnBounds(e,t,i,n,s){const r=(e+t)*.5,o=(i+n)*.5,c=this.position.z;switch(s){case B.MTextAttachmentPoint.TopLeft:return new f.Vector3(e,n,c);case B.MTextAttachmentPoint.TopCenter:return new f.Vector3(r,n,c);case B.MTextAttachmentPoint.TopRight:return new f.Vector3(t,n,c);case B.MTextAttachmentPoint.MiddleLeft:return new f.Vector3(e,o,c);case B.MTextAttachmentPoint.MiddleCenter:return new f.Vector3(r,o,c);case B.MTextAttachmentPoint.MiddleRight:return new f.Vector3(t,o,c);case B.MTextAttachmentPoint.BottomLeft:case B.MTextAttachmentPoint.BaselineLeft:return new f.Vector3(e,i,c);case B.MTextAttachmentPoint.BottomCenter:case B.MTextAttachmentPoint.BaselineCenter:return new f.Vector3(r,i,c);case B.MTextAttachmentPoint.BottomRight:case B.MTextAttachmentPoint.BaselineRight:return new f.Vector3(t,i,c);default:return new f.Vector3(e,n,c)}}mapRibbonParagraphAlignment(e){switch(e){case"default":return B.MTextParagraphAlignment.DEFAULT;case"left":return B.MTextParagraphAlignment.LEFT;case"center":return B.MTextParagraphAlignment.CENTER;case"right":return B.MTextParagraphAlignment.RIGHT;case"justified":return B.MTextParagraphAlignment.JUSTIFIED;case"distributed":return B.MTextParagraphAlignment.DISTRIBUTED;default:return}}mapRibbonAttachmentCode(e){switch(e.trim().toUpperCase()){case"TL":return B.MTextAttachmentPoint.TopLeft;case"TC":return B.MTextAttachmentPoint.TopCenter;case"TR":return B.MTextAttachmentPoint.TopRight;case"ML":return B.MTextAttachmentPoint.MiddleLeft;case"MC":return B.MTextAttachmentPoint.MiddleCenter;case"MR":return B.MTextAttachmentPoint.MiddleRight;case"BL":return B.MTextAttachmentPoint.BottomLeft;case"BC":return B.MTextAttachmentPoint.BottomCenter;case"BR":return B.MTextAttachmentPoint.BottomRight;default:return}}attachmentPointToRibbonCode(e){switch(e){case B.MTextAttachmentPoint.TopLeft:return"TL";case B.MTextAttachmentPoint.TopCenter:return"TC";case B.MTextAttachmentPoint.TopRight:return"TR";case B.MTextAttachmentPoint.MiddleLeft:return"ML";case B.MTextAttachmentPoint.MiddleCenter:return"MC";case B.MTextAttachmentPoint.MiddleRight:return"MR";case B.MTextAttachmentPoint.BottomLeft:case B.MTextAttachmentPoint.BaselineLeft:return"BL";case B.MTextAttachmentPoint.BottomCenter:case B.MTextAttachmentPoint.BaselineCenter:return"BC";case B.MTextAttachmentPoint.BottomRight:case B.MTextAttachmentPoint.BaselineRight:return"BR";default:return"TL"}}mergeCharFormat(e,t){const i={...e,...t};if(t.aci!==void 0)if(!this.isExplicitAci(t.aci))i.aci=null;else{const n=this.resolveAciColor(t.aci);i.aci=t.aci,i.rgb=n}return t.rgb!==void 0&&(t.rgb===null?i.rgb=null:(i.rgb=this.normalizeColorNumber(t.rgb),t.aci===void 0&&(i.aci=null))),t.paragraphAlignment!==void 0&&(i.paragraphAlignment=t.paragraphAlignment),i}cloneDocumentStyle(e){return{underline:e.underline,overline:e.overline,strikeThrough:e.strikeThrough,script:e.script,aci:e.aci,rgb:e.rgb?[...e.rgb]:null,align:e.align,fontFace:{...e.fontFace},capHeight:{...e.capHeight},widthFactor:{...e.widthFactor},charTrackingFactor:{...e.charTrackingFactor},oblique:e.oblique,paragraph:{indent:e.paragraph.indent,left:e.paragraph.left,right:e.paragraph.right,align:e.paragraph.align,tabs:[...e.paragraph.tabs]}}}toDocumentStyle(e,t){const i=this.isExplicitAci(e.aci)?e.aci:null,n=i!==null?null:this.colorNumberToRgbArray(e.rgb!==null?e.rgb:this.resolveBaseColor()),s=e.script!=="normal",r=Math.max(1,e.fontSize*(s?.7:1)),o=e.script==="superscript"?B.MTextLineAlignment.TOP:e.script==="subscript"?B.MTextLineAlignment.BOTTOM:B.MTextLineAlignment.MIDDLE,c=e.paragraphAlignment;return{underline:e.underline,overline:e.overline,strikeThrough:e.strike,script:e.script,aci:i,rgb:n,align:o,fontFace:{family:e.fontFamily,style:e.italic?"Italic":"Regular",weight:e.bold?700:400},capHeight:{value:r,isRelative:!1},widthFactor:{value:Math.max(.01,e.widthFactor),isRelative:!1},charTrackingFactor:{value:Math.max(.01,e.tracking),isRelative:!1},oblique:e.obliqueAngle,paragraph:{indent:(t==null?void 0:t.paragraph.indent)??0,left:(t==null?void 0:t.paragraph.left)??0,right:(t==null?void 0:t.paragraph.right)??0,align:c,tabs:t!=null&&t.paragraph.tabs?[...t.paragraph.tabs]:[]}}}colorNumberToRgbArray(e){const t=this.normalizeColorNumber(e);return[t>>16&255,t>>8&255,t&255]}rgbArrayToColorNumber(e){const t=Math.max(0,Math.min(255,Math.round(e[0]))),i=Math.max(0,Math.min(255,Math.round(e[1]))),n=Math.max(0,Math.min(255,Math.round(e[2])));return t<<16|i<<8|n}};I(R,"activeEditor",null),I(R,"sharedToolbar",null),I(R,"sharedToolbarContainer",null),I(R,"sharedToolbarFontFamiliesKey",""),I(R,"sharedToolbarColorPickerFactory",null),I(R,"instances",new Set),I(R,"FALLBACK_LINE_ADVANCE_RATIO",1.5),I(R,"DEFAULT_TEXT_STYLE",{name:"MTextInputBoxStyle",standardFlag:0,fixedTextHeight:24,widthFactor:1,obliqueAngle:0,textGenerationFlag:0,lastHeight:24,font:hi,bigFont:""}),I(R,"DEFAULT_LINE_SPACE_FACTOR",.3);let pn=R;function gc(a){if(a===void 0)return;const e=a;return e>=1&&e<=12?e:B.MTextAttachmentPoint.TopLeft}function yu(a){return a}const mi="__mlightcadMTextFormatBridge",H=class H{static setDefaultColorPicker(e){H.defaultColorPicker=e}static setDefaultToolbarEnabled(e){H.defaultToolbarEnabled=e}static getActiveInputBox(){return H.activeInputBox}static addActiveInputBoxChangeListener(e){H.activeInputBoxChangeListeners.add(e)}static removeActiveInputBoxChangeListener(e){H.activeInputBoxChangeListeners.delete(e)}static setActiveInputBox(e){H.activeInputBox!==e&&(H.activeInputBox=e,H.activeInputBoxChangeListeners.forEach(t=>{t(e)}))}static createHiddenToolbarContainer(e){const t=e.ownerDocument.createElement("div");return t.setAttribute("aria-hidden","true"),Object.assign(t.style,{display:"none",pointerEvents:"none"}),e.appendChild(t),t}static attachFormatBridge(e){const t=e;if(t[mi])return;const i=new Set,n=[],s=()=>{i.forEach(o=>{o()})},r=o=>{const c=t[o];typeof c=="function"&&(t[o]=(...l)=>{const h=c.apply(t,l);return s(),h},n.push(()=>{t[o]=c}))};["setCurrentFormat","refreshCurrentFormatFromDocument","toggleCase","toggleStackSelection","toggleScriptSelection","setParagraphAlignment","setAttachmentPoint","setLineSpacingFactor","clearLineSpacing"].forEach(r),t.addCurrentFormatChangeListener=o=>{i.add(o)},t.removeCurrentFormatChangeListener=o=>{i.delete(o)},t.focusEditor=()=>{const o=t,c=o.focusImeInput;if(typeof c=="function"){c.call(t);return}const l=o.refocusImeInputSoon;typeof l=="function"&&l.call(t)},t.isStackSelectionActive=()=>{var A,_;const o=t,c=o.getSelectionRange,l=o.toDocumentIndexFromLogicalIndex,h=o.isScriptOnlyStack,d=o.document;if(typeof c!="function"||typeof l!="function")return!1;const g=c.call(t);if(!g||g.isCollapsed)return!1;const m=l.call(t,g.start,!0),y=l.call(t,g.end,!1),w=((_=(A=d==null?void 0:d.ast)==null?void 0:A.nodes)==null?void 0:_.slice(m,y))??[],C=w[0];if(w.length!==1||(C==null?void 0:C.type)!=="stack")return!1;if(typeof h=="function")return!h.call(t,C);if(C.divider!=="^")return!0;const b=(C.numerator??"").trim().length>0,x=(C.denominator??"").trim().length>0;return b===x},t[mi]={addCurrentFormatChangeListener:t.addCurrentFormatChangeListener,removeCurrentFormatChangeListener:t.removeCurrentFormatChangeListener,dispose:()=>{n.forEach(o=>{o()}),i.clear(),delete t.addCurrentFormatChangeListener,delete t.removeCurrentFormatChangeListener,delete t.focusEditor,delete t.isStackSelectionActive,delete t[mi]}}}static detachFormatBridge(e){var i;(i=e[mi])==null||i.dispose()}open(e){const{view:t,location:i,width:n,textHeight:s,initialText:r="",toolbarFontFamilies:o=[],toolbarColorPicker:c,toolbarEnabled:l=H.defaultToolbarEnabled,initialAttachmentPoint:h}=e,d=new f.Vector3(i.x,i.y,i.z??0),m=t.backgroundColor===16777215?"#000000":"#ffffff",y=S.instance,w=y.curDocument.database,{layerColor:C}=y.resolveColors(),b=()=>{const M=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.COLORTHEME,w);return M===0||M==="0"||M===!1||M==="dark"?"dark":"light"},x=Array.from(new Set(o.map(M=>M.trim()).filter(M=>M.length>0))),A=()=>{const M=w.tables.textStyleTable.getAt(w.textstyle);return M==null?void 0:M.textStyle},_=Math.max(1,s),L=A(),T=L?{...L,fixedTextHeight:_,lastHeight:_}:void 0,O=l?null:H.createHiddenToolbarContainer(t.container),k=gc(h),E=new pn({scene:t.internalScene,camera:t.internalCamera,width:n,position:d.clone(),initialText:r,...k!==void 0?{initialAttachmentPoint:k}:{},textStyle:T,cursorStyle:{color:m,glowColor:m},boundingBoxStyle:{padding:0},imeTarget:t.canvas,colorSettings:{layer:w.clayer,color:new B.MTextColor,byLayerColor:C,byBlockColor:C},toolbar:{enabled:!0,theme:b(),fontFamilies:x,container:O??t.container,offsetY:10,colorPicker:c??H.defaultColorPicker??void 0}});return H.attachFormatBridge(E),H.setActiveInputBox(E),new Promise(M=>{let F=!1;const z=()=>{F||(E.update(),t.isDirty=!0)},U=W=>{W.name.toLowerCase()===u.AcDbSystemVariables.COLORTHEME.toLowerCase()&&(E.setToolbarTheme(b()),t.isDirty=!0)},V=()=>{H.activeInputBox===E&&H.setActiveInputBox(null),H.detachFormatBridge(E),E.dispose(),O==null||O.remove(),t.events.renderFrame.removeEventListener(z),E.off("close",G),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(U),t.isDirty=!0},K=W=>{F||(F=!0,V(),M(W))},G=()=>{var ee;const W=E.getMTextInsertionPoint();K({contents:E.getText(),location:{x:W.x,y:W.y,z:W.z},width:n,height:_,lineSpacingFactor:((ee=E.getLineSpacingFactor)==null?void 0:ee.call(E))??H.defaultLineSpacingFactor,attachmentPoint:E.getMTextAttachmentPoint()})};E.on("close",G),t.events.renderFrame.addEventListener(z),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(U)})}};H.defaultLineSpacingFactor=.3,H.activeInputBox=null,H.activeInputBoxChangeListeners=new Set,H.defaultColorPicker=null,H.defaultToolbarEnabled=!0;let Re=H;class Ms{constructor(e){this.events={sysVarChanged:new u.AcCmEventManager,commandWillStart:new u.AcCmEventManager,commandEnded:new u.AcCmEventManager},this._view=e,this._cursorManager=new cs(e),this._inputManager=new li(e)}get isActive(){return this._inputManager.isActive}get isEntitySelectionActive(){return this._inputManager.isEntitySelectionActive}getInputModifiers(){return this._inputManager.modifiers}getInputToggles(){return this._inputManager.toggles}resetInputToggles(){this._inputManager.resetToggles()}enqueueScriptInputs(e){this._inputManager.enqueueScriptInputs(e)}clearScriptInputs(){this._inputManager.clearScriptInputs()}showMessage(e,t="info",i){this._inputManager.showMessage(e,t,i)}peekScriptInput(){return this._inputManager.peekScriptInput()}consumeScriptInput(){return this._inputManager.consumeScriptInput()}get currentCursor(){return this._currentCursor}restoreCursor(){this._previousCursor!=null&&this.setCursor(this._previousCursor)}setCursor(e){this._cursorManager.setCursor(e),this._previousCursor=this._currentCursor,this._currentCursor=e}async withCursor(e,t){const i=this._currentCursor;this.setCursor(e);try{return await Promise.resolve(t())}finally{i!==void 0?this.setCursor(i):this.restoreCursor()}}setCursorColor(e){this._cursorManager.setCursorColor(e)}async getPoint(e){return await this._inputManager.getPoint(e)}async getAngle(e){return await this._inputManager.getAngle(e)}async getDistance(e){return await this._inputManager.getDistance(e)}async getDouble(e){return await this._inputManager.getDouble(e)}async getInteger(e){return await this._inputManager.getInteger(e)}async getString(e){return await this._inputManager.getString(e)}async getKeywords(e){return await this._inputManager.getKeywords(e)}async getEntity(e){return await this._inputManager.getEntity(e)}async getSelection(e){return await this._inputManager.getSelection(e)}async getBox(e){return await this._inputManager.getBox(e)}selectAll(e){try{const t=S.instance.curDocument.database.tables.blockTable.modelSpace,i=[];for(const n of t.newIterator())(!e||e.matches(n))&&i.push(n.objectId);return new xt(v.OK,new ei(i))}catch{return new xt(v.Error)}}}class ${constructor(e){this.view=e}render(){this.entity&&this.view.addTransientEntity(this.entity)}end(){this.entity&&this.view.removeTransientEntity(this.entity.objectId)}}class Te{constructor(e){this.state=e}setState(e){this.state=e}async run(e){for(;this.state;)try{const t=this.state.buildPrompt(),i=await e(t);if(await this.state.handleResult(i)==="finish")break}catch{break}}}class mc{constructor(e=[]){this._typedValues=[...e]}get typedValues(){return[...this._typedValues]}matches(e){if(this._typedValues.length===0)return!0;let t="equals";for(const i of this._typedValues){if(i.code===u.AcDbDxfCode.Operator){t=this.parseOperator(i.value);continue}if(!this.matchTypedValue(e,i,t))return!1;t="equals"}return!0}parseOperator(e){switch(String(e??"").trim()){case"!=":case"<>":return"notEquals";case">":return"greaterThan";case">=":return"greaterThanOrEqual";case"<":return"lessThan";case"<=":return"lessThanOrEqual";case"=":case"==":default:return"equals"}}matchTypedValue(e,t,i){const n=this.resolveEntityValue(e,t.code);return n==null?!1:this.compare(n,t.value,i)}resolveEntityValue(e,t){var i;switch(t){case u.AcDbDxfCode.Start:return e.dxfTypeName||e.type;case u.AcDbDxfCode.LayerName:return e.layer;case u.AcDbDxfCode.ColorName:return(i=e.color)==null?void 0:i.toString();case u.AcDbDxfCode.LinetypeName:return e.lineType;case u.AcDbDxfCode.LineWeight:return Number(e.lineWeight);default:return}}compare(e,t,i){const n=Number(e),s=Number(t);if(Number.isFinite(n)&&Number.isFinite(s)&&`${e}`.trim()!==""&&`${t}`.trim()!=="")switch(i){case"equals":return n===s;case"notEquals":return n!==s;case"greaterThan":return n>s;case"greaterThanOrEqual":return n>=s;case"lessThan":return n<s;case"lessThanOrEqual":return n<=s}const o=String(e).toLowerCase(),c=String(t).toLowerCase();switch(i){case"equals":return o===c;case"notEquals":return o!==c;case"greaterThan":return o>c;case"greaterThanOrEqual":return o>=c;case"lessThan":return o<c;case"lessThanOrEqual":return o<=c}}}class Os{constructor(e,t,i,n=500,s=500){this.host=e,this.hoverEvent=t,this.unhoverEvent=i,this.hoverDelay=n,this.pauseDelay=s,this.hoverTimer=null,this.pauseTimer=null,this.hoveredId=null}handleMouseMove(e,t){if(this.clearHoverTimer(),this.hoveredId){this.hoverAt(e,t);return}this.hoverTimer=setTimeout(()=>{this.hoverAt(e,t)},this.hoverDelay)}clear(){this.setHoveredId(null),this.clearHoverTimer(),this.clearPauseTimer()}dispose(){this.clearHoverTimer(),this.clearPauseTimer()}hoverAt(e,t){const i=this.host.pick({x:e,y:t});i.length>0?this.setHoveredId(i[0].id):this.clear()}setHoveredId(e){this.hoveredId!==e&&(this.hoveredId&&(this.unhoverEvent.dispatch({id:this.hoveredId,x:this.host.curMousePos.x,y:this.host.curMousePos.y}),this.host.onUnhover(this.hoveredId)),this.hoveredId=e,e&&(this.startPauseTimer(e),this.host.onHover(e)))}startPauseTimer(e){this.clearPauseTimer(),this.pauseTimer=setTimeout(()=>{this.hoverEvent.dispatch({id:e,x:this.host.curMousePos.x,y:this.host.curMousePos.y})},this.pauseDelay)}clearHoverTimer(){this.hoverTimer&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}clearPauseTimer(){this.pauseTimer&&(clearTimeout(this.pauseTimer),this.pauseTimer=null)}}function gn(a,e="replace"){return a.shiftKey?"remove":a.ctrlKey||a.metaKey?"add":e}function Fs(a){return gn(a,"add")}var se=(a=>(a[a.SELECTION=0]="SELECTION",a[a.PAN=1]="PAN",a))(se||{});class js{constructor(e,t){this.events={mouseMove:new u.AcCmEventManager,viewResize:new u.AcCmEventManager,viewChanged:new u.AcCmEventManager,hover:new u.AcCmEventManager,unhover:new u.AcCmEventManager,renderFrame:new u.AcCmEventManager},this._container=t,this._canvas=e;const i=e.getBoundingClientRect();this._bbox=new u.AcGeBox3d,this._width=i.width,this._height=i.height,this._curPos=new u.AcGePoint2d,this._curMousePos=new u.AcGePoint2d,this._selectionSet=new ei,this._editor=new Ms(this),this._canvas.addEventListener("mousemove",r=>this.onMouseMove(r)),this._canvas.addEventListener("mousedown",r=>{r.button===1&&this._editor.setCursor(be.Grab)}),this._canvas.addEventListener("mouseup",r=>{r.button===1&&this._editor.restoreCursor()});const n=Ue.debounce(()=>this.onWindowResize(),0,{leading:!1,trailing:!0});new ResizeObserver(n).observe(this._canvas.parentElement),this._selectionBoxSize=4,this._hoverController=new Os(this,this.events.hover,this.events.unhover)}get editor(){return this._editor}get selectionBoxSize(){return this._selectionBoxSize}set selectionBoxSize(e){this._selectionBoxSize=e}async withMode(e,t){const i=this.mode;this.mode=e;try{return await Promise.resolve(t())}finally{this.mode=i}}setCursor(e){this._editor.setCursor(e)}getSelectionMode(e,t){return t.x>=e.x?"window":"crossing"}getSelectionActionFromEvent(e,t="replace"){return gn(e,t)}isSelectionClick(e,t,i=2){const n=t.x-e.x,s=t.y-e.y;return Math.hypot(n,s)<i}getSelectionPreviewStyle(e,t){return{borderStyle:e==="window"?"solid":"dashed",lineColor:t==="remove"?"var(--ml-ui-danger, #ff4d4f)":e==="window"?"var(--ml-ui-canvas-line, #00ff5a)":"var(--ml-ui-accent-alt, #00d1ff)",background:"var(--ml-ui-canvas-fill-mix, var(--ml-ui-canvas-fill, rgba(64, 158, 255, 0.12)))"}}applySelection(e,t){if(t==="replace"){this.selectionSet.clear();const i=e.filter(n=>!this.selectionSet.has(n));i.length>0&&this.selectionSet.add(i);return}if(e.length!==0)if(t==="add"){const i=e.filter(n=>!this.selectionSet.has(n));i.length>0&&this.selectionSet.add(i)}else{const i=e.filter(n=>this.selectionSet.has(n));i.length>0&&this.selectionSet.delete(i)}}selectByBoxWithMode(e,t,i="add"){const n=this.collectSelectionIdsByBox(e,t);this.applySelection(n,i)}collectSelectionIdsByBox(e,t){const i=this.search(e),n=[];return i.forEach(s=>{(t==="crossing"||s.minX>=e.min.x&&s.maxX<=e.max.x&&s.minY>=e.min.y&&s.maxY<=e.max.y)&&n.push(s.id)}),n}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 container(){return this._container}viewportToCanvas(e){const t=this._canvas.getBoundingClientRect();return new u.AcGePoint2d(e.x-t.left,e.y-t.top)}canvasToViewport(e){const t=this._canvas.getBoundingClientRect();return new u.AcGePoint2d(e.x+t.left,e.y+t.top)}canvasToContainer(e){const t=this._canvas.getBoundingClientRect(),i=this._container.getBoundingClientRect();return new u.AcGePoint2d(e.x+(t.left-i.left),e.y+(t.top-i.top))}viewportToContainer(e){const t=this._container.getBoundingClientRect();return new u.AcGePoint2d(e.x-t.left,e.y-t.top)}get aspect(){return this._width/this._height}get curPos(){return this._curPos}get curMousePos(){return this._curMousePos}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})}clearHover(){this._hoverController.clear()}onMouseMove(e){this._curMousePos=this.viewportToCanvas({x:e.clientX,y:e.clientY});const t=this.screenToWorld(this._curMousePos);this._curPos.copy(t),this.events.mouseMove.dispatch({x:t.x,y:t.y}),this.mode==0&&(this._editor.isActive||this._hoverController.handleMouseMove(t.x,t.y))}}var j=(a=>(a[a.Read=0]="Read",a[a.Review=4]="Review",a[a.Write=8]="Write",a))(j||{});class N{constructor(){this._mode=j.Read,this._globalName="",this._localName="",this._userData={}}get userData(){return this._userData}get globalName(){return this._globalName}set globalName(e){this._globalName=e}get localName(){return this._localName}set localName(e){this._localName=e}get mode(){return this._mode}set mode(e){this._mode=e}onCommandWillStart(e){}onCommandEnded(e){}async trigger(e){try{this.onCommandWillStart(e),e.view.editor.events.commandWillStart.dispatch({command:this}),await this.execute(e)}finally{e.view.editor.events.commandEnded.dispatch({command:this}),this.onCommandEnded(e)}}async execute(e){}}class yc{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 ft=class ft{constructor(){this._commandsByGroup=[],this._systemCommandGroup={groupName:ft.SYSTEMT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._defaultCommandGroup={groupName:ft.DEFAUT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._commandsByGroup.push(this._systemCommandGroup),this._commandsByGroup.push(this._defaultCommandGroup)}addCommand(e,t,i,n,s){if(e=e.toUpperCase(),t=t.toUpperCase(),i=i.toUpperCase(),!t)throw new Error("[AcEdCommandStack] The global name of the command is required!");i||(i=t);let r=this._defaultCommandGroup;if(e){const c=this._commandsByGroup.find(l=>l.groupName==e);c?r=c:(r={groupName:e,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._commandsByGroup.push(r))}if(r.commandsByGlobalName.has(t))throw new Error(`[AcEdCommandStack] The command with global name '${t}' already exists!`);if(r.commandsByLocalName.has(i))throw new Error(`[AcEdCommandStack] The command with local name '${i}' already exists!`);const o=this.normalizeAliases(s,t,i);for(const c of o){if(r.commandsByAlias.has(c))throw new Error(`[AcEdCommandStack] The command alias '${c}' already exists!`);if(r.commandsByGlobalName.has(c)||r.commandsByLocalName.has(c))throw new Error(`[AcEdCommandStack] The command alias '${c}' conflicts with existing command name!`)}r.commandsByGlobalName.set(t,n),r.commandsByLocalName.set(i,n),o.forEach(c=>{r.commandsByAlias.set(c,n)}),r.aliasesByCommand.set(n,new Set(o)),n.globalName=t,n.localName=i}iterator(){return new yc(this._commandsByGroup)}searchCommandsByPrefix(e,t){e=e.toUpperCase();const i=[],n=this.iterator();let s=n.next();for(;!s.done;){const{command:r}=s.value;(r.globalName.startsWith(e)||r.localName.startsWith(e)||this.commandAliasStartsWith(s.value.commandGroup,r,e))&&(t===void 0||this.isModeCompatible(t,r.mode))&&i.push(s.value),s=n.next()}return i}lookupGlobalCmd(e,t){e=e.toUpperCase();let i;for(const n of this._commandsByGroup)if(i=n.commandsByGlobalName.get(e),i||(i=n.commandsByAlias.get(e)),i){if(t===void 0||this.isModeCompatible(t,i.mode))break;i=void 0}return i}lookupLocalCmd(e,t){e=e.toUpperCase();let i;for(const n of this._commandsByGroup)if(i=n.commandsByLocalName.get(e),i||(i=n.commandsByAlias.get(e)),i){if(t===void 0||this.isModeCompatible(t,i.mode))break;i=void 0}return i}removeCmd(e,t){e=e.toUpperCase(),t=t.toUpperCase();for(const i of this._commandsByGroup)if(i.groupName==e){const n=i.commandsByGlobalName.get(t);if(!n)return!1;i.commandsByGlobalName.delete(t),i.commandsByLocalName.delete(n.localName);const s=i.aliasesByCommand.get(n);return s==null||s.forEach(r=>{i.commandsByAlias.delete(r)}),i.aliasesByCommand.delete(n),!0}return!1}removeGroup(e){e=e.toUpperCase();const t=this._commandsByGroup.findIndex(i=>i.groupName===e);return t>=0?(this._commandsByGroup.splice(t,1),!0):!1}removeAll(){this._defaultCommandGroup.commandsByGlobalName.clear(),this._defaultCommandGroup.commandsByLocalName.clear(),this._defaultCommandGroup.commandsByAlias.clear(),this._defaultCommandGroup.aliasesByCommand.clear(),this._systemCommandGroup.commandsByGlobalName.clear(),this._systemCommandGroup.commandsByLocalName.clear(),this._systemCommandGroup.commandsByAlias.clear(),this._systemCommandGroup.aliasesByCommand.clear(),this._commandsByGroup=[this._systemCommandGroup,this._defaultCommandGroup]}getCommandAliases(e,t){const i=t==null?void 0:t.trim().toUpperCase(),n=i?this._commandsByGroup.filter(s=>s.groupName===i):this._commandsByGroup;for(const s of n){const r=s.aliasesByCommand.get(e);if(r)return[...r]}return[]}commandAliasStartsWith(e,t,i){const n=this._commandsByGroup.find(r=>r.groupName===e);if(!n)return!1;const s=n.aliasesByCommand.get(t);if(!s)return!1;for(const r of s)if(r.startsWith(i))return!0;return!1}normalizeAliases(e,t,i){const n=Array.isArray(e)?e:e?[e]:[],s=new Set;return n.forEach(r=>{const o=r.trim().toUpperCase();o&&o!==t&&o!==i&&s.add(o)}),[...s]}isModeCompatible(e,t){return e>=t}};ft.SYSTEMT_COMMAND_GROUP_NAME="ACAD",ft.DEFAUT_COMMAND_GROUP_NAME="USER";let le=ft;function fc(a){return{all:a=a||new Map,on:function(e,t){var i=a.get(e);i?i.push(t):a.set(e,[t])},off:function(e,t){var i=a.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):a.set(e,[]))},emit:function(e,t){var i=a.get(e);i&&i.slice().map(function(n){n(t)}),(i=a.get("*"))&&i.slice().map(function(n){n(e,t)})}}}const J=fc();function wc(a){J.emit("message",{message:a,type:"warning"})}class mn{constructor(e,t,i=1e3,n=0){this.condition=e,this.action=t,this.checkInterval=i,this.timeout=n,this.timerId=null,this.timeoutId=null}start(){this.timerId===null&&(this.timerId=window.setInterval(()=>{this.condition()&&this.executeAndStop()},this.checkInterval),this.timeout>0&&(this.timeoutId=window.setTimeout(()=>{u.log.warn("AcEdConditionWaiter: Timeout reached."),this.executeAndStop()},this.timeout)))}stop(){this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}executeAndStop(){this.stop(),this.action()}isRunning(){return this.timerId!==null}}const bc={light:{"--ml-ui-text":"var(--el-text-color-primary, #303133)","--ml-ui-text-muted":"var(--el-text-color-regular, #606266)","--ml-ui-bg":"var(--el-bg-color-overlay, #ffffff)","--ml-ui-border":"var(--el-border-color, #dcdfe6)","--ml-ui-shadow":"var(--el-box-shadow, 0 2px 6px rgba(0, 0, 0, 0.12))","--ml-ui-overlay":"var(--el-overlay-color-lighter, rgba(0, 0, 0, 0.18))","--ml-ui-accent":"var(--el-color-primary, #409eff)","--ml-ui-accent-alt":"var(--el-color-info, #909399)","--ml-ui-danger":"var(--el-color-danger, #f56c6c)","--ml-ui-canvas-line":"var(--el-color-primary, #409eff)","--ml-ui-canvas-fill":"rgba(64, 158, 255, 0.2)","--ml-ui-canvas-fill-mix":"color-mix(in srgb, var(--el-color-primary, #409eff) 20%, transparent)"},dark:{"--ml-ui-text":"var(--el-text-color-primary, #e5eaf3)","--ml-ui-text-muted":"var(--el-text-color-regular, #cfd3dc)","--ml-ui-bg":"var(--el-bg-color-overlay, #1d1e1f)","--ml-ui-border":"var(--el-border-color, #4c4d4f)","--ml-ui-shadow":"var(--el-box-shadow, 0 6px 18px rgba(0, 0, 0, 0.35))","--ml-ui-overlay":"var(--el-overlay-color-lighter, rgba(0, 0, 0, 0.5))","--ml-ui-accent":"var(--el-color-primary, #409eff)","--ml-ui-accent-alt":"var(--el-color-info, #909399)","--ml-ui-danger":"var(--el-color-danger, #f56c6c)","--ml-ui-canvas-line":"var(--el-color-primary, #409eff)","--ml-ui-canvas-fill":"rgba(64, 158, 255, 0.2)","--ml-ui-canvas-fill-mix":"color-mix(in srgb, var(--el-color-primary, #409eff) 20%, transparent)"}};function Ns(a,e=document.documentElement){const t=bc[a];Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])}),e.setAttribute("data-ml-ui-theme",a)}function Rs(a,e=document.documentElement){Ns(a===16777215?"light":"dark",e)}class zs{constructor(){this._fileName="",this._docTitle="",this._openMode=j.Write,this._database=new u.AcDbDatabase,this.docTitle="Untitled",this._openMode=j.Write}async openUri(e,t){this._uri=e,this._openMode=(t==null?void 0:t.mode)??j.Read,this._fileName=this.getFileNameFromUri(e);let i=!0;try{const n={...t,readOnly:this._openMode===j.Read};await this._database.openUri(e,n),this.docTitle=this._fileName}catch{i=!1,J.emit("failed-to-open-file",{fileName:e})}return i}async openDocument(e,t,i){var s;let n=!0;this._fileName=e,this._openMode=(i==null?void 0:i.mode)??j.Read;try{const r=(s=e.split(".").pop())==null?void 0:s.toLocaleLowerCase(),o={...i,readOnly:this._openMode===j.Read};await this._database.read(t,o,r=="dwg"?u.AcDbFileType.DWG:u.AcDbFileType.DXF),this.docTitle=this._fileName}catch{n=!1,J.emit("failed-to-open-file",{fileName:e})}return n}get uri(){return this._uri}get database(){return this._database}get fileName(){return this._fileName}get docTitle(){return this._docTitle}set docTitle(e){this._docTitle=e}get openMode(){return this._openMode}getFileNameFromUri(e){try{const i=new URL(e).pathname.split("/");return i[i.length-1]||""}catch(t){return u.log.error("Invalid URI:",t),""}}}var te=function(){return te=Object.assign||function(a){for(var e,t=1,i=arguments.length;t<i;t++){e=arguments[t];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(a[n]=e[n])}return a},te.apply(this,arguments)},yi=function(a){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&a[e],i=0;if(t)return t.call(a);if(a&&typeof a.length=="number")return{next:function(){return a&&i>=a.length&&(a=void 0),{value:a&&a[i++],done:!a}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Vs=function(){function a(){}return a.prototype.convert=function(e){var t=this.createEntity(e);return t&&this.processCommonAttrs(e,t),t},a.prototype.createEntity=function(e){return e.type=="3DFACE"?this.convertFace(e):e.type=="ARC"?this.convertArc(e):e.type=="ATTDEF"?this.convertAttributeDefinition(e):e.type=="ATTRIB"?this.convertAttribute(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=="MLINE"?this.convertMLine(e):e.type=="MTEXT"?this.convertMText(e):e.type=="MULTILEADER"||e.type=="MLEADER"?this.convertMLeader(e):e.type=="POINT"?this.convertPoint(e):e.type=="POLYLINE2D"?this.convertPolyline2d(e):e.type=="POLYLINE3D"?this.convertPolyline3d(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},a.prototype.convertFace=function(e){var t=new u.AcDbFace;return e.corner1&&t.setVertexAt(0,e.corner1),e.corner2&&t.setVertexAt(1,e.corner2),e.corner3&&t.setVertexAt(2,e.corner3),e.corner4&&t.setVertexAt(3,e.corner4),t.setEdgeInvisibilities(e.flag),t},a.prototype.convertArc=function(e){var t,i=(t=e.extrusionDirection)!==null&&t!==void 0?t:u.AcGeVector3d.Z_AXIS,n=new u.AcDbArc(u.transformOcsPointToWcs(e.center,i),e.radius,e.startAngle,e.endAngle,i);return n},a.prototype.convertCirle=function(e){var t,i=(t=e.extrusionDirection)!==null&&t!==void 0?t:u.AcGeVector3d.Z_AXIS,n=new u.AcDbCircle(u.transformOcsPointToWcs(e.center,i),e.radius,i);return n},a.prototype.convertEllipse=function(e){var t,i=new u.AcGeVector3d(e.majorAxisEndPoint),n=i.length(),s=new u.AcDbEllipse(e.center,(t=e.extrusionDirection)!==null&&t!==void 0?t:u.AcGeVector3d.Z_AXIS,i,n,n*e.axisRatio,e.startAngle,e.endAngle);return s},a.prototype.convertLine=function(e){var t=e.startPoint,i=e.endPoint,n=new u.AcDbLine(new u.AcGePoint3d(t.x,t.y,t.z),new u.AcGePoint3d(i.x,i.y,i.z));return n},a.prototype.convertSpline=function(e){try{if(e.numberOfControlPoints>0&&e.numberOfKnots>0)return new u.AcDbSpline(e.controlPoints,e.knots,e.weights,e.degree,!!(e.flag&1));if(e.numberOfFitPoints>0)return new u.AcDbSpline(e.fitPoints,"Uniform",e.degree,!!(e.flag&1))}catch(t){console.log("Failed to convert spline with error: ".concat(t))}return null},a.prototype.convertPoint=function(e){var t=new u.AcDbPoint;return t.position=e.position,t},a.prototype.convertSolid=function(e){var t=new u.AcDbTrace;return t.setPointAt(0,te(te({},e.corner1),{z:0})),t.setPointAt(1,te(te({},e.corner2),{z:0})),t.setPointAt(2,te(te({},e.corner3),{z:0})),t.setPointAt(3,e.corner4?te(te({},e.corner4),{z:0}):te(te({},e.corner3),{z:0})),t.thickness=e.thickness,t},a.prototype.convertLWPolyline=function(e){var t,i=new u.AcDbPolyline;i.closed=!!(e.flag&512);var n=(t=e.constantWidth)!==null&&t!==void 0?t:-1;return e.vertices.forEach(function(s,r){var o,c;i.addVertexAt(r,new u.AcGePoint2d(s.x,s.y),s.bulge,(o=s.startWidth)!==null&&o!==void 0?o:n,(c=s.endWidth)!==null&&c!==void 0?c:n)}),i},a.prototype.convertPolyline2d=function(e){var t,i,n=!!(e.flag&1),s=!!(e.flag&16),r=!!(e.flag&64),o=!!(e.flag&32),c=[],l=[],h=[];if(e.vertices.map(function(y){var w,C;if(!(y.flag&16))if(r&&y.flag&128)if(y.flag&64)c.push({x:y.x,y:y.y,z:y.z}),l.push((w=y.bulge)!==null&&w!==void 0?w:0);else{var b=[];y.polyfaceIndex0!=null&&y.polyfaceIndex0!=0&&b.push(Math.abs(y.polyfaceIndex0)-1),y.polyfaceIndex1!=null&&y.polyfaceIndex1!=0&&b.push(Math.abs(y.polyfaceIndex1)-1),y.polyfaceIndex2!=null&&y.polyfaceIndex2!=0&&b.push(Math.abs(y.polyfaceIndex2)-1),y.polyfaceIndex3!=null&&y.polyfaceIndex3!=0&&b.push(Math.abs(y.polyfaceIndex3)-1),b.length>=3&&h.push(b)}else c.push({x:y.x,y:y.y,z:y.z}),l.push((C=y.bulge)!==null&&C!==void 0?C:0)}),s){var d=(t=e.meshMVertexCount)!==null&&t!==void 0?t:2,g=(i=e.meshNVertexCount)!==null&&i!==void 0?i:2;return new u.AcDbPolygonMesh(d,g,c,n,o)}else{if(r)return new u.AcDbPolyFaceMesh(c,h);var m=u.AcDbPoly2dType.SimplePoly;return e.flag&2?m=u.AcDbPoly2dType.FitCurvePoly:e.flag&4&&(e.smoothType==6?m=u.AcDbPoly2dType.CubicSplinePoly:e.smoothType==5&&(m=u.AcDbPoly2dType.QuadSplinePoly)),new u.AcDb2dPolyline(m,c,0,n,e.startWidth,e.endWidth,l)}},a.prototype.convertPolyline3d=function(e){var t=!!(e.flag&1),i=[];e.vertices.map(function(s){s.flag&16||i.push({x:s.x,y:s.y,z:s.z})});var n=u.AcDbPoly3dType.SimplePoly;return e.flag&4&&(e.smoothType==6?n=u.AcDbPoly3dType.CubicSplinePoly:e.smoothType==5&&(n=u.AcDbPoly3dType.QuadSplinePoly)),new u.AcDb3dPolyline(n,i,t)},a.prototype.convertHatch=function(e){var t,i,n,s,r=new u.AcDbHatch;(t=e.definitionLines)===null||t===void 0||t.forEach(function(h){r.definitionLines.push({angle:h.angle,base:h.base,offset:h.offset,dashLengths:h.numberOfDashLengths>0?h.dashLengths:[]})}),r.isSolidFill=e.solidFill==1,r.hatchStyle=e.hatchStyle,r.patternName=e.patternName,r.patternType=e.patternType,r.patternAngle=e.patternAngle==null?0:e.patternAngle,r.patternScale=e.patternScale==null?0:e.patternScale;var o=e.boundaryPaths;if(o.forEach(function(h){var d=h.boundaryPathTypeFlag;if(d&2){var g=h,m=new u.AcGePolyline2d;m.closed=g.isClosed,g.vertices.forEach(function(b,x){m.addVertexAt(x,{x:b.x,y:b.y,bulge:b.bulge})}),r.add(m)}else{var y=h,w=[];y.edges.forEach(function(b){if(b!=null){if(b.type==1){var x=b;w.push(new u.AcGeLine2d(x.start,x.end))}else if(b.type==2){var A=b;w.push(new u.AcGeCircArc2d(A.center,A.radius,A.startAngle,A.endAngle,!A.isCCW))}else if(b.type==3){var _=b,L=new u.AcGeVector2d;L.subVectors(_.end,_.center);var T=Math.sqrt(Math.pow(_.end.x,2)+Math.pow(_.end.y,2)),O=T*_.lengthOfMinorAxis,k=_.startAngle,E=_.endAngle,M=Math.atan2(_.end.y,_.end.x);_.isCCW||(k=Math.PI*2-k,E=Math.PI*2-E),w.push(new u.AcGeEllipseArc2d(te(te({},_.center),{z:0}),T,O,k,E,!_.isCCW,M))}else if(b.type==4){var F=b;if(F.numberOfControlPoints>0&&F.numberOfKnots>0){var z=F.controlPoints.map(function(G){return{x:G.x,y:G.y,z:0}}),U=!0,V=F.controlPoints.map(function(G){return G.weight==null&&(U=!1),G.weight||1});w.push(new u.AcGeSpline3d(z,F.knots,U?V:void 0))}else if(F.numberOfFitData>0){var K=F.fitDatum.map(function(G){return{x:G.x,y:G.y,z:0}});w.push(new u.AcGeSpline3d(K,"Uniform"))}}}});var C=u.AcGeLoop2d.buildFromEdges(w);C.length==0&&w.length>0?r.add(new u.AcGeLoop2d(w)):C.forEach(function(b){return r.add(b)})}}),e.gradientFlag){var c=e;if(r.hatchObjectType=u.AcDbHatchObjectType.GradientObject,r.gradientName=c.gradientName,r.gradientAngle=(i=c.gradientRotation)!==null&&i!==void 0?i:0,r.gradientShift=(n=c.gradientDefinition)!==null&&n!==void 0?n:0,r.gradientOneColorMode=c.gradientColorFlag==1,r.shadeTintValue=(s=c.colorTint)!==null&&s!==void 0?s:0,c.gradientColors){var l=c.gradientColors.length;l>1?(r.gradientStartColor=c.gradientColors[0].rgb,r.gradientEndColor=c.gradientColors[1].rgb):l>0&&(r.gradientStartColor=c.gradientColors[0].rgb)}}return r},a.prototype.convertTable=function(e){var t=new u.AcDbTable(e.name,e.rowCount,e.columnCount);return t.tableStyleId=e.tableStyleId,t.owningBlockRecordId=e.blockRecordHandle,e.directionVector&&(t.horizontalDirection=new u.AcGeVector3d(e.directionVector)),t.attachmentPoint=e.attachmentPoint,t.position.copy(e.startPoint),t.tableValueFlag=e.tableValue,t.tableOverrideFlag=e.overrideFlag,t.borderColorOverrideFlag=e.borderColorOverrideFlag,t.borderLineweightOverrideFlag=e.borderLineWeightOverrideFlag,t.borderVisibilityOverrideFlag=e.borderVisibilityOverrideFlag,e.columnWidthArr.forEach(function(i,n){return t.setColumnWidth(n,i)}),e.rowHeightArr.forEach(function(i,n){return t.setRowHeight(n,i)}),e.cells.forEach(function(i,n){t.setCell(n,i)}),t},a.prototype.convertText=function(e){var t,i,n,s=new u.AcDbText;s.textString=e.text,s.styleName=e.styleName,s.height=e.textHeight,s.position.copy(e.startPoint);var r=!e.endPoint||e.endPoint.x===0&&e.endPoint.y===0&&((t=e.endPoint.z)!==null&&t!==void 0?t:0)===0;return e.endPoint&&!r?s.alignmentPoint.copy(e.endPoint):s.alignmentPoint.copy(e.startPoint),s.rotation=e.rotation,s.oblique=(i=e.obliqueAngle)!==null&&i!==void 0?i:0,s.thickness=e.thickness,s.horizontalMode=e.halign,s.verticalMode=e.valign,s.widthFactor=(n=e.xScale)!==null&&n!==void 0?n:1,s},a.prototype.convertMText=function(e){var t=new u.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 u.AcGeVector3d(e.direction)),t.drawingDirection=e.drawingDirection,t},a.prototype.convertLeader=function(e){var t=new u.AcDbLeader;return e.vertices.forEach(function(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},a.prototype.convertMLine=function(e){var t,i,n,s=new u.AcDbMLine;return s.styleName=e.mlineStyle||"STANDARD",s.scale=e.scale,s.flags=e.flags,s.justification=e.justification,s.startPosition=e.startPoint,s.normal=(t=e.extrusionDirection)!==null&&t!==void 0?t:u.AcGeVector3d.Z_AXIS,s.styleCount=(i=e.numberOfLines)!==null&&i!==void 0?i:0,s.segments=((n=e.vertices)!==null&&n!==void 0?n:[]).map(function(r){var o;return{position:r.vertex,direction:r.vertexDirection,miterDirection:r.miterDirection,elements:((o=r.lines)!==null&&o!==void 0?o:[]).map(function(c){var l,h;return{parameterCount:c.numberOfSegmentParams,parameters:(l=c.segmentParams)!==null&&l!==void 0?l:[],fillCount:c.numberOfAreaFillParams,fillParameters:(h=c.areaFillParams)!==null&&h!==void 0?h:[]}})}}),s},a.prototype.convertMLeader=function(e){var t,i,n,s,r,o,c,l,h,d,g,m,y,w,C=new u.AcDbMLeader,b=e;C.leaderLineType=(t=this.readNumber(b,["multileaderType","leaderLineType","leaderType"]))!==null&&t!==void 0?t:u.AcDbMLeaderLineType.StraightLeader;var x=(i=this.readNumber(b,["contentType"]))!==null&&i!==void 0?i:e.textContent?u.AcDbMLeaderContentType.MTextContent:e.blockContent?u.AcDbMLeaderContentType.BlockContent:u.AcDbMLeaderContentType.NoneContent;C.contentType=x,C.doglegEnabled=(n=this.readBoolean(b,["doglegEnabled","enableDogleg"]))!==null&&n!==void 0?n:!1,C.doglegLength=(s=this.readNumber(b,["doglegLength"]))!==null&&s!==void 0?s:0,e.landingPoint&&(C.landingPoint=e.landingPoint),e.doglegVector&&(C.doglegVector=e.doglegVector);var A=this.readString(b,["mleaderStyleId","mLeaderStyleId","mleaderStyleHandle","styleHandle","styleName"]);A&&(C.mleaderStyleId=A);var _=this.readPoint(b,["normal","extrusionDirection"]);_&&(C.normal=_);var L=e.textContent,T=(r=this.readString(L??{},["styleName","textStyleName"]))!==null&&r!==void 0?r:this.readString(b,["textStyleName","textStyle","styleName"]);T&&(C.textStyleName=T),C.textHeight=(c=(o=this.readNumber(L??{},["textHeight","height"]))!==null&&o!==void 0?o:this.readNumber(b,["textHeight","mtextHeight","textContentHeight"]))!==null&&c!==void 0?c:C.textHeight,C.textWidth=(h=(l=this.readNumber(L??{},["textWidth","width"]))!==null&&l!==void 0?l:this.readNumber(b,["textWidth","mtextWidth","textContentWidth"]))!==null&&h!==void 0?h:C.textWidth;var O=(d=this.readNumber(L??{},["textRotation","rotation"]))!==null&&d!==void 0?d:this.readNumber(b,["textRotation","mtextRotation","textContentRotation"]);O!=null&&(C.textRotation=O);var k=this.readPoint(b,["textDirection","mtextDirection","textDirectionVector"]);k&&(C.textDirection=k);var E=this.readNumber(b,["textAttachmentPoint","attachmentPoint"]);E!=null&&(C.textAttachmentPoint=E);var M=this.readNumber(b,["textDrawingDirection","drawingDirection"]);if(M!=null&&(C.textDrawingDirection=M),((g=e.textContent)===null||g===void 0?void 0:g.text)!=null&&e.textContent.anchorPoint)C.mtextContent={text:e.textContent.text,anchorPoint:e.textContent.anchorPoint};else{var F=this.readString(b,["text","contents","mtext"]),z=this.readPoint(b,["textLocation","textPosition","textAnchorPoint"]);F!=null&&z&&(C.mtextContent={text:F,anchorPoint:z})}if(!((m=e.blockContent)===null||m===void 0)&&m.blockHandle&&e.blockContent.position)C.blockContent={blockHandle:e.blockContent.blockHandle,position:e.blockContent.position};else{var U=this.readString(b,["blockHandle","blockContentHandle","blockId"]),V=this.readPoint(b,["blockPosition","blockContentPosition"]);U&&V&&(C.blockContent={blockHandle:U,position:V})}return(y=e.leaders)===null||y===void 0||y.forEach(function(K){var G,W,ee,_e,wt=C.addLeader({landingPoint:(G=K.landingPoint)!==null&&G!==void 0?G:e.landingPoint,doglegVector:(W=K.doglegVector)!==null&&W!==void 0?W:e.doglegVector,doglegLength:(ee=K.doglegLength)!==null&&ee!==void 0?ee:e.doglegLength});(_e=K.leaderLines)===null||_e===void 0||_e.forEach(function(Qe){var Xt,qt,nn=C.addLeaderLine(wt,(Xt=Qe.vertices)!==null&&Xt!==void 0?Xt:[]);(qt=Qe.breaks)===null||qt===void 0||qt.forEach(function(Zt){C.addBreak(wt,nn,Zt.start,Zt.end)})})}),C.numberOfLeaders===0&&((w=this.readLeaderLineArray(b))===null||w===void 0||w.forEach(function(K){var G=C.addLeader({landingPoint:e.landingPoint,doglegVector:e.doglegVector,doglegLength:e.doglegLength});C.addLeaderLine(G,K)})),C},a.prototype.convertDimension=function(e){if(e.subclassMarker=="AcDbAlignedDimension"){var t=e,i=new u.AcDbAlignedDimension(t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return t.insertionPoint&&(i.dimBlockPosition={x:t.insertionPoint.x,y:t.insertionPoint.y,z:0}),i.rotation=t.rotationAngle,this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbRotatedDimension"){var t=e,i=new u.AcDbRotatedDimension(t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return t.insertionPoint&&(i.dimBlockPosition={x:t.insertionPoint.x,y:t.insertionPoint.y,z:0}),i.rotation=t.rotationAngle,this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDb3PointAngularDimension"){var t=e,i=new u.AcDb3PointAngularDimension(t.centerPoint,t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbOrdinateDimension"){var t=e,i=new u.AcDbOrdinateDimension(t.subDefinitionPoint1,t.subDefinitionPoint2);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbRadialDimension"){var t=e,i=new u.AcDbRadialDimension(t.definitionPoint,t.centerPoint,t.leaderLength);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbDiametricDimension"){var t=e,i=new u.AcDbDiametricDimension(t.definitionPoint,t.centerPoint,t.leaderLength);return this.processDimensionCommonAttrs(e,i),i}return null},a.prototype.processImage=function(e,t){t.position.copy(e.position),t.brightness=e.brightness,t.contrast=e.contrast,t.fade=e.fade,t.imageSize.copy(e.imageSize),t.imageDefId=e.imageDefHandle,t.isClipped=e.clipping>0,t.isShownClipped=(e.flags|4)>0,t.isImageShown=(e.flags|3)>0,t.isImageTransparent=(e.flags|8)>0,e.clippingBoundaryPath.forEach(function(i){t.clipBoundary.push(new u.AcGePoint2d(i))}),t.clipBoundaryType=e.clippingBoundaryType,t.width=Math.sqrt(Math.pow(e.uPixel.x,2)+Math.pow(e.uPixel.y,2)+Math.pow(e.uPixel.z,2))*e.imageSize.x,t.height=Math.sqrt(Math.pow(e.vPixel.x,2)+Math.pow(e.vPixel.y,2)+Math.pow(e.vPixel.z,2))*e.imageSize.y,t.rotation=Math.atan2(e.uPixel.y,e.uPixel.x)},a.prototype.convertImage=function(e){var t=new u.AcDbRasterImage;return this.processImage(e,t),t},a.prototype.convertWipeout=function(e){var t=new u.AcDbWipeout;return this.processImage(e,t),t},a.prototype.convertViewport=function(e){var t=new u.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},a.prototype.convertRay=function(e){var t=new u.AcDbRay;return t.basePoint.copy(e.firstPoint),t.unitDir.copy(e.unitDirection),t},a.prototype.convertXline=function(e){var t=new u.AcDbXline;return t.basePoint.copy(e.firstPoint),t.unitDir.copy(e.unitDirection),t},a.prototype.convertAttributeCommon=function(e,t){var i,n,s,r,o=e.text;t.textString=o.text,t.styleName=o.styleName,t.height=o.textHeight,t.position.copy(o.startPoint);var c=(i=e.alignmentPoint)!==null&&i!==void 0?i:o.endPoint,l=!c||c.x===0&&c.y===0&&((n=c.z)!==null&&n!==void 0?n:0)===0;c&&!l?t.alignmentPoint.copy(c):t.alignmentPoint.copy(o.startPoint),t.rotation=o.rotation,t.oblique=(s=o.obliqueAngle)!==null&&s!==void 0?s:0,t.thickness=o.thickness,t.horizontalMode=o.halign,t.verticalMode=o.valign,t.widthFactor=(r=o.xScale)!==null&&r!==void 0?r:1,t.tag=e.tag,t.fieldLength=e.fieldLength,t.isInvisible=(e.flags&u.AcDbAttributeFlags.Invisible)!==0,t.isConst=(e.flags&u.AcDbAttributeFlags.Const)!==0,t.isVerifiable=(e.flags&u.AcDbAttributeFlags.Verifiable)!==0,t.isPreset=(e.flags&u.AcDbAttributeFlags.Preset)!==0,t.lockPositionInBlock=e.lockPositionFlag,t.isReallyLocked=e.isReallyLocked,t.isMTextAttribute=(e.mtextFlag&u.AcDbAttributeMTextFlag.MultiLine)!==0,t.isConstMTextAttribute=(e.mtextFlag&u.AcDbAttributeMTextFlag.ConstMultiLine)!==0},a.prototype.convertAttribute=function(e){var t=new u.AcDbAttribute;return this.convertAttributeCommon(e,t),t},a.prototype.convertAttributeDefinition=function(e){var t=new u.AcDbAttributeDefinition;return this.convertAttributeCommon(e,t),t.prompt=e.prompt,t},a.prototype.convertBlockReference=function(e){var t=this,i=new u.AcDbBlockReference(e.name);return e.insertionPoint&&i.position.copy(e.insertionPoint),i.scaleFactors.x=e.xScale,i.scaleFactors.y=e.yScale,i.scaleFactors.z=e.zScale,i.rotation=e.rotation,i.normal.copy(e.extrusionDirection),e.handle!=null&&(i.objectId=e.handle),e.attribs&&e.attribs.forEach(function(n){var s=t.convert(n);s instanceof u.AcDbAttribute&&i.appendAttributes(s)}),i},a.prototype.processDimensionCommonAttrs=function(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},a.prototype.processCommonAttrs=function(e,t){if(t.layer=e.layer||"0",t.objectId=e.handle,e.ownerBlockRecordSoftId!=null&&(t.ownerId=e.ownerBlockRecordSoftId),e.lineType!=null&&(t.lineType=e.lineType),e.lineweight!=null&&(t.lineWeight=e.lineweight),e.lineTypeScale!=null&&(t.linetypeScale=e.lineTypeScale),e.color!=null||e.colorIndex!=null||e.colorName){var i=new u.AcCmColor;e.color!=null&&i.setRGBValue(e.color),e.colorIndex!=null&&(e.color==null||e.colorIndex===7)&&(i.colorIndex=e.colorIndex),e.colorName&&(i.colorName=e.colorName),t.color=i}if(e.isVisible!=null&&(t.visibility=e.isVisible),e.transparency!=null){var n=new u.AcCmTransparency;n.method=e.transparencyType,(n.isByBlock||n.isByBlock)&&(n.alpha=e.transparency),t.transparency=n}},a.prototype.readNumber=function(e,t){var i,n;try{for(var s=yi(t),r=s.next();!r.done;r=s.next()){var o=r.value,c=e[o];if(typeof c=="number"&&Number.isFinite(c))return c}}catch(l){i={error:l}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}},a.prototype.readString=function(e,t){var i,n;try{for(var s=yi(t),r=s.next();!r.done;r=s.next()){var o=r.value,c=e[o];if(typeof c=="string")return c}}catch(l){i={error:l}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}},a.prototype.readBoolean=function(e,t){var i,n;try{for(var s=yi(t),r=s.next();!r.done;r=s.next()){var o=r.value,c=e[o];if(typeof c=="boolean")return c;if(typeof c=="number")return c!==0}}catch(l){i={error:l}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}},a.prototype.readPoint=function(e,t){var i,n,s;try{for(var r=yi(t),o=r.next();!o.done;o=r.next()){var c=o.value,l=e[c];if(this.isPointLike(l))return l;if(Array.isArray(l)&&typeof l[0]=="number"&&typeof l[1]=="number")return{x:l[0],y:l[1],z:(s=l[2])!==null&&s!==void 0?s:0}}}catch(h){i={error:h}}finally{try{o&&!o.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}},a.prototype.readLeaderLineArray=function(e){var t=this,i=e.leaderLines;if(Array.isArray(i))return i.map(function(r){if(!(!r||typeof r!="object")){var o=r.vertices;return Array.isArray(o)?o.filter(function(c){return t.isPointLike(c)}):void 0}}).filter(function(r){return!!r&&r.length>0});var n=e.vertices;if(Array.isArray(n)){var s=n.filter(function(r){return t.isPointLike(r)});return s.length>0?[s]:void 0}},a.prototype.isPointLike=function(e){return!!e&&typeof e=="object"&&typeof e.x=="number"&&typeof e.y=="number"},a}(),xc=function(){var a=function(e,t){return a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},a(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");a(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),fi=function(a,e,t,i){function n(s){return s instanceof t?s:new t(function(r){r(s)})}return new(t||(t=Promise))(function(s,r){function o(h){try{l(i.next(h))}catch(d){r(d)}}function c(h){try{l(i.throw(h))}catch(d){r(d)}}function l(h){h.done?s(h.value):n(h.value).then(o,c)}l((i=i.apply(a,e||[])).next())})},wi=function(a,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,r;return r={next:o(0),throw:o(1),return:o(2)},typeof Symbol=="function"&&(r[Symbol.iterator]=function(){return this}),r;function o(l){return function(h){return c([l,h])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r&&(r=0,l[0]&&(t=0)),t;)try{if(i=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,n=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(a,t)}catch(h){l=[6,h],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Gs=function(a,e){var t=typeof Symbol=="function"&&a[Symbol.iterator];if(!t)return a;var i=t.call(a),n,s=[],r;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(o){r={error:o}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(r)throw r.error}}return s},$s=function(a,e,t){if(t||arguments.length===2)for(var i=0,n=e.length,s;i<n;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return a.concat(s||Array.prototype.slice.call(e))},Ks=function(a){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&a[e],i=0;if(t)return t.call(a);if(a&&typeof a.length=="number")return{next:function(){return a&&i>=a.length&&(a=void 0),{value:a&&a[i++],done:!a}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},vc="*MODEL_SPACE",Sc=function(a){xc(e,a);function e(t){t===void 0&&(t={});var i=a.call(this,t)||this;return t.useWorker=!0,t.parserWorkerUrl||(t.parserWorkerUrl="/assets/libredwg-parser-worker.js"),i}return e.prototype.parse=function(t,i){return fi(this,void 0,void 0,function(){var n,s,r,o;return wi(this,function(c){switch(c.label){case 0:return n=this.config,s=this.getParserWorkerTimeout(t,i),n.useWorker&&n.parserWorkerUrl?(r=u.createWorkerApi({workerUrl:n.parserWorkerUrl,timeout:s,maxConcurrentWorkers:1}),[4,r.execute(t)]):[3,2];case 1:if(o=c.sent(),r.destroy(),o.success)return[2,o.data];throw new Error("Failed to parse drawing due to error: '".concat(o.error,"'"));case 2:throw new Error("dwg converter can run in web worker only!");case 3:return[2]}})})},e.prototype.getFonts=function(t){var i=new Map;t.tables.BLOCK_RECORD.entries.forEach(function(o){i.set(o.name,o)});var n=new Map,s=function(o){if(o){var c=o.lastIndexOf(".");return c>=0?o.substring(0,c).toLowerCase():o.toLowerCase()}};t.tables.STYLE.entries.forEach(function(o){var c=[],l=s(o.font);l&&c.push(l),l=s(o.bigFont),l&&c.push(l),n.set(o.name,c)});var r=new Set;return this.getFontsInBlock(t.entities,i,n,r),Array.from(r)},e.prototype.getFontsInBlock=function(t,i,n,s){var r=this,o=/\\f(.*?)\|/g;t.forEach(function(c){if(c.type=="MTEXT"){var l=c;$s([],Gs(l.text.matchAll(o)),!1).forEach(function(b){s.add(b[1].toLowerCase())});var h=n.get(l.styleName);h==null||h.forEach(function(b){return s.add(b)})}else if(c.type=="TEXT"){var d=c,h=n.get(d.styleName);h==null||h.forEach(function(x){return s.add(x)})}else if(c.type=="MULTILEADER"||c.type=="MLEADER"){var g=c,m=g.textContent,d=typeof(m==null?void 0:m.text)=="string"?m.text:"";$s([],Gs(d.matchAll(o)),!1).forEach(function(A){s.add(A[1].toLowerCase())});var y=typeof(m==null?void 0:m.styleName)=="string"?m.styleName:typeof g.textStyleName=="string"?g.textStyleName:typeof g.styleName=="string"?g.styleName:void 0,h=y?n.get(y):void 0;h==null||h.forEach(function(A){return s.add(A)})}else if(c.type=="INSERT"){var w=c,C=i.get(w.name);C&&r.getFontsInBlock(C.entities,i,n,s)}})},e.prototype.processLineTypes=function(t,i){var n=this,s=t.tables.LTYPE.entries;s.forEach(function(r){var o={name:r.name,description:r.description,standardFlag:r.standardFlag,totalPatternLength:r.totalPatternLength,pattern:r.pattern},c=new u.AcDbLinetypeTableRecord(o);n.processCommonTableEntryAttrs(r,c),c.name=r.name,i.tables.linetypeTable.add(c)})},e.prototype.processTextStyles=function(t,i){var n=this,s=t.tables.STYLE.entries;s.forEach(function(r){var o=new u.AcDbTextStyleTableRecord(r);n.processCommonTableEntryAttrs(r,o),i.tables.textStyleTable.add(o)}),i.ensureTextStyleDefaults()},e.prototype.processDimStyles=function(t,i){var n=this,s=t.tables.DIMSTYLE.entries;s.forEach(function(r){var o={name:r.name,ownerId:r.ownerHandle,dimpost:r.DIMPOST||"",dimapost:r.DIMAPOST||"",dimscale:r.DIMSCALE,dimasz:r.DIMASZ,dimexo:r.DIMEXO,dimdli:r.DIMDLI,dimexe:r.DIMEXE,dimrnd:r.DIMRND,dimdle:r.DIMDLE,dimtp:r.DIMTP,dimtm:r.DIMTM,dimtxt:r.DIMTXT,dimcen:r.DIMCEN,dimtsz:r.DIMTSZ,dimaltf:r.DIMALTF,dimlfac:r.DIMLFAC,dimtvp:r.DIMTVP,dimtfac:r.DIMTFAC,dimgap:r.DIMGAP,dimaltrnd:r.DIMALTRND,dimtol:r.DIMTOL==null||r.DIMTOL==0?0:1,dimlim:r.DIMLIM==null||r.DIMLIM==0?0:1,dimtih:r.DIMTIH==null||r.DIMTIH==0?0:1,dimtoh:r.DIMTOH==null||r.DIMTOH==0?0:1,dimse1:r.DIMSE1==null||r.DIMSE1==0?0:1,dimse2:r.DIMSE2==null||r.DIMSE2==0?0:1,dimtad:r.DIMTAD,dimzin:r.DIMZIN,dimazin:r.DIMAZIN,dimalt:r.DIMALT,dimaltd:r.DIMALTD,dimtofl:r.DIMTOFL,dimsah:r.DIMSAH,dimtix:r.DIMTIX,dimsoxd:r.DIMSOXD,dimclrd:r.DIMCLRD,dimclre:r.DIMCLRE,dimclrt:r.DIMCLRT,dimadec:r.DIMADEC||0,dimunit:r.DIMUNIT||2,dimdec:r.DIMDEC,dimtdec:r.DIMTDEC,dimaltu:r.DIMALTU,dimalttd:r.DIMALTTD,dimaunit:r.DIMAUNIT,dimfrac:r.DIMFRAC,dimlunit:r.DIMLUNIT,dimdsep:r.DIMDSEP||".",dimtmove:r.DIMTMOVE||0,dimjust:r.DIMJUST,dimsd1:r.DIMSD1,dimsd2:r.DIMSD2,dimtolj:r.DIMTOLJ,dimtzin:r.DIMTZIN,dimaltz:r.DIMALTZ,dimalttz:r.DIMALTTZ,dimfit:r.DIMFIT||0,dimupt:r.DIMUPT,dimatfit:r.DIMATFIT,dimtxsty:u.DEFAULT_TEXT_STYLE,dimldrblk:"",dimblk:r.DIMBLK||"",dimblk1:r.DIMBLK1||"",dimblk2:r.DIMBLK2||"",dimlwd:r.DIMLWD,dimlwe:r.DIMLWE},c=new u.AcDbDimStyleTableRecord(o);n.processCommonTableEntryAttrs(r,c),i.tables.dimStyleTable.add(c)})},e.prototype.processLayers=function(t,i){var n=this,s=t.tables.LAYER.entries;s.forEach(function(r){var o=new u.AcCmColor;o.colorIndex=r.colorIndex;var c=new u.AcDbLayerTableRecord({name:r.name,standardFlags:r.standardFlag,linetype:r.lineType,lineWeight:r.lineweight,isOff:r.off,color:o,isPlottable:r.plotFlag!=0});n.processCommonTableEntryAttrs(r,c),i.tables.layerTable.add(c)})},e.prototype.processViewports=function(t,i){var n=this,s=t.tables.VPORT.entries;s.forEach(function(r){var o,c,l,h,d,g,m=new u.AcDbViewportTableRecord;n.processCommonTableEntryAttrs(r,m),r.circleSides&&(m.circleSides=r.circleSides),m.standardFlag=r.standardFlag,m.center.copy((o=r.center)!==null&&o!==void 0?o:u.VPORT_FALLBACK_CENTER_2D),m.lowerLeftCorner.copy((c=r.lowerLeftCorner)!==null&&c!==void 0?c:u.VPORT_FALLBACK_LLC),m.upperRightCorner.copy((l=r.upperRightCorner)!==null&&l!==void 0?l:u.VPORT_FALLBACK_URC),r.snapBasePoint&&m.snapBase.copy(r.snapBasePoint),r.snapRotationAngle&&(m.snapAngle=r.snapRotationAngle),r.snapSpacing&&m.snapIncrements.copy(r.snapSpacing),r.majorGridLines&&(m.gridMajor=r.majorGridLines),r.gridSpacing&&m.gridIncrements.copy(r.gridSpacing),r.backgroundObjectId&&(m.backgroundObjectId=r.backgroundObjectId),m.gsView.center.copy((h=r.center)!==null&&h!==void 0?h:u.VPORT_FALLBACK_CENTER_2D),m.gsView.viewDirectionFromTarget.copy((d=r.viewDirectionFromTarget)!==null&&d!==void 0?d:u.VPORT_FALLBACK_VIEW_DIR),m.gsView.viewTarget.copy((g=r.viewTarget)!==null&&g!==void 0?g:u.VPORT_FALLBACK_VIEW_TARGET),r.lensLength&&(m.gsView.lensLength=r.lensLength),r.frontClippingPlane&&(m.gsView.frontClippingPlane=r.frontClippingPlane),r.backClippingPlane&&(m.gsView.backClippingPlane=r.backClippingPlane),r.viewHeight&&(m.gsView.viewHeight=r.viewHeight),r.viewTwistAngle&&(m.gsView.viewTwistAngle=r.viewTwistAngle),r.frozenLayers&&(m.gsView.frozenLayers=r.frozenLayers),r.styleSheet&&(m.gsView.styleSheet=r.styleSheet),r.renderMode&&(m.gsView.renderMode=r.renderMode),r.viewMode&&(m.gsView.viewMode=r.viewMode),r.ucsIconSetting&&(m.gsView.ucsIconSetting=r.ucsIconSetting),r.ucsOrigin&&m.gsView.ucsOrigin.copy(r.ucsOrigin),r.ucsXAxis&&m.gsView.ucsXAxis.copy(r.ucsXAxis),r.ucsYAxis&&m.gsView.ucsYAxis.copy(r.ucsYAxis),r.orthographicType&&(m.gsView.orthographicType=r.orthographicType),r.shadePlotSetting&&(m.gsView.shadePlotSetting=r.shadePlotSetting),r.shadePlotObjectId&&(m.gsView.shadePlotObjectId=r.shadePlotObjectId),r.visualStyleObjectId&&(m.gsView.visualStyleObjectId=r.visualStyleObjectId),r.isDefaultLightingOn&&(m.gsView.isDefaultLightingOn=r.isDefaultLightingOn),r.defaultLightingType&&(m.gsView.defaultLightingType=r.defaultLightingType),r.brightness&&(m.gsView.brightness=r.brightness),r.contrast&&(m.gsView.contrast=r.contrast),r.ambientColor&&(m.gsView.ambientColor=r.ambientColor),i.tables.viewportTable.add(m)})},e.prototype.processBlockTables=function(t,i){var n=this,s=t.tables.BLOCK_RECORD.entries;s.forEach(function(r){var o=i.tables.blockTable.getAt(r.name);o||(o=new u.AcDbBlockTableRecord,o.objectId=r.handle,o.name=r.name,o.ownerId=r.ownerHandle,o.origin.copy(r.basePoint),o.layoutId=r.layout,o.blockInsertUnits=r.insertionUnits,o.explodability=r.explodability,o.blockScaling=r.scalability,r.bmpPreview&&(o.bmpPreview=r.bmpPreview),i.tables.blockTable.add(o)),!o.isModelSapce&&r.entities&&r.entities.length>0&&n.processEntitiesInBlock(r.entities,o)})},e.prototype.processBlocks=function(t,i){},e.prototype.processEntitiesInBlock=function(t,i){return fi(this,void 0,void 0,function(){var n,s,r,o,c,l;return wi(this,function(h){for(n=new Vs,s=t.length,r=[],o=0;o<s;o++)c=t[o],l=n.convert(c),l&&r.push(l);return i.appendEntity(r),[2]})})},e.prototype.processEntities=function(t,i,n,s,r){return fi(this,void 0,void 0,function(){var o,c,l,h,d,g=this;return wi(this,function(m){switch(m.label){case 0:return o=new Vs,c=[],t.tables.BLOCK_RECORD.entries.forEach(function(y){g.isModelSpace(y.name)&&(c=y.entities)}),l=c.length,h=new u.AcDbBatchProcessing(l,100-s.value,n),this.config.convertByEntityType&&(c=this.groupAndFlattenByType(c)),d=i.tables.blockTable.modelSpace,[4,h.processChunk(function(y,w){return fi(g,void 0,void 0,function(){var C,b,x,A,_;return wi(this,function(L){switch(L.label){case 0:for(C=[],b=y;b<w;b++)x=c[b],A=o.convert(x),A&&C.push(A);return d.appendEntity(C),r?(_=s.value+w/l*(100-s.value),_>100&&(_=100),[4,r(_,"ENTITY","IN-PROGRESS")]):[3,2];case 1:L.sent(),L.label=2;case 2:return[2]}})})})];case 1:return m.sent(),[2]}})})},e.prototype.processHeader=function(t,i){var n,s,r,o,c,l,h,d,g,m,y=t.header;y.CECOLOR&&(y.CECOLOR.index>=0&&y.CECOLOR.index<=256?i.cecolor.colorIndex=y.CECOLOR.index:i.cecolor.setRGBValue(y.CECOLOR.rgb)),i.angbase=(n=y.ANGBASE)!==null&&n!==void 0?n:0,i.angdir=(s=y.ANGDIR)!==null&&s!==void 0?s:0,i.aunits=(r=y.AUNITS)!==null&&r!==void 0?r:0,y.AUPREC!=null&&(i.auprec=y.AUPREC),y.LUNITS!=null&&(i.lunits=y.LUNITS),y.LUPREC!=null&&(i.luprec=y.LUPREC),y.UNITMODE!=null&&(i.unitmode=y.UNITMODE),y.MEASUREMENT!=null&&(i.measurement=y.MEASUREMENT),i.celtype=(o=y.CELTYPE)!==null&&o!==void 0?o:u.ByLayer,i.celtscale=(c=y.CELTSCALE)!==null&&c!==void 0?c:1,i.ltscale=(l=y.LTSCALE)!==null&&l!==void 0?l:1,y.EXTMAX&&(i.extmax=y.EXTMAX),y.EXTMIN&&(i.extmin=y.EXTMIN),i.insunits=(h=y.INSUNITS)!==null&&h!==void 0?h:1,i.pdmode=(d=y.PDMODE)!==null&&d!==void 0?d:0,i.pdsize=(g=y.PDSIZE)!==null&&g!==void 0?g:0,i.textstyle=(m=y.TEXTSTYLE)!==null&&m!==void 0?m:u.DEFAULT_TEXT_STYLE},e.prototype.processCommonTableEntryAttrs=function(t,i){i.name=t.name,i.objectId=t.handle,t.ownerHandle!=null&&(i.ownerId=t.ownerHandle)},e.prototype.processObjects=function(t,i){this.processLayouts(t,i),this.processImageDefs(t,i)},e.prototype.processLayouts=function(t,i){var n=this,s=i.objects.layout,r=t.objects.LAYOUT;r.forEach(function(o){var c,l,h=new u.AcDbLayout;h.layoutName=o.layoutName,h.tabOrder=o.tabOrder;var d=i.tables.blockTable.newIterator();h.objectId=o.handle;try{for(var g=Ks(d),m=g.next();!m.done;m=g.next()){var y=m.value;if(y.layoutId===h.objectId){h.blockTableRecordId=y.objectId;break}}}catch(w){c={error:w}}finally{try{m&&!m.done&&(l=g.return)&&l.call(g)}finally{if(c)throw c.error}}h.blockTableRecordId||o.layoutName==="Model"&&(h.blockTableRecordId=i.tables.blockTable.modelSpace.objectId),h.limits.min.copy(o.minLimit),h.limits.max.copy(o.maxLimit),h.extents.min.copy(o.minExtent),h.extents.max.copy(o.maxExtent),o.viewportId&&h.viewportArray.push(o.viewportId),n.processCommonObjectAttrs(o,h),s.setAt(h.layoutName,h)})},e.prototype.processImageDefs=function(t,i){var n=this,s=i.objects.imageDefinition,r=t.objects.IMAGEDEF;r.forEach(function(o){var c=new u.AcDbRasterImageDef;c.sourceFileName=o.fileName,n.processCommonObjectAttrs(o,c),s.setAt(c.objectId,c)})},e.prototype.processCommonObjectAttrs=function(t,i){i.objectId=t.handle,t.ownerHandle!=null&&(i.ownerId=t.ownerHandle)},e.prototype.groupAndFlattenByType=function(t){var i,n,s={},r=[];try{for(var o=Ks(t),c=o.next();!c.done;c=o.next()){var l=c.value;s[l.type]||(s[l.type]=[],r.push(l.type)),s[l.type].push(l)}}catch(h){i={error:h}}finally{try{c&&!c.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return r.flatMap(function(h){return s[h]})},e.prototype.isModelSpace=function(t){return t&&t.toUpperCase()==vc},e}(u.AcDbDatabaseConverter),Q;(function(a){a[a.BeforeStart=0]="BeforeStart",a[a.EqualStart=1]="EqualStart",a[a.BetweenStartAndEnd=2]="BetweenStartAndEnd",a[a.EqualEnd=3]="EqualEnd",a[a.AfterEnd=4]="AfterEnd"})(Q||(Q={}));class Ac{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 Us extends Ac{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],c=e[0],l=e[1];return(r-n)*(l-s)-(o-s)*(c-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],c=r*s+n*o;if(c<this.epsilon)return!1;const l=s*s+o*o;return!(c-l>-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],c=n[1]-i[1],l=s*c-r*o;if(Math.abs(l)<this.epsilon)return null;const h=e[0]-i[0],d=e[1]-i[1],g=(o*d-c*h)/l,m=(s*d-r*h)/l,y=C=>C<=-this.epsilon?Q.BeforeStart:C<this.epsilon?Q.EqualStart:C-1<=-this.epsilon?Q.BetweenStartAndEnd:C-1<this.epsilon?Q.EqualEnd:Q.AfterEnd,w=[e[0]+g*s,e[1]+g*r];return{alongA:y(g),alongB:y(m),p:w}}}class Ws{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=(c,l)=>t(l)-t(c);let r=0,o=this.nodes.length;for(;r<o;){const c=r+o>>1;s(this.nodes[c],e)>0?o=c:r=c+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:c=>(this.nodes.splice(r,0,c),c)}}}class tt{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 Hs{constructor(e,t,i,n){this.status=null,this.isStart=e,this.p=t,this.seg=i,this.primary=n}}class Ys{constructor(e,t,i=null){this.events=new Ws,this.status=new Ws,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 tt(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 tt(e,t,null,this.log):new tt(t,e,null,this.log)}addSegment(e,t){const i=new Hs(!0,e.start,e,t),n=new Hs(!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,c=s.start,l=s.end;(i=this.log)===null||i===void 0||i.checkIntersection(n,s);const h=this.geo.linesIntersect(r,o,c,l);if(h===null){if(!this.geo.pointsCollinear(r,o,c)||this.geo.pointsSame(r,l)||this.geo.pointsSame(o,c))return null;const d=this.geo.pointsSame(r,c),g=this.geo.pointsSame(o,l);if(d&&g)return t;const m=!d&&this.geo.pointBetween(r,c,l),y=!g&&this.geo.pointBetween(o,c,l);if(d)return y?this.divideEvent(t,o):this.divideEvent(e,l),t;m&&(g||(y?this.divideEvent(t,o):this.divideEvent(e,l)),this.divideEvent(t,r))}else h.alongA===Q.BetweenStartAndEnd&&(h.alongB===Q.EqualStart?this.divideEvent(e,c):h.alongB===Q.BetweenStartAndEnd?this.divideEvent(e,h.p):h.alongB===Q.EqualEnd&&this.divideEvent(e,l)),h.alongB===Q.BetweenStartAndEnd&&(h.alongA===Q.EqualStart?this.divideEvent(t,r):h.alongA===Q.BetweenStartAndEnd?this.divideEvent(t,h.p):h.alongA===Q.EqualEnd&&this.divideEvent(t,o));return null}calculate(e,t){var i,n,s,r,o,c,l,h;const d=[];for(;!this.events.isEmpty();){const g=this.events.getHead();if((i=this.log)===null||i===void 0||i.vert(g.p[0]),g.isStart){(n=this.log)===null||n===void 0||n.segmentNew(g.seg,g.primary);const m=this.statusFindSurrounding(g),y=m.before,w=m.after;(s=this.log)===null||s===void 0||s.tempStatus(g.seg,y?y.seg:!1,w?w.seg:!1);const b=(()=>{if(y){const x=this.checkIntersection(g,y);if(x)return x}return w?this.checkIntersection(g,w):null})();if(b){if(this.selfIntersection){let x;g.seg.myFill.below===null?x=!0:x=g.seg.myFill.above!==g.seg.myFill.below,x&&(b.seg.myFill.above=!b.seg.myFill.above)}else b.seg.otherFill=g.seg.myFill;(r=this.log)===null||r===void 0||r.segmentUpdate(b.seg),this.events.remove(g.other),this.events.remove(g)}if(this.events.getHead()!==g){(o=this.log)===null||o===void 0||o.rewind(g.seg);continue}if(this.selfIntersection){let x;g.seg.myFill.below===null?x=!0:x=g.seg.myFill.above!==g.seg.myFill.below,w?g.seg.myFill.below=w.seg.myFill.above:g.seg.myFill.below=e,x?g.seg.myFill.above=!g.seg.myFill.below:g.seg.myFill.above=g.seg.myFill.below}else if(g.seg.otherFill===null){let x;if(!w)x=g.primary?t:e;else if(g.primary===w.primary){if(w.seg.otherFill===null)throw new Error("otherFill is null");x=w.seg.otherFill.above}else x=w.seg.myFill.above;g.seg.otherFill={above:x,below:x}}(c=this.log)===null||c===void 0||c.status(g.seg,y?y.seg:!1,w?w.seg:!1),g.other.status=m.insert(g)}else{const m=g.status;if(m===null)throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large");const y=this.status.getIndex(m);if(y>0&&y<this.status.nodes.length-1){const w=this.status.nodes[y-1],C=this.status.nodes[y+1];this.checkIntersection(w,C)}if((l=this.log)===null||l===void 0||l.statusRemove(m.seg),this.status.remove(m),!g.primary){if(!g.seg.otherFill)throw new Error("otherFill is null");const w=g.seg.myFill;g.seg.myFill=g.seg.otherFill,g.seg.otherFill=w}d.push(g.seg)}this.events.removeHead()}return(h=this.log)===null||h===void 0||h.done(),d}}function Pt(a,e,t){const i=[];for(const n of a){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 tt(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 Lt{static union(e,t){return Pt(e,[0,2,1,0,2,2,0,0,1,0,1,0,0,0,0,0],t)}static intersect(e,t){return Pt(e,[0,0,0,0,0,2,0,2,0,0,1,1,0,2,1,0],t)}static difference(e,t){return Pt(e,[0,0,0,0,2,0,2,0,1,1,0,0,0,1,2,0],t)}static differenceRev(e,t){return Pt(e,[0,2,1,0,0,0,1,1,0,2,0,2,0,0,0,0],t)}static xor(e,t){return Pt(e,[0,2,1,0,2,0,0,1,1,0,0,2,0,1,2,0],t)}}function Cc(a,e,t){const i=[],n=[];for(const s of a){let d=function(b,x,A){return h&&(h.index=b,h.matches_head=x,h.matches_pt1=A),h===c?(h=l,!1):(h=null,!0)},g=function(b){t==null||t.chainReverse(b),i[b].reverse()},m=function(b,x){const A=i[b],_=i[x];let L=A[A.length-1];const T=A[A.length-2],O=_[0],k=_[1];e.pointsCollinear(T,L,O)&&(t==null||t.chainRemoveTail(b,L),A.pop(),L=T),e.pointsCollinear(L,O,k)&&(t==null||t.chainRemoveHead(x,O),_.shift()),t==null||t.chainJoin(b,x),i[b]=A.concat(_),i.splice(x,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 c={index:0,matches_head:!1,matches_pt1:!1},l={index:0,matches_head:!1,matches_pt1:!1};let h=c;for(let b=0;b<i.length;b++){const x=i[b],A=x[0],_=x[x.length-1];if(e.pointsSame(A,r)){if(d(b,!0,!0))break}else if(e.pointsSame(A,o)){if(d(b,!0,!1))break}else if(e.pointsSame(_,r)){if(d(b,!1,!0))break}else if(e.pointsSame(_,o)&&d(b,!1,!1))break}if(h===c){i.push([r,o]),t==null||t.chainNew(r,o);continue}if(h===l){t==null||t.chainMatch(c.index);const b=c.index,x=c.matches_pt1?o:r,A=c.matches_head,_=i[b];let L=A?_[0]:_[_.length-1];const T=A?_[1]:_[_.length-2],O=A?_[_.length-1]:_[0],k=A?_[_.length-2]:_[1];if(e.pointsCollinear(T,L,x)&&(A?(t==null||t.chainRemoveHead(c.index,x),_.shift()):(t==null||t.chainRemoveTail(c.index,x),_.pop()),L=T),e.pointsSame(O,x)){i.splice(b,1),e.pointsCollinear(k,O,L)&&(A?(t==null||t.chainRemoveTail(c.index,L),_.pop()):(t==null||t.chainRemoveHead(c.index,L),_.shift())),t==null||t.chainClose(c.index),n.push(_);continue}A?(t==null||t.chainAddHead(c.index,x),_.unshift(x)):(t==null||t.chainAddTail(c.index,x),_.push(x));continue}const y=c.index,w=l.index;t==null||t.chainConnect(y,w);const C=i[y].length<i[w].length;c.matches_head?l.matches_head?C?(g(y),m(y,w)):(g(w),m(w,y)):m(w,y):l.matches_head?m(y,w):C?(g(y),m(w,y)):(g(w),m(y,w))}return n}class _c{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 Xs{constructor(e){this.log=null,this.geo=e}buildLog(e){var t;return this.log=e?new _c:null,(t=this.log)===null||t===void 0?void 0:t.list}segments(e){const t=new Ys(!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 Ys(!1,this.geo,this.log);for(const n of e.segments)i.addSegment(new tt(n.start,n.end,n,this.log),!0);for(const n of t.segments)i.addSegment(new tt(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:Lt.union(e.combined,this.log),inverted:e.inverted1||e.inverted2}}selectIntersect(e){return{segments:Lt.intersect(e.combined,this.log),inverted:e.inverted1&&e.inverted2}}selectDifference(e){return{segments:Lt.difference(e.combined,this.log),inverted:e.inverted1&&!e.inverted2}}selectDifferenceRev(e){return{segments:Lt.differenceRev(e.combined,this.log),inverted:!e.inverted1&&e.inverted2}}selectXor(e){return{segments:Lt.xor(e.combined,this.log),inverted:e.inverted1!==e.inverted2}}polygon(e){return{regions:Cc(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 Xs(new Us);const ve=[.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],Se=[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],Pc=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(ve),indices:new Uint16Array(Se)}],[33,{position:new Float32Array(ve),indices:new Uint16Array(Se)}],[34,{position:new Float32Array([...ve,-1,0,0,1,0,0,0,-1,0,0,1,0]),indices:new Uint16Array([...Se,26,27,28,29])}],[35,{position:new Float32Array([...ve,-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([...Se,26,27,28,29])}],[36,{position:new Float32Array([...ve,0,0,0,0,.5,0]),indices:new Uint16Array([...Se,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([...ve,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0]),indices:new Uint16Array([...Se,26,27,27,28,28,29,29,26])}],[97,{position:new Float32Array([...ve,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0]),indices:new Uint16Array([...Se,26,27,27,28,28,29,29,30])}],[98,{position:new Float32Array([...ve,-.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([...Se,26,27,27,28,28,29,29,30,31,32,33,34])}],[99,{position:new Float32Array([...ve,-.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([...Se,26,27,27,28,28,29,29,26,30,31,32,33])}],[100,{position:new Float32Array([...ve,-.5,.5,0,.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,0,0,0,0,.5,0]),indices:new Uint16Array([...Se,26,27,27,28,28,29,29,30,31,32])}]]);class ze{constructor(){this._symbols=this.initialize()}static get instance(){return ze._instance||(ze._instance=new ze),ze._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)Tt.copy(t),i.point=new f.BufferGeometry().setFromPoints([Tt]);else if(e!=1){const n=this._symbols.get(e);if(n==null)throw new Error(`[AcTrPointSymbolCreator] Invalid point type value: '${e}'!`);Tt.copy(t),qs.identity().makeTranslation(Tt),i.line=n.clone().applyMatrix4(qs),(e==32||e==64||e==96)&&(i.point=new f.BufferGeometry().setFromPoints([Tt]))}return i}initialize(){const e=new Map;return Pc.forEach((t,i)=>{const n=new f.BufferGeometry;n.setAttribute("position",new f.BufferAttribute(t.position,3)),n.setIndex(new f.BufferAttribute(t.indices,1)),e.set(i,n)}),e}}const qs=new f.Matrix4,Tt=new f.Vector3,bi=new f.Vector3,xi=new f.Vector3;class It{static release(e){e.index=null,e.attributes={}}static toNonIndexed(e){if(!e.index)return e;const t=new f.BufferGeometry,i=e.index;for(const n in e.attributes)t.setAttribute(n,It.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 c=t.getX(o)*n;for(let l=0;l<n;l++)r[o*n+l]=e.array[c+l]}return new f.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 f.InterleavedBufferAttribute){const n=i.clone();e.attributes[t]=n}})}static createBufferGeometryByPoints(e){const t=new f.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 f.Float32BufferAttribute(i,3)),t.setIndex(new f.Uint16BufferAttribute(n,1)),t}static computeLineDistance(e){const t=e.isLineSegments===!0;let i=e.geometry;const n=e.matrixWorld;if(i.index&&(i=It.toNonIndexed(i)),i.index===null){const s=i.attributes.position;if(!s||s.count===0)return;const r=[];if(t)for(let o=0,c=s.count;o<c;o+=2)bi.fromBufferAttribute(s,o).applyMatrix4(n),xi.fromBufferAttribute(s,o+1).applyMatrix4(n),r[o]=o===0?0:r[o-1],r[o+1]=r[o]+bi.distanceTo(xi);else{r[0]=0;for(let o=1,c=s.count;o<c;o++)bi.fromBufferAttribute(s,o-1).applyMatrix4(n),xi.fromBufferAttribute(s,o).applyMatrix4(n),r[o]=r[o-1],r[o]+=bi.distanceTo(xi)}i.setAttribute("lineDistance",new f.Float32BufferAttribute(r,1)),e.geometry.dispose(),e.geometry=i}}static computeLineDistances(e){e.traverse(t=>{let i=t;i.isLine&&i.material instanceof f.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 c=Math.cos(i),l=Math.sin(i);for(let h=0;h<o.length;h+=r){const d=o[h],g=o[h+1],m=d*c-g*l,y=d*l+g*c;o[h]=m*n+t.x,o[h+1]=y*n+t.y}}else for(let c=0;c<o.length;c+=r)o[c]=o[c]*n+t.x,o[c+1]+=o[c+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),c=Math.sin(i.x),l=Math.cos(i.y),h=Math.sin(i.y),d=Math.cos(i.z),g=Math.sin(i.z);for(let m=0;m<r.length;m+=s){let y=r[m],w=r[m+1],C=r[m+2],b=w*o-C*c,x=w*c+C*o;w=b,C=x;let A=y*l+C*h;x=-y*h+C*l,y=A,C=x,A=y*d-w*g,b=y*g+w*d,y=A,w=b,r[m]=y+t.x,r[m+1]=w+t.y,r[m+2]=C+t.z}return n.needsUpdate=!0,e}}class yn{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=yn.getFileName(e);if(t){const i=t.lastIndexOf(".");return i===-1?t:t.substring(0,i)}return e}}class fn{static toAcCmColor(e){const t=new u.AcCmColor;return e?e.isRgb&&typeof e.rgbValue=="number"?(t.setRGBValue(e.rgbValue),t):(typeof e.aci=="number"&&(e.aci===256?t.setByLayer():e.aci===0?t.setByBlock():t.colorIndex=e.aci),t):t}static toMTextColor(e){const t=new B.MTextColor;if(!e)return t;if(e.isByLayer)return t.aci=256,t;if(e.isByBlock)return t.aci=0,t;if(e.isByACI&&typeof e.colorIndex=="number")return t.aci=e.colorIndex,t;const i=e.RGB;return typeof i=="number"&&(t.rgbValue=i),t}static resolveRgbColor(e){const{color:t,byBlockColor:i,byLayerColor:n}=e;if(t.isRgb&&typeof t.rgbValue=="number")return t.rgbValue;if(t.aci===0)return i;if(t.aci===256||t.aci==null)return n;const s=new u.AcCmColor;s.colorIndex=t.aci;const r=s.RGB;return typeof r=="number"?r:n}}class wn{static createDefaultTraits(){return{color:new u.AcCmColor,rgbColor:16777215,lineType:{type:"ByLayer",name:"Continuous",standardFlag:0,description:"Solid line",totalPatternLength:0},lineTypeScale:1,lineWeight:u.AcGiLineWeight.ByLayer,fillType:{solidFill:!0,patternAngle:0,definitionLines:[]},transparency:new u.AcCmTransparency,thickness:0,layer:"0",drawOrder:0}}static createTraitsForMText(e){const t=fn.toAcCmColor(e.color),i=fn.resolveRgbColor(e);return{color:t,rgbColor:i,lineType:{type:"ByLayer",name:"Continuous",standardFlag:0,description:"Solid line",totalPatternLength:0},lineTypeScale:1,lineWeight:u.AcGiLineWeight.ByLayer,fillType:{solidFill:!0,patternAngle:0,definitionLines:[]},transparency:new u.AcCmTransparency,thickness:0,layer:e.layer??"0",drawOrder:0}}}const Lc=new f.Color(583902);let ue=class{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=Lc){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),e.uniforms.u_startColor&&e.uniforms.u_startColor.value.set(t),e.uniforms.u_endColor&&e.uniforms.u_endColor.value.set(t))}static hasColorProperty(e){return"color"in e&&e.color instanceof f.Color}static hasEmissiveProperty(e){return"emissive"in e&&e.emissive instanceof f.Color}static hasUniformsProperty(e){return"uniforms"in e&&e.uniforms!==void 0}};class Zs{static createMatrix4(e){const t=e.elements;return new f.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])}}class Js extends f.Object3D{constructor(e){super(),this._styleManager=e}get styleManager(){return this._styleManager}copy(e,t){return this._styleManager=e._styleManager,super.copy(e,t)}}const Qs=class Jt extends Js{constructor(e){super(e),this._box=new f.Box3}get box(){return this._box}set box(e){this._box.copy(e)}get basePoint(){return this._basePoint}set basePoint(e){e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e)}get objectId(){return this.userData.objectId}set objectId(e){this.userData.objectId=e}get ownerId(){return this.userData.ownerId}set ownerId(e){this.userData.ownerId=e}get layerName(){return this.userData.layerName}set layerName(e){this.userData.layerName=e}static flattenObject(e){const t=[],i=new f.Vector3,n=new f.Quaternion,s=new f.Vector3;function r(c,l){l.decompose(i,n,s),c.position.copy(i),c.quaternion.copy(n),c.scale.copy(s),c.updateMatrix()}function o(c,l){const h=[...c.children];for(const d of h)!d.userData.layerName&&c.userData.layerName&&(d.userData.layerName=c.userData.layerName),d.children.length>0?o(d,l):(d.updateMatrixWorld(!0),t.push({object:d,relativeMatrix:l.clone().multiply(d.matrixWorld)})),c.remove(d)}e.updateMatrixWorld(!0),o(e,e.matrixWorld.clone().invert());for(const c of t){const{object:l,relativeMatrix:h}=c;r(l,h),e.add(l)}e.updateMatrixWorld(!0)}static disposeObject(e,t=!0){t&&e.removeFromParent(),(e instanceof f.Mesh||e instanceof f.Line||e instanceof f.Points)&&e.geometry&&e.geometry.dispose(),(e instanceof f.Mesh||e instanceof f.Line||e instanceof f.Points)&&(Array.isArray(e.material)?e.material:[e.material]).forEach(i=>{var n,s,r,o,c,l,h,d;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(),(c=i.normalMap)==null||c.dispose(),(l=i.roughnessMap)==null||l.dispose(),(h=i.metalnessMap)==null||h.dispose(),(d=i.alphaMap)==null||d.dispose()}),e.children.forEach(i=>this.disposeObject(i)),"geometry"in e&&(e.geometry=null),"material"in e&&(e.material=null),e.children=[]}flatten(){Jt.flattenObject(this)}dispose(){Jt.disposeObject(this)}async draw(){}addChild(e){this.add(e)}applyMatrix(e){const t=Zs.createMatrix4(e);this.applyMatrix4(t),this.updateMatrixWorld(!0),this._box.applyMatrix4(t)}bakeTransformToChildren(){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.clone();this.children.forEach(t=>{t.updateMatrix(),t.applyMatrix4(e)}),this.position.set(0,0,0),this.rotation.set(0,0,0),this.scale.set(1,1,1),this.updateMatrix()}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 Jt(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];if(n instanceof Jt){t.add(n.fastDeepClone());continue}const s=n.clone(!1);"geometry"in s&&(s.geometry=s.geometry.clone()),t.add(s)}}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 f.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,c=0;o<t;o++)r[c]=i,r[c+1]=n,r[c+2]=s,c+=3;return r}};Qs.NO_BATCH_FLAG="noBatch";let re=Qs;class He extends re{constructor(e,t){super(t),this._boxes=[],e.forEach(s=>{if(Array.isArray(s)){const r=new re(t);this.add(r),this.box.union(r.box)}else this.add(s),this.box.union(s.box);this.storeBoxes(s)}),this.flatten();let i=!1;const n=this.children;for(let s=0;s<n.length;++s){const r=n[s];if(r.userData.layerName!=null&&r.userData.layerName!=="0"){i=!0;break}}this._isOnTheSameLayer=!i}get isOnTheSameLayer(){return this._isOnTheSameLayer}get boxes(){return this._boxes}applyMatrix(e){const t=Zs.createMatrix4(e);this._boxes.forEach(i=>this.applyMatrixToEntityBox(i,t)),super.applyMatrix(e)}copy(e,t){return this._isOnTheSameLayer=e._isOnTheSameLayer,this._boxes=[],e.boxes.forEach(i=>this._boxes.push({...i})),super.copy(e,t)}fastDeepClone(){const e=new He([],this.styleManager);return e.copy(this,!1),this.copyGeometry(this,e),e}storeBoxes(e){e instanceof He?e._boxes.forEach(t=>this._boxes.push(t)):e instanceof re&&this._boxes.push({minX:e.box.min.x,minY:e.box.min.y,maxX:e.box.max.x,maxY:e.box.max.y,id:e.objectId})}applyMatrixToEntityBox(e,t){const i=[new f.Vector3(e.minX,e.minY,0),new f.Vector3(e.maxX,e.minY,0),new f.Vector3(e.maxX,e.maxY,0),new f.Vector3(e.minX,e.maxY,0)];for(const c of i)c.applyMatrix4(t);let n=1/0,s=1/0,r=-1/0,o=-1/0;for(const c of i)n=Math.min(n,c.x),s=Math.min(s,c.y),r=Math.max(r,c.x),o=Math.max(o,c.y);e.minX=n,e.minY=s,e.maxX=r,e.maxY=o}}class Tc extends re{constructor(e,t,i){super(i);const n=URL.createObjectURL(e),s=new f.TextureLoader().load(n,()=>URL.revokeObjectURL(n),void 0,()=>URL.revokeObjectURL(n));s.colorSpace=f.SRGBColorSpace;const r=new f.MeshBasicMaterial({side:f.DoubleSide,map:s}),o=new f.Shape(t.boundary),c=new f.ShapeGeometry(o);this.generateUVs(c);const l=new f.Mesh(c,r);this.add(l)}generateUVs(e){const t=e.attributes.position.array,i=new Float32Array(t.length/3*2),n=Math.min(...t.filter((h,d)=>d%3===0)),s=Math.max(...t.filter((h,d)=>d%3===0)),r=Math.min(...t.filter((h,d)=>d%3===1)),o=Math.max(...t.filter((h,d)=>d%3===1)),c=s-n,l=o-r;for(let h=0;h<t.length;h+=3){const d=t[h],g=t[h+1];i[h/3*2]=(d-n)/c,i[h/3*2+1]=(g-r)/l}e.setAttribute("uv",new f.BufferAttribute(i,2))}}class Ic extends re{constructor(e,t,i,n=!1){super(i);const s=this.styleManager.getLineMaterial(t,n),r=e.length,o=this.computeLocalOrigin(e);if(s instanceof bt.LineMaterial){const g=new Float32Array((r-1)*6);for(let w=0,C=0;w<r-1;w++){const b=e[w],x=e[w+1];g[C++]=b.x-o.x,g[C++]=b.y-o.y,g[C++]=(b.z??0)-o.z,g[C++]=x.x-o.x,g[C++]=x.y-o.y,g[C++]=(x.z??0)-o.z}const m=new Fe.LineSegmentsGeometry;m.setPositions(g),m.computeBoundingBox(),m.computeBoundingSphere(),this.geometry=m,this.setBoundingBox(m,o);const y=new We.LineSegments2(m,s);y.position.set(o.x,o.y,o.z),y.userData.styleMaterialId=s.id,this.add(y);return}const c=new Float32Array(r*3),l=r*2>65535?new Uint32Array(r*2):new Uint16Array(r*2);for(let g=0,m=0;g<r;g++){const y=e[g];c[m++]=y.x-o.x,c[m++]=y.y-o.y,c[m++]=(y.z??0)-o.z}for(let g=0,m=0;g<r-1;g++)l[m++]=g,l[m++]=g+1;const h=new f.BufferGeometry;h.setAttribute("position",new f.BufferAttribute(c,3)),h.setIndex(new f.BufferAttribute(l,1)),this.setBoundingBox(h,o),this.geometry=h;const d=new f.LineSegments(h,s);d.position.set(o.x,o.y,o.z),It.computeLineDistances(d),this.add(d)}setBoundingBox(e,t){e.computeBoundingBox();const i=e.boundingBox.clone();i.translate(t),this.box=i}computeLocalOrigin(e){const t=new f.Box3;for(let i=0;i<e.length;i++){const n=e[i];t.expandByPoint(Ec.set(n.x,n.y,n.z??0))}return t.getCenter(new f.Vector3)}}const Ec=new f.Vector3;class kc extends re{constructor(e,t,i,n,s){super(s);const r=this.styleManager.getLineMaterial(n);if(r instanceof bt.LineMaterial){const l=Math.floor(i.length/2),h=new Float32Array(l*6),d=new f.Box3;for(let y=0;y<e.length;y+=t)d.expandByPoint(Bc.set(e[y],e[y+1],e[y+2]??0));for(let y=0,w=0;y<l;y++){const C=i[y*2],b=i[y*2+1],x=C*t,A=b*t;h[w++]=e[x],h[w++]=e[x+1],h[w++]=e[x+2]??0,h[w++]=e[A],h[w++]=e[A+1],h[w++]=e[A+2]??0}const g=new Fe.LineSegmentsGeometry;g.setPositions(h),g.computeBoundingBox(),g.computeBoundingSphere(),this.box.copy(d);const m=new We.LineSegments2(g,r);m.userData.styleMaterialId=r.id,this.add(m);return}const o=new f.BufferGeometry;o.setAttribute("position",new f.BufferAttribute(e,t)),o.setIndex(new f.BufferAttribute(i,1)),o.computeBoundingBox(),this.box=o.boundingBox;const c=new f.LineSegments(o,r);It.computeLineDistances(c),this.add(c)}}const Bc=new f.Vector3;class Dc{constructor(e){this.unsupportedTextStyles={},this._styleManager=e}getMeshBasicMaterial(e){const t=wn.createTraitsForMText(e);return this._styleManager.getMTextFillMaterial(t)}getLineBasicMaterial(e){const t=wn.createTraitsForMText(e);return this._styleManager.getLineMaterial(t,!0)}}const er=class Qt{constructor(){}static getInstance(){return Qt._instance||(Qt._instance=new Qt),Qt._instance}overrideStyleManager(e){this._styleManager=e}setFontUrl(e){this._fontUrl=e,this.applyFontUrl()}setRenderMode(e){this._renderMode=e,this._renderer&&(this._renderer.setDefaultMode(e),this.applyFontUrl())}async asyncRenderMText(e,t,i=B.createDefaultColorSettings()){if(!this._renderer)throw new Error("AcTrMTextRenderer not initialized!");return await this._renderer.asyncRenderMText(e,t,i)}syncRenderMText(e,t,i=B.createDefaultColorSettings()){if(this.ensureRendererCreated(),!this._renderer)throw new Error("AcTrMTextRenderer not initialized!");return this._renderer.syncRenderMText(e,t,i)}initialize(e){if(this._workerUrl=e,this._renderer=new B.UnifiedRenderer("worker",{workerUrl:e}),this._renderMode&&this._renderer.setDefaultMode(this._renderMode),this.applyFontUrl(),this._styleManager){const t=new Dc(this._styleManager);this._renderer.setStyleManager(t)}}dispose(){this._renderer&&(this._renderer.destroy(),this._renderer=void 0)}ensureRendererCreated(){!this._renderer&&this._workerUrl&&this.initialize(this._workerUrl)}applyFontUrl(){this._renderer&&this._fontUrl&&this._renderer.setFontUrl(this._fontUrl)}};er._instance=null;let Ye=er;class Mc extends B.DefaultFontLoader{onFontUrlChanged(e){Ye.getInstance().setFontUrl(e)}}function Ie(a){return a.userData}function bn(a,e){Object.assign(Ie(a),e)}function tr(a){return a.isByLayerColor===!0||a.isByLayerLineType===!0||a.isByLayerLineWeight===!0||a.isByLayerTransparency===!0}const ir=class{constructor(e){this.cache={},this.keyToTraits={},this.options=e}getMaterial(e,t){const i=this.buildKey(e,t);return this.keyToTraits[i]||(this.keyToTraits[i]={...u.deepClone(e),...t}),this.cache[i]?this.cache[i]:this.createMaterial(i,e,t)}updateLayerMaterial(e,t){const i={};for(const n of Object.keys(this.cache)){const s=this.cache[n],r=Ie(s);if(!(r.layer===e&&tr(r)))continue;const o=this.keyToTraits[n];if(!o)continue;const c=this.resolveByLayerBindings(o,s),l=u.deepClone(o);this.applyInheritedLayerTraits(l,t,c),t.layer!=null&&(l.layer=t.layer);const h=this.buildKey(l,l),d=s.id;s.dispose(),delete this.cache[n],delete this.keyToTraits[n];const g=this.createMaterial(h,l,l,c);this.keyToTraits[h]=l,i[d]=g}return i}changeForeground(e){for(const t of Object.keys(this.cache)){const i=this.cache[t];Ie(i).isForeground!==!0||!this.keyToTraits[t]||ue.setMaterialColor(i,new f.Color(e))}}changeBackground(e){for(const t of Object.keys(this.cache)){const i=this.cache[t];Ie(i).isBackgroundFill!==!0||!this.keyToTraits[t]||ue.setMaterialColor(i,new f.Color(e))}}dispose(){Object.values(this.cache).forEach(e=>e.dispose()),this.cache={},this.keyToTraits={}}getBackSideVariant(e){return e}getLayerBoundMaterial(e,t,i){const n=Ie(e).materialKey;if(!n)return;const s=this.keyToTraits[n];if(!s)return;if(s.layer===t&&!i)return e;const r={...u.deepClone(s),layer:t},o=this.resolveByLayerBindings(s,e);this.applyInheritedLayerTraits(r,i,o);const c=this.buildKey(r,r);return this.cache[c]?this.cache[c]:(this.keyToTraits[c]=r,this.createMaterial(c,r,r,o))}applyInheritedLayerTraits(e,t,i){if(!t)return;const n=(i==null?void 0:i.isByLayerColor)===!0,s=(i==null?void 0:i.isByLayerLineType)===!0,r=(i==null?void 0:i.isByLayerLineWeight)===!0,o=(i==null?void 0:i.isByLayerTransparency)===!0;if(n){if(t.rgbColor!=null)e.rgbColor=t.rgbColor;else if(t.color){const c=t.color.RGB;c!=null&&(e.rgbColor=c)}}s&&t.lineType&&(e.lineType=u.deepClone(t.lineType)),r&&t.lineWeight!=null&&(e.lineWeight=t.lineWeight),o&&t.transparency&&(e.transparency=u.deepClone(t.transparency))}resolveByLayerBindings(e,t){var i;const n=t?Ie(t):void 0,s=((i=e.transparency)==null?void 0:i.isByLayer)===!0;return{isByLayerColor:(n==null?void 0:n.isByLayerColor)??e.color.isByLayer===!0,isByLayerLineType:(n==null?void 0:n.isByLayerLineType)??e.lineType.type==="ByLayer",isByLayerLineWeight:(n==null?void 0:n.isByLayerLineWeight)??e.lineWeight===u.AcGiLineWeight.ByLayer,isByLayerTransparency:(n==null?void 0:n.isByLayerTransparency)??s}}createMaterial(e,t,i,n){const s=this.createMaterialImpl(t,i),r=this.shouldTrackForeground(t,i),o=this.shouldTrackBackground(t,i);if(r){const l=this.options.currentBackgroundColor===0?16777215:0;ue.setMaterialColor(s,new f.Color(l))}const c=n??this.resolveByLayerBindings(t);return bn(s,{layer:t.layer,isByLayerColor:c.isByLayerColor,isByLayerLineType:c.isByLayerLineType,isByLayerLineWeight:c.isByLayerLineWeight,isByLayerTransparency:c.isByLayerTransparency,isForeground:r,isBackgroundFill:o,drawOrder:t.drawOrder??0,materialKey:e}),this.cache[e]=s,s}hasByLayerKeyTraits(e){return e.color.isByLayer||e.lineType.type==="ByLayer"}shouldTrackForeground(e,t){return e.color.isForeground}shouldTrackBackground(e,t){return!1}buildDrawOrderSuffix(e){return e.drawOrder===0?"":`_draw_${e.drawOrder??0}`}};ir.CameraZoomUniform={value:1};let it=ir;const Oc={LINEAR:0,CYLINDER:1,INVCYLINDER:2,SPHERICAL:3,INVSPHERICAL:4,HEMISPHERICAL:5,INVHEMISPHERICAL:6,CURVED:7,INVCURVED:8};function Fc(a,e,t,i=f.FrontSide){const n=new f.Color(a.startColor??t.getHex()),s=new f.Color(a.endColor??jc(n,a.oneColorMode,a.shadeTintValue)),r=Oc[(a.name||"LINEAR").trim().toUpperCase()]??0,o={u_startColor:{value:n},u_endColor:{value:s},u_angle:{value:a.angle??0},u_shift:{value:a.shift??0},u_gradientType:{value:r}},c=`
|
|
498
|
-
attribute vec2 gradientPosition;
|
|
499
|
-
|
|
500
|
-
varying vec2 v_gradientPosition;
|
|
501
|
-
|
|
502
|
-
#include <clipping_planes_pars_vertex>
|
|
503
|
-
void main() {
|
|
504
|
-
v_gradientPosition = gradientPosition;
|
|
505
|
-
|
|
506
|
-
#include <begin_vertex>
|
|
507
|
-
#include <project_vertex>
|
|
508
|
-
#include <clipping_planes_vertex>
|
|
509
|
-
}`,l=`
|
|
510
|
-
precision highp float;
|
|
511
|
-
|
|
512
|
-
uniform vec3 u_startColor;
|
|
513
|
-
uniform vec3 u_endColor;
|
|
514
|
-
uniform float u_angle;
|
|
515
|
-
uniform float u_shift;
|
|
516
|
-
uniform int u_gradientType;
|
|
517
|
-
|
|
518
|
-
varying vec2 v_gradientPosition;
|
|
519
|
-
|
|
520
|
-
#include <clipping_planes_pars_fragment>
|
|
521
|
-
|
|
522
|
-
const float EPSILON = 1e-6;
|
|
523
|
-
|
|
524
|
-
vec2 rotate(vec2 samplePos, float angle) {
|
|
525
|
-
float s = sin(angle);
|
|
526
|
-
float c = cos(angle);
|
|
527
|
-
return vec2(c * samplePos.x - s * samplePos.y, c * samplePos.y + s * samplePos.x);
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
float saturate(float value) {
|
|
531
|
-
return clamp(value, 0.0, 1.0);
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
float getGradientFactor(vec2 localPos) {
|
|
535
|
-
vec2 shiftedPos = localPos - vec2(clamp(u_shift, -1.0, 1.0), 0.0);
|
|
536
|
-
float linear = saturate(shiftedPos.x * 0.5 + 0.5);
|
|
537
|
-
float cylinder = saturate(1.0 - abs(shiftedPos.x));
|
|
538
|
-
float radial = saturate(length(shiftedPos));
|
|
539
|
-
float curved = smoothstep(0.0, 1.0, linear);
|
|
540
|
-
float hemi = saturate(1.0 - length(shiftedPos - vec2(0.0, -1.0)) * 0.5);
|
|
541
|
-
|
|
542
|
-
if (u_gradientType == 1) {
|
|
543
|
-
return cylinder;
|
|
544
|
-
}
|
|
545
|
-
if (u_gradientType == 2) {
|
|
546
|
-
return 1.0 - cylinder;
|
|
547
|
-
}
|
|
548
|
-
if (u_gradientType == 3) {
|
|
549
|
-
return 1.0 - radial;
|
|
550
|
-
}
|
|
551
|
-
if (u_gradientType == 4) {
|
|
552
|
-
return radial;
|
|
553
|
-
}
|
|
554
|
-
if (u_gradientType == 5) {
|
|
555
|
-
return hemi;
|
|
556
|
-
}
|
|
557
|
-
if (u_gradientType == 6) {
|
|
558
|
-
return 1.0 - hemi;
|
|
559
|
-
}
|
|
560
|
-
if (u_gradientType == 7) {
|
|
561
|
-
return curved;
|
|
562
|
-
}
|
|
563
|
-
if (u_gradientType == 8) {
|
|
564
|
-
return 1.0 - curved;
|
|
565
|
-
}
|
|
566
|
-
return linear;
|
|
567
|
-
}
|
|
568
|
-
|
|
569
|
-
void main() {
|
|
570
|
-
#include <clipping_planes_fragment>
|
|
571
|
-
|
|
572
|
-
vec2 localPos = rotate(v_gradientPosition, -u_angle);
|
|
573
|
-
float factor = saturate(getGradientFactor(localPos));
|
|
574
|
-
|
|
575
|
-
gl_FragColor = vec4(mix(u_startColor, u_endColor, factor), 1.0);
|
|
576
|
-
#include <colorspace_fragment>
|
|
577
|
-
}`;return new f.ShaderMaterial({uniforms:o,vertexShader:c,fragmentShader:l,side:i})}function jc(a,e=!1,t=0){if(!e)return 16777215;const i=Math.abs(f.MathUtils.clamp(t,-1,1))||.5,n=t<0?new f.Color(0):new f.Color(16777215);return a.clone().lerp(n,i).getHex()}function nr(a){return a?{minX:vi(a.minX,0),minY:vi(a.minY,0),maxX:vi(a.maxX,1),maxY:vi(a.maxY,1)}:{minX:0,minY:0,maxX:1,maxY:1}}function vi(a,e){return Number.isFinite(a)?a:e}function Nc(a,e,t,i,n=0,s=f.FrontSide){const r={u_cameraZoom:t,u_patternLines:{value:a},u_patternAngle:{value:e},u_color:{value:i}},o=`
|
|
578
|
-
varying vec3 v_pos;
|
|
579
|
-
|
|
580
|
-
#include <clipping_planes_pars_vertex>
|
|
581
|
-
void main() {
|
|
582
|
-
//vec4 worldPosition = modelMatrix * vec4(position, 1.0);
|
|
583
|
-
v_pos = position;
|
|
584
|
-
|
|
585
|
-
#include <begin_vertex>
|
|
586
|
-
#include <project_vertex>
|
|
587
|
-
#include <clipping_planes_vertex>
|
|
588
|
-
}`,c=`
|
|
589
|
-
precision highp float;
|
|
590
|
-
uniform mat4 modelMatrix;
|
|
591
|
-
uniform float u_cameraZoom;
|
|
592
|
-
uniform vec3 u_color;
|
|
593
|
-
varying vec3 v_pos;
|
|
594
|
-
|
|
595
|
-
struct PatternLine {
|
|
596
|
-
float angle;
|
|
597
|
-
vec2 base;
|
|
598
|
-
vec2 offset;
|
|
599
|
-
float dashLengths[MAX_PATTERN_SEGMENT_COUNT];
|
|
600
|
-
float patternLength;
|
|
601
|
-
};
|
|
602
|
-
|
|
603
|
-
uniform PatternLine u_patternLines[${a.length}];
|
|
604
|
-
uniform float u_patternAngle;
|
|
109
|
+
uniform PatternLine u_patternLines[${o.length}];
|
|
110
|
+
uniform float u_patternAngle;
|
|
605
111
|
|
|
606
112
|
#include <clipping_planes_pars_fragment>
|
|
607
113
|
|
|
@@ -758,7 +264,7 @@
|
|
|
758
264
|
|
|
759
265
|
float total = 0.0;
|
|
760
266
|
|
|
761
|
-
#if ${
|
|
267
|
+
#if ${o.length} > 1
|
|
762
268
|
#pragma unroll_loop_start
|
|
763
269
|
for (int i = 0; i < u_patternLines.length(); i++) {
|
|
764
270
|
PatternLine pl = u_patternLines[i];
|
|
@@ -779,7 +285,7 @@
|
|
|
779
285
|
gl_FragColor = vec4(u_color * total, 1.0);
|
|
780
286
|
#include <colorspace_fragment>
|
|
781
287
|
}
|
|
782
|
-
`;return new
|
|
288
|
+
`;return new y.ShaderMaterial({uniforms:a,vertexShader:c,fragmentShader:l,clipping:!0,side:s,defines:{MAX_PATTERN_SEGMENT_COUNT:r}})}class Gc extends ot{getBackSideVariant(e){const t=Ce(e),i=t.materialKey;if(!i||t.side==="back")return e;const n=this.keyToTraits[i];return n?this.getMaterial(n,{...n,side:"back"}):e}shouldTrackForeground(e,t){var i;if(!e.color.isForeground)return!1;if((e.drawOrder??0)>=0)return!0;const n=e.fillType;return!n.gradient&&!!((i=n.definitionLines)!=null&&i.length)}shouldTrackBackground(e,t){if(!e.color.isForeground||(e.drawOrder??0)>=0)return!1;const i=e.fillType;return i.gradient?!1:!i.definitionLines||i.definitionLines.length===0}createMaterialImpl(e,t){const i=e.fillType,n=t.side??"front",s=n==="back"?y.BackSide:y.FrontSide,r=this.shouldTrackBackground(e,t)?{...e,rgbColor:this.options.currentBackgroundColor}:e;let a;return i.gradient?a=this.createGradientShaderMaterial(r,t,s):!i.definitionLines||i.definitionLines.length<1?a=this.createMeshBasicMaterial(r,s):i.definitionLines.some(c=>!this.isValidDefinitionLine(c))?(u.log.warn("Invalid hatch pattern definition line, fallback to solid fill",i),a=this.createMeshBasicMaterial(r,s)):a=this.createHatchShaderMaterial(r,t,s),ln(a,{side:n}),a}createGradientShaderMaterial(e,t,i){return jc(e.fillType.gradient,Us(t.gradientBounds),new y.Color(e.rgbColor),i)}createHatchShaderMaterial(e,t,i){const n=e.fillType,s=.005,r=.05;let a=2;n.definitionLines.forEach(p=>{a=Math.max(p.dashLengths.length,a)});let c=0;const l=[],h=new y.Vector2;for(const p of n.definitionLines){const m=new y.Vector2(p.base.x,p.base.y).sub(t.rebaseOffset),f=new y.Vector2(p.offset.x,p.offset.y).rotateAround(h,-p.angle);if(f.y===0){u.log.warn("offset.y is zero, skipping pattern line");continue}const w=p.dashLengths.length;let x=!0,b=0;for(let M=0;M<w;++M){const k=p.dashLengths[M];k>0&&(x=!1),b+=Math.abs(k)}const v=x?r:s,C=[];let P=0;for(let M=0;M<w;++M)C[M]=p.dashLengths[M],C[M]===0&&(C[M]=v*b),P+=Math.abs(C[M]);for(let M=w;M<a;++M)C[M]=0;const L={angle:p.angle,base:m,offset:f,dashLengths:C,patternLength:P};if(c+=4,c+=a,c+=4,c>this.options.maxFragmentUniforms){u.log.warn("There will be warning in fragment shader when number of uniforms exceeds 1024, so extra hatch line patterns are ignored here!");break}l.push(L)}const d=Vc(l,n.patternAngle,ot.CameraZoomUniform,new y.Color(e.rgbColor),0,i);return d.defines={MAX_PATTERN_SEGMENT_COUNT:a},d}createMeshBasicMaterial(e,t){return new y.MeshBasicMaterial({color:e.rgbColor,side:t})}buildKey(e,t){const i=e.fillType,n=t.side==="back"?"_back":"",s=this.buildDrawOrderSuffix(e),r=this.shouldTrackBackground(e,t)?"_bgfill":"";if(i.gradient){const c=i.gradient,l=Us(t.gradientBounds);return["gradient",e.layer,e.rgbColor,c.name||"LINEAR",c.angle??0,c.shift??0,c.oneColorMode?1:0,c.shadeTintValue??0,c.startColor??"",c.endColor??"",l.minX,l.minY,l.maxX,l.maxY,n,s].join("_")}if(!i.definitionLines||i.definitionLines.length===0)return`solid_${e.layer}_${e.rgbColor}${n}${s}${r}`;const a=i.definitionLines.map(c=>{if(!this.isValidDefinitionLine(c))return"invalid";const l=c.dashLengths.join(","),h=Number.isFinite(c.angle)?c.angle:0,d=c.base.x,p=c.base.y,m=c.offset.x,f=c.offset.y;return`${l}@${h},${d},${p},${m},${f}`}).join("|");return["hatch",e.layer,e.rgbColor,i.patternAngle,t.rebaseOffset.x,t.rebaseOffset.y,a,n,s].join("_")}isValidDefinitionLine(e){var t,i,n,s;if(!e||typeof e!="object")return!1;const r=e;return Array.isArray(r.dashLengths)?(r.base={x:this.toFiniteNumber((t=r.base)==null?void 0:t.x,0),y:this.toFiniteNumber((i=r.base)==null?void 0:i.y,0)},r.offset={x:this.toFiniteNumber((n=r.offset)==null?void 0:n.x,0),y:this.toFiniteNumber((s=r.offset)==null?void 0:s.y,0)},r.angle=this.toFiniteNumber(r.angle,0),r.dashLengths=r.dashLengths.map(a=>this.toFiniteNumber(a,0)),!0):!1}toFiniteNumber(e,t=0){return Number.isFinite(e)?e:t}}class Kc{static createLineShaderMaterial(e,t,i,n,s){let r=0;const a=[];for(let c=0;c<e.length;c++){let l=e[c].elementLength;l<0&&e[c].elementTypeFlag!==0&&(l=Math.abs(l)),l*=i,a[c]=l,r+=Math.abs(a[c])}for(let c=0;c<a.length;c++)a[c]===0&&(a[c]=.5,r+=a[c]);return this.createLineShaderMaterialFromScaledPattern(a,r,t,n,s)}static createLineShaderMaterialFromScaledPattern(e,t,i,n,s){const r=y.UniformsUtils.merge([y.UniformsLib.common,{pattern:{value:e},patternLength:{value:t},u_color:{value:new y.Color(i)}}]);r.u_viewportScale={value:n},r.u_cameraZoom=s;const a=`
|
|
783
289
|
attribute float lineDistance;
|
|
784
290
|
varying float vLineDistance;
|
|
785
291
|
|
|
@@ -791,7 +297,7 @@
|
|
|
791
297
|
#include <begin_vertex>
|
|
792
298
|
#include <project_vertex>
|
|
793
299
|
#include <clipping_planes_vertex>
|
|
794
|
-
}`,
|
|
300
|
+
}`,c=`
|
|
795
301
|
uniform mat4 modelMatrix;
|
|
796
302
|
uniform vec3 diffuse;
|
|
797
303
|
uniform vec3 u_color;
|
|
@@ -834,27 +340,502 @@
|
|
|
834
340
|
}
|
|
835
341
|
}
|
|
836
342
|
#include <colorspace_fragment>
|
|
837
|
-
}`;return new f.ShaderMaterial({uniforms:c,vertexShader:l,fragmentShader:h,clipping:!0})}}class Vc extends it{buildKey(e,t){const i=this.hasByLayerKeyTraits(e),n=this.resolveLineWidth(e.lineWeight),s=this.getMaterialMode(e,t),r=this.buildDrawOrderSuffix(e);return s==="shader"?i?`layer_${s}_${e.layer}_${e.lineType.name}_${e.rgbColor}_${e.lineTypeScale}_${n}${r}`:`entity_${s}_${e.lineType.name}_${e.rgbColor}_${e.lineTypeScale}_${n}${r}`:i?`layer_${s}_${e.layer}_${e.rgbColor}_${n}${r}`:`entity_${s}_${e.rgbColor}_${n}${r}`}isShaderMaterial(e,t){return!!(!t.basicMaterialOnly&&e.lineType.pattern&&e.lineType.pattern.length>0)}getMaterialMode(e,t){return this.isShaderMaterial(e,t)?"shader":t.basicMaterialOnly?"basic":"fat"}createMaterialImpl(e,t={}){let i;const n=this.getLineTypeScales(),s=n.ltscale*n.celtscale*e.lineTypeScale;if(this.isShaderMaterial(e,t))i=zc.createLineShaderMaterial(e.lineType.pattern,e.rgbColor,s,this.options.viewportScaleUniform,it.CameraZoomUniform);else if(t.basicMaterialOnly||e.lineWeight<0)i=new f.LineBasicMaterial({color:e.rgbColor});else{const r=new bt.LineMaterial({color:e.rgbColor,linewidth:this.resolveLineWidth(e.lineWeight)});r.resolution.copy(this.options.resolution),i=r}return i}hasByLayerKeyTraits(e){return super.hasByLayerKeyTraits(e)||e.lineWeight===u.AcGiLineWeight.ByLayer}resolveLineWidth(e){return e<0?1:Math.max(1,e/40)}updateResolution(){const e=this.options.resolution;Object.values(this.cache).forEach(t=>{t instanceof bt.LineMaterial&&t.resolution.copy(e)})}getLineTypeScales(){return{ltscale:this.options.ltscale||1,celtscale:this.options.celtscale||1}}}class Gc extends it{buildKey(e,t){const i=t.size??1,n=this.buildDrawOrderSuffix(e);return this.hasByLayerKeyTraits(e)?`layer_${e.layer}_${e.rgbColor}_${i}${n}`:`entity_${e.rgbColor}_${i}${n}`}hasByLayerKeyTraits(e){return e.color.isByLayer}createMaterialImpl(e,t={}){return new f.PointsMaterial({color:e.rgbColor,size:t.size})}}class $c{constructor(){this.options={ltscale:1,celtscale:1,viewportScaleUniform:1,maxFragmentUniforms:1024,resolution:new f.Vector2(1,1),showLineWeight:!1,currentBackgroundColor:0},this.unsupportedTextStyles={},this.pointMgr=new Gc(this.options),this.lineMgr=new Vc(this.options),this.fillMgr=new Rc(this.options)}getPointsMaterial(e,t=2){return this.pointMgr.getMaterial(e,{size:t})}getLineMaterial(e,t){const i=!!(e.lineType.pattern&&e.lineType.pattern.length>0),n=!this.options.showLineWeight&&!i;return this.lineMgr.getMaterial(e,{basicMaterialOnly:t||n})}get showLineWeight(){return this.options.showLineWeight}set showLineWeight(e){this.options.showLineWeight=e}get currentBackgroundColor(){return this.options.currentBackgroundColor}set currentBackgroundColor(e){this.options.currentBackgroundColor=e,this.changeBackground(e)}getFillMaterial(e,t=sr,i){return this.fillMgr.getMaterial(e,{rebaseOffset:t,gradientBounds:i})}getMTextFillMaterial(e,t=sr){return this.fillMgr.getMaterial(e,{rebaseOffset:t})}getBackSideVariant(e){return this.fillMgr.getBackSideVariant(e)}updateLayerMaterial(e,t){return{...this.lineMgr.updateLayerMaterial(e,t),...this.pointMgr.updateLayerMaterial(e,t),...this.fillMgr.updateLayerMaterial(e,t)}}getLayerBoundMaterial(e,t,i){return this.lineMgr.getLayerBoundMaterial(e,t,i)||this.pointMgr.getLayerBoundMaterial(e,t,i)||this.fillMgr.getLayerBoundMaterial(e,t,i)||e}changeForeground(e){this.lineMgr.changeForeground(e),this.pointMgr.changeForeground(e),this.fillMgr.changeForeground(e)}changeBackground(e){this.lineMgr.changeBackground(e),this.pointMgr.changeBackground(e),this.fillMgr.changeBackground(e)}dispose(){this.lineMgr.dispose(),this.pointMgr.dispose(),this.fillMgr.dispose()}updateLineResolution(e,t){this.options.resolution.set(e,t),this.lineMgr.updateResolution()}}const sr=new f.Vector2(0,0);class Kc{constructor(e){this.events={fontNotFound:new u.AcCmEventManager},this._renderer=e,this._styleManager=new $c;const t=e.getSize(new f.Vector2);this._styleManager.updateLineResolution(t.x,t.y),Ye.getInstance().overrideStyleManager(this._styleManager),B.FontManager.instance.events.fontNotFound.addEventListener(i=>{this.events.fontNotFound.dispatch(i)}),this._subEntityTraits=wn.createDefaultTraits()}get subEntityTraits(){return this._subEntityTraits}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),this._styleManager.updateLineResolution(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.updateCameraZoomUniform(t.zoom),this._renderer.render(e,t.internalCamera)}changeForeground(e){this._styleManager.changeForeground(e)}changeBackground(e){this._styleManager.changeBackground(e)}get currentBackgroundColor(){return this._styleManager.currentBackgroundColor}set currentBackgroundColor(e){this._styleManager.currentBackgroundColor=e}setClearColor(e,t){this._renderer.setClearColor(e,t)}getClearColor(){const e=new f.Color;return this._renderer.getClearColor(e),e.getHex()}set clearAlpha(e){this._renderer.setClearAlpha(e)}get clearAlpha(){return this._renderer.getClearAlpha()}get internalRenderer(){return this._renderer}setFontMapping(e){B.FontManager.instance.setFontMapping(e)}set ltscale(e){this._styleManager.options.ltscale=e}set celtscale(e){this._styleManager.options.celtscale=e}get missedFonts(){return B.FontManager.instance.missedFonts}get showLineWeight(){return this._styleManager.showLineWeight}set showLineWeight(e){this._styleManager.showLineWeight=e}updateLayerMaterial(e,t){return this._styleManager.updateLayerMaterial(e,t)}getLayerBoundMaterial(e,t,i){return this._styleManager.getLayerBoundMaterial(e,t,i)}createObject(){return new Js(this._styleManager)}createEntity(){return new re(this._styleManager)}group(e){return new He(e,this._styleManager)}point(e,t){return new Hc(e,this._subEntityTraits,t,this._styleManager)}circularArc(e){return this.linePoints(e.getPoints(100))}ellipticalArc(e){return this.linePoints(e.getPoints(100))}lines(e){return this.linePoints(e)}lineSegments(e,t,i){return new kc(e,t,i,this._subEntityTraits,this._styleManager)}area(e){return new Xc(e,this._subEntityTraits,this._styleManager)}mtext(e,t,i){return new Uc(e,this._subEntityTraits,t,this._styleManager,i)}image(e,t){return new Tc(e,t,this._styleManager)}dispose(){this._styleManager.dispose(),B.FontManager.instance.missedFonts={}}linePoints(e){return new Ic(e,this._subEntityTraits,this._styleManager)}updateCameraZoomUniform(e){it.CameraZoomUniform.value=e}}const rr=new f.Box3,xn=new f.Vector3;class Uc extends re{constructor(e,t,i,n,s=!1){super(n),this._text=e,this._style={...i},this._colorSettings={layer:t.layer,color:fn.toMTextColor(t.color),byLayerColor:16777215,byBlockColor:16777215},s||this.syncDraw()}async syncDraw(){const e=Ye.getInstance();if(e)try{const t=this._style,i=this._text;this._mtext=e.syncRenderMText(i,t,this._colorSettings),this.attachMText(this._mtext)}catch(t){u.log.info(`Failed to render mtext '${this._text.text}' with the following error:
|
|
838
|
-
|
|
839
|
-
`,t)}}raycast(e,t){var i;const n=t.length;(i=this._mtext)==null||i.raycast(e,t),!(t.length>n||this.box.isEmpty())&&(rr.copy(this.box).applyMatrix4(this.matrixWorld),e.ray.intersectBox(rr,xn)&&t.push({distance:e.ray.origin.distanceTo(xn),point:xn.clone(),object:this,face:null,faceIndex:void 0,uv:void 0}))}attachMText(e){this.add(e),this.flatten(),this.traverse(t=>{t.userData.bboxIntersectionCheck=!0}),this.updateSelectionBox(e)}updateSelectionBox(e){const t=this.computeGeometryBox();if(t.isEmpty()){this.box=e.box;return}if(!e.box.isEmpty()&&e.box.intersectsBox(t)){this.box=t.clone().union(e.box);return}this.box=t}computeGeometryBox(){const e=new f.Box3,t=new f.Box3;return this.updateMatrixWorld(!0),this.traverse(i=>{if(!this.hasGeometry(i))return;const n=i.geometry;n.boundingBox==null&&n.computeBoundingBox(),n.boundingBox!=null&&(i.updateMatrixWorld(!0),t.copy(n.boundingBox).applyMatrix4(i.matrixWorld),e.union(t))}),e}hasGeometry(e){return"geometry"in e&&e.geometry instanceof f.BufferGeometry}}const Wc=new f.Vector3;class Hc extends re{constructor(e,t,i,n){super(n);const s=ze.instance.create(i.displayMode,e);this.isShowPoint=s.point!=null;const r=s.point??new f.BufferGeometry().setFromPoints([Wc.copy(e)]);r.computeBoundingBox(),r.boundingBox&&this.box.union(r.boundingBox);const o=this.styleManager.getPointsMaterial(t),c=new f.Points(r,o);if(c.userData.bboxIntersectionCheck=!0,c.visible=this.isShowPoint,this.add(c),s.line){const l=s.line;l.computeBoundingBox(),l.boundingBox&&this.box.union(l.boundingBox);const h=this.styleManager.getLineMaterial(t,!0),d=new f.LineSegments(l,h);d.userData.bboxIntersectionCheck=!0,d.userData.isPoint=!0,d.userData.position={x:e.x,y:e.y,z:e.z},this.add(d)}}}function vn(a){return a.map(e=>new f.Vector2(e.x,e.y))}function Yc(a){if(!a)return!1;const e=a.getAttribute("position");return!!e&&e.count>0}class Xc extends re{constructor(e,t,i){super(i);const n=e.getPoints(100),s=e.buildHierarchy(),r=n.some(l=>l.length>=3),o=[];this.buildHatchGeometry(n,s,o);let c;if(o.length===1?c=o[0]:o.length>1&&(c=Sa.mergeGeometries(o)??void 0),c&&Yc(c)){c.computeBoundingBox(),this.box=c.boundingBox,this.addGradientPositionAttribute(c,t);const l={minX:this.box.min.x,minY:this.box.min.y,maxX:this.box.max.x,maxY:this.box.max.y},h=this.styleManager.getFillMaterial(t,void 0,l);this.add(new f.Mesh(c,h))}else r&&u.log.warn("Failed to convert hatch boundaries!")}addGradientPositionAttribute(e,t){if(!t.fillType.gradient||!e.boundingBox)return;const i=e.getAttribute("position");if(!i)return;const n=e.boundingBox,s=(n.min.x+n.max.x)*.5,r=(n.min.y+n.max.y)*.5,o=Math.max((n.max.x-n.min.x)*.5,1e-9),c=Math.max((n.max.y-n.min.y)*.5,1e-9),l=new Float32Array(i.count*2);for(let h=0;h<i.count;h++)l[h*2]=(i.getX(h)-s)/o,l[h*2+1]=(i.getY(h)-r)/c;e.setAttribute("gradientPosition",new f.BufferAttribute(l,2))}buildHatchGeometry(e,t,i){if(t.children.length===0)return;const n=[],s=new Map;t.children.forEach(c=>{c.children.length===0?n.push(c.index):s.set(c.index,c.children.map(l=>l.index))});const r=c=>{try{const l=new f.ShapeGeometry(c);l.hasAttribute("uv")&&l.deleteAttribute("uv"),l.hasAttribute("normal")&&l.deleteAttribute("normal"),i.push(l)}catch{u.log.warn(`Triangulate shape error: ${c.getPoints().map(l=>l.toArray()).toString()}`)}};n.forEach(c=>{const l=e[c];if(l.length<3)return;const h=new f.Shape(vn(l));r(h)});const o=c=>c.map(l=>l.toArray());for(const c of s){const l=e[c[0]];if(l.length<3)continue;const h=new f.Shape(vn(l));let d={regions:[],inverted:!1};const g=this.findIntersectHole(e,c[1]);g.forEach(y=>{let w={segments:[],inverted:!1},C=1e-6;try{y.forEach((b,x)=>{C=Math.min(e[b][0].relativeEps(),1e-6);const A=new Xs(new Us(C));if(x===0)w=A.segments({regions:[o(e[b])],inverted:!1});else{const _=A.segments({regions:[o(e[b])],inverted:!1}),L=A.combine(w,_);d=A.polygon(A.selectUnion(L)),d.regions.length>0?d.regions.forEach(T=>{if(T.length===0)return;const O=T.map(k=>new f.Vector2(k[0],k[1]));h.holes.push(new f.Path(O))}):u.log.warn("mergedHoles.regions is empty!")}})}catch(b){u.log.warn(`Polybool error: ${b}, epsilon is ${C}`)}});const m=g.flat(2);for(let y=0;y<c[1].length;y++){const w=c[1][y];if(!m.includes(w)){const C=e[w];if(C.length<3)continue;h.holes.push(new f.Path(vn(C)))}}r(h)}t.children.forEach(c=>{c.children.forEach(l=>{this.buildHatchGeometry(e,l,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 c=[];for(let l=s+1;l<i;l++){const h=e[t[l]];u.AcGeGeometryUtil.isPolygonIntersect(r,h)&&(o=!0,c.push(t[l]))}o&&(c.push(t[s]),n.push(c))}return n}}const qc="default";class or{constructor(e){this.scene=e,this.htmlGroup=new f.Group,this.htmlGroup.name="Html_Transient_Group",this.scene.add(this.htmlGroup),this.entries=new Map}add(e,t,i,n=qc){this.remove(e);const s=new os.CSS2DObject(t);s.position.set(i.x,i.y,i.z??0),this.entries.set(e,{object:s,layer:n}),this.htmlGroup.add(s)}updatePosition(e,t){const i=this.entries.get(e);i&&i.object.position.set(t.x,t.y,t.z??0)}remove(e){const t=this.entries.get(e);t&&(this.htmlGroup.remove(t.object),t.object.element.remove(),this.entries.delete(e))}clear(e){if(e==null){for(const t of this.entries.values())this.htmlGroup.remove(t.object),t.object.element.remove();this.entries.clear()}else for(const[t,i]of this.entries)i.layer===e&&(this.htmlGroup.remove(i.object),i.object.element.remove(),this.entries.delete(t))}has(e){return this.entries.has(e)}get(e){var t;return(t=this.entries.get(e))==null?void 0:t.object.element}setVisible(e,t){if(t==null)this.htmlGroup.visible=e;else for(const i of this.entries.values())i.layer===t&&(i.object.visible=e)}dispose(){this.clear(),this.scene.remove(this.htmlGroup)}}class ar{constructor(e){this.scene=e,this.transientGroup=new f.Group,this.transientGroup.name="Transient_Object_Group",this.scene.add(this.transientGroup),this.entities=new Map}clear(){for(const e of this.entities.values())e.dispose();this.entities.clear(),this.transientGroup.clear()}add(e){const t=e.objectId,i=this.entities.get(t);i&&(this.transientGroup.remove(i),i.dispose()),this.entities.set(t,e),this.transientGroup.add(e)}update(e){const t=this.entities.get(e.objectId);t&&(this.transientGroup.remove(t),t.dispose()),this.entities.set(e.objectId,e),this.transientGroup.add(e)}remove(e){const t=this.entities.get(e);t&&(this.transientGroup.remove(t),re.disposeObject(t),this.entities.delete(e))}get(e){return this.entities.get(e)}has(e){return this.entities.has(e)}setVisible(e){this.transientGroup.visible=e}dispose(){this.clear(),this.scene.remove(this.transientGroup)}}function Zc(a,e){return a-e}function Sn(a,e,t=0){const i=e.itemSize;if(a.isInterleavedBufferAttribute||a.array.constructor!==e.array.constructor){const n=a.count;for(let s=0;s<n;s++)for(let r=0;r<i;r++)e.setComponent(s+t,r,a.getComponent(s,r))}else e.array.set(a.array,t*i);e.needsUpdate=!0}function Xe(a,e){if(a.constructor!==e.constructor){const t=Math.min(a.length,e.length);for(let i=0;i<t;i++)e[i]=a[i]}else{const t=Math.min(a.length,e.length);e.set(new a.constructor(a.buffer,0,t))}}function Jc(a){const e=a.length;let t=0;return e>0&&(t=yn.estimateObjectSize(a[0])),{count:e,size:e*t}}function An(a,e,t,i){for(const n in e.attributes){const s=e.getAttribute(n),{array:r,itemSize:o,normalized:c}=s,l=new r.constructor(t*o),h=new f.BufferAttribute(l,o,c);a.setAttribute(n,h)}if(i!=null&&e.getIndex()!==null){const n=t>65535?new Uint32Array(i):new Uint16Array(i);a.setIndex(new f.BufferAttribute(n,1))}}function Cn(a,e,t,i){if(i&&!!e.getIndex()!=!!a.getIndex())throw new Error(`${t}: All geometries must consistently have "index".`);for(const n in a.attributes){if(!e.hasAttribute(n))throw new Error(`${t}: Added geometry missing "${n}". All geometries must have consistent attributes.`);const s=e.getAttribute(n),r=a.getAttribute(n);if(s.itemSize!==r.itemSize||s.normalized!==r.normalized)throw new Error(`${t}: All attributes must have a consistent itemSize and normalized value.`)}}function Si(a,e,t,i){let n,s=t;return a.length>0?(a.sort(Zc),n=a.shift(),e[n]=i):(n=t,s++,e.push(i)),{geometryId:n,geometryCount:s}}function nt(a,e){return a===-1?e:a}function Ai(){return{boundingBox:null,active:!0,visible:!0}}function Ci(a){const{typeName:e,maxVertexCount:t,vertexStart:i,reservedVertexCount:n,maxIndexCount:s,indexStart:r=-1,reservedIndexCount:o=0}=a;if(s!=null&&r!==-1&&r+o>s||i+n>t)throw new Error(`${e}: Reserved space request exceeds the maximum buffer size.`)}function st(a){const{currentMaxCount:e,nextStart:t,requiredCount:i,growthFactor:n}=a,s=t+i;return s<=e?e:Math.ceil(s*n)}function Qc(a,e,t){return a>=e.length||e[a].active===!1?!1:(e[a].active=!1,e[a].visible=!1,t.push(a),!0)}function el(a,e,t){if(a<0||a>=e.length||e[a].active===!1)throw new Error(`${t}: Invalid geometryId ${a}. Geometry is either out of range or has been deleted.`)}function tl(a,e,t,i){for(const n in a.attributes){const s=e.getAttribute(n),r=a.getAttribute(n);Sn(s,r,t);const o=s.itemSize;for(let c=s.count,l=i;c<l;c++){const h=t+c;for(let d=0;d<o;d++)r.setComponent(h,d,0)}r.needsUpdate=!0,r.addUpdateRange(t*o,i*o)}}function il(a,e,t,i,n){const s=a.getIndex(),r=e.getIndex();if(!(!s||!r)){for(let o=0;o<r.count;o++)s.setX(i+o,t+r.getX(o));for(let o=r.count,c=n;o<c;o++)s.setX(i+o,t);s.needsUpdate=!0,s.addUpdateRange(i,n)}}function _n(a,e,t,i){const n=e.getIndex()!==null,s=t.getIndex();if(n&&s&&s.count>a.reservedIndexCount||t.attributes.position.count>a.reservedVertexCount)throw new Error(`${i}: Reserved space not large enough for provided geometry.`);const r=a.vertexStart,o=a.reservedVertexCount;if(a.vertexCount=t.getAttribute("position").count,tl(e,t,r,o),n&&s){const c=a;c.indexCount=s.count,il(e,t,r,c.indexStart,c.reservedIndexCount)}a.boundingBox=null}function nl(a,e){const t=a??new f.Box3;t.makeEmpty();for(let i=0,n=e.length;i<n;i++){const s=e[i];s.active!==!1&&s.boundingBox!=null&&t.union(s.boundingBox)}return t}function sl(a,e,t){const i=a??new f.Sphere;i.makeEmpty();const n=new f.Sphere;for(let s=0,r=e.length;s<r;s++)e[s].active!==!1&&(t(s,n),i.union(n));return i}function rl(a,e,t){a.material=t,a.geometry.index=e.index,a.geometry.attributes=e.attributes,a.geometry.boundingBox===null&&(a.geometry.boundingBox=new f.Box3),a.geometry.boundingSphere===null&&(a.geometry.boundingSphere=new f.Sphere)}function ol(a,e,t,i,n){a.geometry.setDrawRange(e,t),a.geometry.boundingBox.copy(i),a.geometry.boundingSphere.copy(n)}function al(a){a.geometry.index=null,a.geometry.attributes={},a.geometry.setDrawRange(0,1/0)}function _i(a,e){return class extends a{constructor(){super(...arguments),this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._geometryCount=0,this._raycastObject=e.createObject(),this._batchIntersects=[],this._box=new f.Box3,this._sphere=new f.Sphere,this._vector=new f.Vector3,this._typedBatchIntersects=this._batchIntersects}get mappingStats(){return Jc(this._geometryInfo)}validateGeometryId(t){el(t,this._geometryInfo,e.typeName)}computeBoundingBox(){this.boundingBox=nl(this.boundingBox,this._geometryInfo)}computeBoundingSphere(){this.boundingSphere=sl(this.boundingSphere,this._geometryInfo,(t,i)=>this.getBoundingSphereAt(t,i))}setVisibleAt(t,i){return this.validateGeometryId(t),this._geometryInfo[t].visible===i?this:(this._geometryInfo[t].visible=i,this)}getVisibleAt(t){return this.validateGeometryId(t),this._geometryInfo[t].visible}deleteGeometry(t){return Qc(t,this._geometryInfo,this._availableGeometryIds)?this:this}getObjectAt(t){const i=e.createObject();this._initializeRaycastObject(i);const n=this._geometryInfo[t],{start:s,count:r}=e.getDrawRange(this,n);return this._setRaycastObjectInfo(i,t,s,r),i}intersectWith(t,i,n){this._initializeRaycastObject(this._raycastObject),this._intersectWith(t,i,n),this._resetRaycastObjectInfo(this._raycastObject)}raycast(t,i){this._initializeRaycastObject(this._raycastObject);for(let n=0,s=this._geometryInfo.length;n<s;n++)this._intersectWith(n,t,i);this._resetRaycastObjectInfo(this._raycastObject)}dispose(){return this.geometry.dispose(),this}_initializeRaycastObject(t){rl(t,this.geometry,this.material),t.position.copy(this.position),t.quaternion.copy(this.quaternion),t.scale.copy(this.scale),t.updateMatrix(),t.updateMatrixWorld(!0)}_setRaycastObjectInfo(t,i,n,s){const r=this;r.getBoundingBoxAt(i,this._box),r.getBoundingSphereAt(i,this._sphere),ol(t,n,s,this._box,this._sphere)}_resetRaycastObjectInfo(t){al(t)}_intersectWith(t,i,n){const s=this._geometryInfo[t];if(!(!s.visible||!s.active))if(s.bboxIntersectionCheck){if(this.getBoundingBoxAt(t,this._box),this._box.applyMatrix4(this.matrixWorld),i.ray.intersectBox(this._box,this._vector)){const r=i.ray.origin.distanceTo(this._vector);n.push({distance:r,point:this._vector.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:t,objectId:s.objectId})}}else{const{start:r,count:o}=e.getDrawRange(this,s);this._setRaycastObjectInfo(this._raycastObject,t,r,o),this._raycastObject.raycast(i,this._batchIntersects);for(let c=0,l=this._typedBatchIntersects.length;c<l;c++){const h=this._typedBatchIntersects[c];h.object=this,h.batchId=t,h.objectId=s.objectId,n.push(h)}this._batchIntersects.length=0}}}}const rt=new f.Box3,cl=new f.Vector3,Pn=new f.Vector3,ll=_i(f.LineSegments,{typeName:"AcTrBatchedLine",createObject:()=>new f.LineSegments,getDrawRange:(a,e)=>a.geometry.index!=null?{start:e.indexStart,count:e.indexCount}:{start:e.vertexStart,count:e.vertexCount}}),cr=class ss extends ll{constructor(e=1e3,t=e*2,i){super(new f.BufferGeometry,i),this._nextIndexStart=0,this._nextVertexStart=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}_initializeGeometry(e){this._geometryInitialized===!1&&(An(this.geometry,e,this._maxVertexCount,this._maxIndexCount),this._geometryInitialized=!0)}_validateGeometry(e){Cn(this.geometry,e,"AcTrBatchedLine",!0)}_resizeSpaceIfNeeded(e){const t=e.getIndex(),i=t==null?this._maxIndexCount:st({currentMaxCount:this._maxIndexCount,nextStart:this._nextIndexStart,requiredCount:t.count,growthFactor:ss.GROWTH_FACTOR}),n=e.getAttribute("position"),s=n==null?this._maxVertexCount:st({currentMaxCount:this._maxVertexCount,nextStart:this._nextVertexStart,requiredCount:n.count,growthFactor:ss.GROWTH_FACTOR});(i>this._maxIndexCount||s>this._maxVertexCount)&&this.setGeometrySize(s,i)}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._origin=void 0,this.position.set(0,0,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=ze.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)}}})}addGeometry(e,t=-1,i=-1,n=new f.Vector3){this.rebaseGeometryInPlace(e,n),this._initializeGeometry(e),this._validateGeometry(e),this._resizeSpaceIfNeeded(e);const s=e.getAttribute("position").count,r=e.getIndex(),o={vertexStart:this._nextVertexStart,vertexCount:-1,reservedVertexCount:nt(t,s),indexStart:r?this._nextIndexStart:-1,indexCount:-1,reservedIndexCount:r?nt(i,r.count):0,...Ai()};Ci({typeName:"AcTrBatchedLine",maxVertexCount:this._maxVertexCount,vertexStart:o.vertexStart,reservedVertexCount:o.reservedVertexCount,maxIndexCount:this._maxIndexCount,indexStart:o.indexStart,reservedIndexCount:o.reservedIndexCount});const{geometryId:c,geometryCount:l}=Si(this._availableGeometryIds,this._geometryInfo,this._geometryCount,o);return this._geometryCount=l,this.setGeometryAt(c,e),this._nextIndexStart=o.indexStart+o.reservedIndexCount,this._nextVertexStart=o.vertexStart+o.reservedVertexCount,this._syncDrawRange(),c}rebaseGeometryInPlace(e,t){const i=e.getAttribute("position");if(!i)return;if(!this._origin){e.computeBoundingBox();const r=e.boundingBox?e.boundingBox.getCenter(new f.Vector3):new f.Vector3;this._origin=r.add(t.clone()),this.position.copy(this._origin)}const n=this._origin;if(!n)return;const s=i.array;if(s instanceof Float32Array){for(let r=0;r<s.length;r+=3)s[r]=s[r]+t.x-n.x,s[r+1]=s[r+1]+t.y-n.y,s[r+2]=s[r+2]+t.z-n.z;i.needsUpdate=!0;return}for(let r=0;r<i.count;r++)i.setXYZ(r,i.getX(r)+t.x-n.x,i.getY(r)+t.y-n.y,i.getZ(r)+t.z-n.z);i.needsUpdate=!0}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];return _n(n,i,t,"AcTrBatchedLine"),e}optimize(){const e=this.geometry,t=e.index!==null,i=e.attributes,n=e.index;let s=0,r=0;const o=this._geometryInfo.map((c,l)=>({info:c,id:l})).filter(c=>c.info.active).sort((c,l)=>c.info.vertexStart-l.info.vertexStart);for(const{info:c}of o){const l=c.vertexCount,h=t?c.indexCount:0,d=c.vertexStart,g=s,m=g-d;if(m!==0&&l>0)for(const y in i){const w=i[y],{array:C,itemSize:b}=w;C.copyWithin(g*b,d*b,(d+l)*b),w.addUpdateRange(g*b,l*b),w.needsUpdate=!0}if(t&&n&&h>0){const y=c.indexStart,w=r,C=n.array;if(m!==0)for(let b=y;b<y+h;b++)C[b]+=m;y!==w&&C.copyWithin(w,y,y+h),n.addUpdateRange(w,h),n.needsUpdate=!0,c.indexStart=w}c.vertexStart=g,s+=c.reservedVertexCount,r+=c.reservedIndexCount}if(t&&n){const c=n.array;for(let l=r;l<c.length;l++)c[l]=0;n.needsUpdate=!0}return t?e.setDrawRange(0,r):e.setDrawRange(0,s),this._nextVertexStart=s,this._nextIndexStart=r,this._syncDrawRange(),this._availableGeometryIds.length=0,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 f.Box3,r=i.index,o=i.attributes.position,{start:c,count:l}=r!=null?{start:n.indexStart,count:n.indexCount}:{start:n.vertexStart,count:n.vertexCount};for(let h=c,d=c+l;h<d;h++){let g=h;r&&(g=r.getX(g)),s.expandByPoint(cl.fromBufferAttribute(o,g))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){return e>=this._geometryCount?null:(this.getBoundingBoxAt(e,rt),rt.getBoundingSphere(t),t)}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 f.BufferGeometry,this._initializeGeometry(i));const n=this.geometry;i.index&&Xe(i.index.array,n.index.array);for(const s in i.attributes)Xe(i.attributes[s].array,n.attributes[s].array);this._syncDrawRange()}getObjectAt(e){const t=super.getObjectAt(e);return t.position.copy(this.position),t}_initializeRaycastObject(e){super._initializeRaycastObject(e),e.position.copy(this.position),e.updateMatrixWorld(!0)}_syncDrawRange(){const e=this.geometry;e.index?e.setDrawRange(0,this._nextIndexStart):e.setDrawRange(0,this._nextVertexStart)}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!n.active||!n.visible)return;if(n.bboxIntersectionCheck){if(this.getBoundingBoxAt(e,this._box),this._box.applyMatrix4(this.matrixWorld),t.ray.intersectBox(this._box,this._vector)){const r=t.ray.origin.distanceTo(this._vector);i.push({distance:r,point:this._vector.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}return}const s=this.geometry.index!=null?{start:n.indexStart,count:n.indexCount}:{start:n.vertexStart,count:n.vertexCount};if(this._setRaycastObjectInfo(this._raycastObject,e,s.start,s.count),this._raycastObject.raycast(t,this._batchIntersects),this._batchIntersects.length===0){this.getBoundingBoxAt(e,rt),rt.applyMatrix4(this.matrixWorld);const r=t.params.Line.threshold;if(r>0&&rt.expandByScalar(r),t.ray.intersectBox(rt,Pn)){const o=t.ray.origin.distanceTo(Pn);i.push({distance:o,point:Pn.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}return}for(let r=0,o=this._typedBatchIntersects.length;r<o;r++){const c=this._typedBatchIntersects[r];c.object=this,c.batchId=e,c.objectId=n.objectId,i.push(c)}this._batchIntersects.length=0}copy(e){var t;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(i=>({...i,boundingBox:i.boundingBox!==null?i.boundingBox.clone():null})),this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._origin=(t=e._origin)==null?void 0:t.clone(),this}};cr.GROWTH_FACTOR=1.25;let hl=cr;const Ee=new f.Box3,Pi=new f.Vector3,Li=new f.Vector3,Et=[],Ve=new We.LineSegments2(new Fe.LineSegmentsGeometry),ul=_i(We.LineSegments2,{typeName:"AcTrBatchedLine2",createObject:()=>new We.LineSegments2(new Fe.LineSegmentsGeometry),getDrawRange:(a,e)=>({start:e.vertexStart,count:e.vertexCount})}),lr=class ba extends ul{constructor(e=1e3,t){super(new Fe.LineSegmentsGeometry,t),this._nextSegmentStart=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxSegmentCount=e}get geometryCount(){return this._geometryCount}get unusedSegmentCount(){return this._maxSegmentCount-this._nextSegmentStart}_initializeGeometry(e){this._geometryInitialized||(this.geometry.setPositions(new Float32Array(this._maxSegmentCount*6)),this._copyStaticAttributes(e),this._geometryInitialized=!0)}_copyStaticAttributes(e,t=this.geometry){const i=t,n=e.getIndex();n&&i.setIndex(n.clone());for(const s in e.attributes)s==="instanceStart"||s==="instanceEnd"||i.setAttribute(s,e.getAttribute(s).clone())}_validateGeometry(e){const t=e.getAttribute("instanceStart"),i=e.getAttribute("instanceEnd");if(!t||!i)throw new Error('AcTrBatchedLine2: Geometry must have "instanceStart" and "instanceEnd" attributes.');if(t.itemSize!==3||i.itemSize!==3||t.count!==i.count)throw new Error("AcTrBatchedLine2: Invalid line segment attributes. Expected matching vec3 instanceStart/instanceEnd.")}_resizeSpaceIfNeeded(e){const t=e.getAttribute("instanceStart").count,i=st({currentMaxCount:this._maxSegmentCount,nextStart:this._nextSegmentStart,requiredCount:t,growthFactor:ba.GROWTH_FACTOR});i>this._maxSegmentCount&&this.setGeometrySize(i)}reset(){this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextSegmentStart=0,this._geometryCount=0,this._origin=void 0,this.position.set(0,0,0),this._geometryInitialized=!1,this.geometry.dispose()}addGeometry(e,t=-1,i=new f.Vector3){this.rebaseGeometryInPlace(e,i),this._initializeGeometry(e),this._validateGeometry(e),this._resizeSpaceIfNeeded(e);const n=e.getAttribute("instanceStart").count,s={vertexStart:this._nextSegmentStart,vertexCount:-1,reservedVertexCount:nt(t,n),...Ai()};Ci({typeName:"AcTrBatchedLine2",maxVertexCount:this._maxSegmentCount,vertexStart:s.vertexStart,reservedVertexCount:s.reservedVertexCount});const{geometryId:r,geometryCount:o}=Si(this._availableGeometryIds,this._geometryInfo,this._geometryCount,s);return this._geometryCount=o,this.setGeometryAt(r,e),this._nextSegmentStart=s.vertexStart+s.reservedVertexCount,this._syncDrawRange(),r}rebaseGeometryInPlace(e,t){const i=e.getAttribute("instanceStart"),n=e.getAttribute("instanceEnd");if(!i||!n)return;if(!this._origin){e.computeBoundingBox();const r=e.boundingBox?e.boundingBox.getCenter(new f.Vector3):new f.Vector3;this._origin=r.add(t.clone()),this.position.copy(this._origin)}const s=this._origin;if(s){for(let r=0;r<i.count;r++)i.setXYZ(r,i.getX(r)+t.x-s.x,i.getY(r)+t.y-s.y,i.getZ(r)+t.z-s.z),n.setXYZ(r,n.getX(r)+t.x-s.x,n.getY(r)+t.y-s.y,n.getZ(r)+t.z-s.z);i.needsUpdate=!0,n.needsUpdate=!0}}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedLine2: 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("AcTrBatchedLine2: Maximum geometry count reached.");this._validateGeometry(t);const i=this._geometryInfo[e],n=t.getAttribute("instanceStart").count;if(n>i.reservedVertexCount)throw new Error("AcTrBatchedLine2: Reserved space not large enough for provided geometry.");const s=this.geometry.getAttribute("instanceStart"),r=this.geometry.getAttribute("instanceEnd"),o=t.getAttribute("instanceStart"),c=t.getAttribute("instanceEnd"),l=i.vertexStart;Sn(o,s,l),Sn(c,r,l);for(let h=n,d=i.reservedVertexCount;h<d;h++){const g=l+h;for(let m=0;m<3;m++)s.setComponent(g,m,0),r.setComponent(g,m,0)}return s.needsUpdate=!0,r.needsUpdate=!0,i.vertexCount=n,i.boundingBox=null,e}optimize(){const e=this._getPackedSegmentArray();let t=0;const i=this._geometryInfo.map((r,o)=>({info:r,id:o})).filter(r=>r.info.active).sort((r,o)=>r.info.vertexStart-o.info.vertexStart);for(const{info:r}of i){const o=r.vertexStart,c=r.reservedVertexCount;o!==t&&e.copyWithin(t*6,o*6,(o+c)*6),r.vertexStart=t,t+=c}for(let r=t*6,o=e.length;r<o;r++)e[r]=0;this._nextSegmentStart=t,this._syncDrawRange(),this._availableGeometryIds.length=0;const n=this.geometry.getAttribute("instanceStart"),s=this.geometry.getAttribute("instanceEnd");return n.needsUpdate=!0,s.needsUpdate=!0,this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;const i=this._geometryInfo[e];if(i.boundingBox===null){const n=new f.Box3,s=this.geometry.getAttribute("instanceStart"),r=this.geometry.getAttribute("instanceEnd");for(let o=i.vertexStart,c=i.vertexStart+i.vertexCount;o<c;o++)n.expandByPoint(Pi.fromBufferAttribute(s,o)),n.expandByPoint(Li.fromBufferAttribute(r,o));i.boundingBox=n}return t.copy(i.boundingBox),t}getBoundingSphereAt(e,t){return e>=this._geometryCount?null:(this.getBoundingBoxAt(e,Ee),Ee.getBoundingSphere(t),t)}getGeometryAt(e){return this.validateGeometryId(e),this._geometryInfo[e]}setGeometrySize(e){const t=this.geometry,i=this._getPackedSegmentArray();this._maxSegmentCount=e,this.geometry=new Fe.LineSegmentsGeometry,this.geometry.setPositions(new Float32Array(e*6));const n=this._getPackedSegmentArray();Xe(i,n),this._copyStaticAttributes(t),this._geometryInitialized=!0,this._syncDrawRange(),t.dispose()}getObjectAt(e){const t=this._geometryInfo[e],i=this._createSubGeometry(t.vertexStart,t.vertexCount,!0),n=new We.LineSegments2(i,this.material);return n.position.copy(this.position),n.updateMatrix(),n.updateMatrixWorld(!0),this.getBoundingBoxAt(e,n.geometry.boundingBox??new f.Box3),this.getBoundingSphereAt(e,n.geometry.boundingSphere??new f.Sphere),n}intersectWith(e,t,i){this._intersectWith(e,t,i)}raycast(e,t){for(let i=0,n=this._geometryInfo.length;i<n;i++)this._intersectWith(i,e,t)}copy(e){var t;return super.copy(e),this.geometry=e.geometry.clone(),this.boundingBox=e.boundingBox?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(i=>({...i,boundingBox:i.boundingBox?i.boundingBox.clone():null})),this._maxSegmentCount=e._maxSegmentCount,this._geometryCount=e._geometryCount,this._nextSegmentStart=e._nextSegmentStart,this._geometryInitialized=e._geometryInitialized,this._origin=(t=e._origin)==null?void 0:t.clone(),this}dispose(){return this.geometry.dispose(),this}_intersectWith(e,t,i){const n=this._geometryInfo[e];if(!n.active||!n.visible)return;if(n.bboxIntersectionCheck){if(this.getBoundingBoxAt(e,Ee),Ee.applyMatrix4(this.matrixWorld),t.ray.intersectBox(Ee,Pi)){const r=t.ray.origin.distanceTo(Pi);i.push({distance:r,point:Pi.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}return}const s=this._createSubGeometry(n.vertexStart,n.vertexCount,!1);if(Ve.geometry=s,Ve.material=this.material,Ve.position.copy(this.position),Ve.quaternion.copy(this.quaternion),Ve.scale.copy(this.scale),Ve.updateMatrix(),Ve.updateMatrixWorld(!0),Ve.raycast(t,Et),Et.length===0){this.getBoundingBoxAt(e,Ee),Ee.applyMatrix4(this.matrixWorld);const r=t.params.Line.threshold;if(r>0&&Ee.expandByScalar(r),t.ray.intersectBox(Ee,Li)){const o=t.ray.origin.distanceTo(Li);i.push({distance:o,point:Li.clone(),object:this,face:null,faceIndex:void 0,uv:void 0,batchId:e,objectId:n.objectId})}s.dispose();return}for(let r=0,o=Et.length;r<o;r++){const c=Et[r];c.batchId=e,c.objectId=n.objectId,c.object=this,i.push(c)}Et.length=0,s.dispose()}_createSubGeometry(e,t,i){const n=this._getPackedSegmentArray(),s=i?n.slice(e*6,(e+t)*6):n.subarray(e*6,(e+t)*6),r=new Fe.LineSegmentsGeometry;return r.setPositions(s),this._copyStaticAttributes(this.geometry,r),r}_getPackedSegmentArray(){var e;const t=this.geometry.getAttribute("instanceStart");if("data"in t&&(e=t.data)!=null&&e.array)return t.data.array;const i=this.geometry.getAttribute("instanceEnd"),n=t.count,s=new Float32Array(n*6);for(let r=0,o=0;r<n;r++)s[o++]=t.getComponent(r,0),s[o++]=t.getComponent(r,1),s[o++]=t.getComponent(r,2),s[o++]=i.getComponent(r,0),s[o++]=i.getComponent(r,1),s[o++]=i.getComponent(r,2);return s}_syncDrawRange(){this.geometry.instanceCount=this._nextSegmentStart}};lr.GROWTH_FACTOR=1.25;let hr=lr;const ur=new f.Box3,dl=new f.Vector3,pl=_i(f.Mesh,{typeName:"AcTrBatchedMesh",createObject:()=>new f.Mesh,getDrawRange:(a,e)=>a.geometry.index!=null?{start:e.indexStart,count:e.indexCount}:{start:e.vertexStart,count:e.vertexCount}}),dr=class rs extends pl{constructor(e=1e3,t=e*2,i){super(new f.BufferGeometry,i),this._nextIndexStart=0,this._nextVertexStart=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}_initializeGeometry(e){this._geometryInitialized===!1&&(An(this.geometry,e,this._maxVertexCount,this._maxIndexCount),this._geometryInitialized=!0)}_validateGeometry(e){Cn(this.geometry,e,"AcTrBatchedMesh",!0)}_resizeSpaceIfNeeded(e){const t=e.getIndex(),i=t==null?this._maxIndexCount:st({currentMaxCount:this._maxIndexCount,nextStart:this._nextIndexStart,requiredCount:t.count,growthFactor:rs.GROWTH_FACTOR}),n=e.getAttribute("position"),s=n==null?this._maxVertexCount:st({currentMaxCount:this._maxVertexCount,nextStart:this._nextVertexStart,requiredCount:n.count,growthFactor:rs.GROWTH_FACTOR});(i>this._maxIndexCount||s>this._maxVertexCount)&&this.setGeometrySize(s,i)}addGeometry(e,t=-1,i=-1,n=new f.Vector3){this.rebaseGeometryInPlace(e,n),e.hasAttribute("uv")&&e.deleteAttribute("uv"),e.hasAttribute("normal")&&e.deleteAttribute("normal"),this._initializeGeometry(e),this._validateGeometry(e),this._resizeSpaceIfNeeded(e);const s=e.getAttribute("position").count,r=e.getIndex(),o={vertexStart:this._nextVertexStart,vertexCount:-1,reservedVertexCount:nt(t,s),indexStart:r?this._nextIndexStart:-1,indexCount:-1,reservedIndexCount:r?nt(i,r.count):0,...Ai()};Ci({typeName:"AcTrBatchedMesh",maxVertexCount:this._maxVertexCount,vertexStart:o.vertexStart,reservedVertexCount:o.reservedVertexCount,maxIndexCount:this._maxIndexCount,indexStart:o.indexStart,reservedIndexCount:o.reservedIndexCount});const{geometryId:c,geometryCount:l}=Si(this._availableGeometryIds,this._geometryInfo,this._geometryCount,o);return this._geometryCount=l,this.setGeometryAt(c,e),this._nextIndexStart=o.indexStart+o.reservedIndexCount,this._nextVertexStart=o.vertexStart+o.reservedVertexCount,this._syncDrawRange(),c}rebaseGeometryInPlace(e,t){const i=e.getAttribute("position");if(!i)return;if(!this._origin){e.computeBoundingBox();const r=e.boundingBox?e.boundingBox.getCenter(new f.Vector3):new f.Vector3;this._origin=r.add(t.clone()),this.position.copy(this._origin)}const n=this._origin;if(!n)return;const s=i.array;if(s instanceof Float32Array){for(let r=0;r<s.length;r+=3)s[r]=s[r]+t.x-n.x,s[r+1]=s[r+1]+t.y-n.y,s[r+2]=s[r+2]+t.z-n.z;i.needsUpdate=!0;return}for(let r=0;r<i.count;r++)i.setXYZ(r,i.getX(r)+t.x-n.x,i.getY(r)+t.y-n.y,i.getZ(r)+t.z-n.z);i.needsUpdate=!0}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=this._geometryInfo[e];return _n(n,i,t,"AcTrBatchedMesh"),e}optimize(){const e=this.geometry,t=e.index!==null,i=e.attributes,n=e.index;let s=0,r=0;const o=this._geometryInfo.map((c,l)=>({info:c,i:l})).filter(c=>c.info.active).sort((c,l)=>c.info.vertexStart-l.info.vertexStart);for(const{info:c}of o){const l=c.vertexCount,h=t?c.indexCount:0,d=c.vertexStart,g=c.indexStart;if(d!==s){for(const m in i){const y=i[m],{array:w,itemSize:C}=y;w.copyWithin(s*C,d*C,(d+l)*C),y.addUpdateRange(s*C,l*C),y.needsUpdate=!0}c.vertexStart=s}if(t&&n&&g!==r){const m=n.array,y=s-d;for(let w=0;w<h;w++)m[r+w]=m[g+w]+y;n.addUpdateRange(r,h),n.needsUpdate=!0,c.indexStart=r}s+=l,r+=h}if(t&&n){const c=n.array;for(let l=r,h=c.length;l<h;l++)c[l]=0;n.needsUpdate=!0}return this._nextVertexStart=s,this._nextIndexStart=r,this._syncDrawRange(),this._availableGeometryIds.length=0,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 f.Box3,r=i.index,o=i.attributes.position,{start:c,count:l}=r!=null?{start:n.indexStart,count:n.indexCount}:{start:n.vertexStart,count:n.vertexCount};for(let h=c,d=c+l;h<d;h++){let g=h;r&&(g=r.getX(g)),s.expandByPoint(dl.fromBufferAttribute(o,g))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){return e>=this._geometryCount?null:(this.getBoundingBoxAt(e,ur),ur.getBoundingSphere(t),t)}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 f.BufferGeometry,this._initializeGeometry(i));const n=this.geometry;i.index&&Xe(i.index.array,n.index.array);for(const s in i.attributes)Xe(i.attributes[s].array,n.attributes[s].array);this._syncDrawRange()}_syncDrawRange(){const e=this.geometry;e.index?e.setDrawRange(0,this._nextIndexStart):e.setDrawRange(0,this._nextVertexStart)}copy(e){var t;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(i=>({...i,boundingBox:i.boundingBox!==null?i.boundingBox.clone():null})),this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._origin=(t=e._origin)==null?void 0:t.clone(),this}};dr.GROWTH_FACTOR=1.25;let gl=dr;const pr=new f.Box3,ml=new f.Vector3,yl=_i(f.Points,{typeName:"AcTrBatchedPoint",createObject:()=>new f.Points,getDrawRange:(a,e)=>({start:e.vertexStart,count:e.vertexCount})}),gr=class xa extends yl{constructor(e=1e3,t){super(new f.BufferGeometry,t),this._nextVertexStart=0,this._geometryInitialized=!1,this.frustumCulled=!1,this._maxVertexCount=e}get geometryCount(){return this._geometryCount}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}_initializeGeometry(e){this._geometryInitialized===!1&&(An(this.geometry,e,this._maxVertexCount,null),this._geometryInitialized=!0)}_validateGeometry(e){Cn(this.geometry,e,"AcTrBatchedPoint",!1)}_resizeSpaceIfNeeded(e){const t=e.getAttribute("position"),i=t==null?this._maxVertexCount:st({currentMaxCount:this._maxVertexCount,nextStart:this._nextVertexStart,requiredCount:t.count,growthFactor:xa.GROWTH_FACTOR});i>this._maxVertexCount&&this.setGeometrySize(i)}reset(){this.boundingBox=null,this.boundingSphere=null,this._geometryInfo=[],this._availableGeometryIds=[],this._nextVertexStart=0,this._geometryCount=0,this._geometryInfo.length=0,this._origin=void 0,this.position.set(0,0,0),this._geometryInitialized=!1,this.geometry.dispose()}addGeometry(e,t=-1,i=new f.Vector3){this.rebaseGeometryInPlace(e,i),this._initializeGeometry(e),this._validateGeometry(e),this._resizeSpaceIfNeeded(e);const n=e.getAttribute("position").count,s={vertexStart:this._nextVertexStart,vertexCount:-1,reservedVertexCount:nt(t,n),...Ai()};Ci({typeName:"AcTrBatchedPoint",maxVertexCount:this._maxVertexCount,vertexStart:s.vertexStart,reservedVertexCount:s.reservedVertexCount});const{geometryId:r,geometryCount:o}=Si(this._availableGeometryIds,this._geometryInfo,this._geometryCount,s);return this._geometryCount=o,this.setGeometryAt(r,e),this._nextVertexStart=s.vertexStart+s.reservedVertexCount,this.geometry.setDrawRange(0,this._nextVertexStart),this._syncDrawRange(),r}rebaseGeometryInPlace(e,t){const i=e.getAttribute("position");if(!i)return;if(!this._origin){e.computeBoundingBox();const r=e.boundingBox?e.boundingBox.getCenter(new f.Vector3):new f.Vector3;this._origin=r.add(t.clone()),this.position.copy(this._origin)}const n=this._origin;if(!n)return;const s=i.array;if(s instanceof Float32Array){for(let r=0;r<s.length;r+=3)s[r]=s[r]+t.x-n.x,s[r+1]=s[r+1]+t.y-n.y,s[r+2]=s[r+2]+t.z-n.z;i.needsUpdate=!0;return}for(let r=0;r<i.count;r++)i.setXYZ(r,i.getX(r)+t.x-n.x,i.getY(r)+t.y-n.y,i.getZ(r)+t.z-n.z);i.needsUpdate=!0}setGeometryInfo(e,t){if(e>=this._geometryCount)throw new Error("AcTrBatchedPoint: 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("AcTrBatchedPoint: Maximum geometry count reached.");this._validateGeometry(t);const i=this.geometry,n=this._geometryInfo[e];return _n(n,i,t,"AcTrBatchedPoint"),e}optimize(){let e=0;const t=this.geometry,i=this._geometryInfo,n=i.map((s,r)=>r).filter(s=>i[s].active).sort((s,r)=>i[s].vertexStart-i[r].vertexStart);for(let s=0;s<n.length;s++){const r=n[s],o=i[r],c=o.vertexStart,l=o.reservedVertexCount;if(c!==e){for(const h in t.attributes){const d=t.attributes[h],{array:g,itemSize:m}=d;g.copyWithin(e*m,c*m,(c+l)*m),d.addUpdateRange(e*m,l*m),d.needsUpdate=!0}o.vertexStart=e}e+=l}return this._nextVertexStart=e,this._syncDrawRange(),this._availableGeometryIds.length=0,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 f.Box3,r=i.index,o=i.attributes.position;for(let c=n.vertexStart,l=n.vertexStart+n.vertexCount;c<l;c++){let h=c;r&&(h=r.getX(h)),s.expandByPoint(ml.fromBufferAttribute(o,h))}n.boundingBox=s}return t.copy(n.boundingBox),t}getBoundingSphereAt(e,t){return e>=this._geometryCount?null:(this.getBoundingBoxAt(e,pr),pr.getBoundingSphere(t),t)}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 f.BufferGeometry,this._initializeGeometry(t));const i=this.geometry;t.index&&Xe(t.index.array,i.index.array);for(const n in t.attributes)Xe(t.attributes[n].array,i.attributes[n].array);this._syncDrawRange()}_syncDrawRange(){this.geometry.setDrawRange(0,this._nextVertexStart)}copy(e){var t;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(i=>({...i,boundingBox:i.boundingBox!==null?i.boundingBox.clone():null})),this._maxVertexCount=e._maxVertexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._origin=(t=e._origin)==null?void 0:t.clone(),this}};gr.GROWTH_FACTOR=1.25;let fl=gr;const ot=class et extends f.Group{constructor(){super(),this._pointBatches=new Map,this._pointSymbolBatches=new Map,this._lineBatches=new Map,this._lineWithIndexBatches=new Map,this._line2Batches=new Map,this._meshBatches=new Map,this._meshWithIndexBatches=new Map,this._entitiesMap=new Map,this._unbatchedEntities=new Map,this._unbatchedObjects=new f.Group,this._selectedObjects=new f.Group,this._hoverObjects=new f.Group,this.add(this._unbatchedObjects),this.add(this._selectedObjects),this.add(this._hoverObjects)}get entityCount(){return this._entitiesMap.size}get stats(){const e=this.getUnbatchedStats(),t={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+this._line2Batches.size,geometrySize:this.getBatchedGeometrySize(this._lineBatches)+this.getBatchedGeometrySize(this._line2Batches),mappingSize:this.getBatchedGeometryMappingSize(this._lineBatches)+this.getBatchedGeometryMappingSize(this._line2Batches)}},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)}},unbatched:e};return t.summary.totalGeometrySize=t.line.indexed.geometrySize+t.line.nonIndexed.geometrySize+t.mesh.indexed.geometrySize+t.mesh.nonIndexed.geometrySize+t.point.indexed.geometrySize+t.point.nonIndexed.geometrySize+t.unbatched.geometrySize,t.summary.totalMappingSize=t.line.indexed.mappingSize+t.line.nonIndexed.mappingSize+t.mesh.indexed.mappingSize+t.mesh.nonIndexed.mappingSize+t.point.indexed.mappingSize+t.point.nonIndexed.mappingSize,t}rerenderPoints(e){const t=ze.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.groups.forEach(e=>{e.forEach(t=>{t.dispose(),t.removeFromParent()}),e.clear()}),this.clearHighlightGroup(this._selectedObjects),this.clearHighlightGroup(this._hoverObjects),this._unbatchedObjects.children.forEach(e=>{this.disposeObject(e)}),this._unbatchedObjects.clear(),this._unbatchedEntities.clear(),this._entitiesMap.clear(),this}updateMaterial(e,t){this.groups.forEach(i=>{const n=i.get(e);n&&(n.material=t,i.set(t.id,n))}),this._unbatchedObjects.traverse(i=>{"material"in i&&i.userData.styleMaterialId===e&&(i.material=t,i.userData.styleMaterialId=t.id)})}hasEntity(e){return this._entitiesMap.has(e)}addEntity(e){const t=e.objectId;let i=this._entitiesMap.get(t);i||(i=[],this._entitiesMap.set(t,i));const n=this._unbatchedEntities.get(t)??[];let s=!1;const r=e.styleManager;e.updateMatrixWorld(!0),e.traverse(o=>{const c=!!o.userData.bboxIntersectionCheck;if(o instanceof We.LineSegments2){i.push(this.addLine2(o,{objectId:t,bboxIntersectionCheck:c}));return}if(o.userData[re.NO_BATCH_FLAG]){const l=this.cloneUnbatchedObject(o);l.userData.bboxIntersectionCheck=c,this._unbatchedObjects.add(l),n.push(l),s=!0;return}o instanceof f.LineSegments?i.push(this.addLine(o,{position:o.userData.position,objectId:t,bboxIntersectionCheck:c})):o instanceof f.Mesh?i.push(this.addMesh(o,{objectId:t,bboxIntersectionCheck:c},r)):o instanceof f.Points&&i.push(this.addPoint(o,{objectId:t,bboxIntersectionCheck:c}))}),s&&this._unbatchedEntities.set(t,n)}removeEntity(e){let t=!1;const i=this._entitiesMap.get(e);if(i){const s=new Map;for(let r=0,o=i.length;r<o;r++){const c=i[r],l=this.getObjectById(c.batchedObjectId);l&&(l.deleteGeometry(c.batchId),s.set(c.batchedObjectId,l),t=!0)}s.forEach(r=>r.optimize()),this.unhighlight(e,this._selectedObjects),this._entitiesMap.delete(e)}const n=this._unbatchedEntities.get(e);return n&&(this.unhighlight(e,this._selectedObjects),this.unhighlight(e,this._hoverObjects),n.forEach(s=>{this.disposeObject(s),this._unbatchedObjects.remove(s)}),this._unbatchedEntities.delete(e),t=!0),t}isIntersectWith(e,t){const i=this._entitiesMap.get(e);if(i){const s=[];for(let r=0,o=i.length;r<o;r++){const c=i[r],l=this.getObjectById(c.batchedObjectId);if(l&&(l.intersectWith(c.batchId,t,s),s.length>0))return!0}}const n=this._unbatchedEntities.get(e);if(n)for(let s=0;s<n.length;s++){const r=n[s];if(t.intersectObject(r,!0).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)}get groups(){return[this._lineBatches,this._lineWithIndexBatches,this._line2Batches,this._meshBatches,this._meshWithIndexBatches,this._pointBatches,this._pointSymbolBatches]}highlight(e,t){const i=this._entitiesMap.get(e);i&&i.length<1e3&&i.forEach(s=>{const r=this.getObjectById(s.batchedObjectId),o=r.getObjectAt(s.batchId),c=ue.cloneMaterial(o.material);ue.setMaterialColor(c),o.material=c,o.userData.objectId=e,o.userData.disposeGeometryOnRemove=r instanceof hr,t.add(o)});const n=this._unbatchedEntities.get(e);n&&n.length<1e3&&n.forEach(s=>{const r=s.clone();if(this.hasMaterial(r)){const o=ue.cloneMaterial(r.material);ue.setMaterialColor(o),r.material=o}r.userData.objectId=e,t.add(r)})}applyHighlightMaterial(e){if(this.hasMaterial(e)){const t=ue.cloneMaterial(e.material);ue.setMaterialColor(t),e.material=t}e.children.forEach(t=>this.applyHighlightMaterial(t))}unhighlight(e,t){const i=[];t.children.forEach(n=>{n.userData.objectId===e&&i.push(n)}),i.forEach(n=>this.disposeHighlightObject(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 hl(et.INITIAL_LINE_VERTEX_CAPACITY,et.INITIAL_LINE_INDEX_CAPACITY,i),n.set(i.id,s),this.add(s));const r=e.geometry.clone(),o=e.matrixWorld.clone(),c=new f.Vector3().setFromMatrixPosition(e.matrixWorld);o.setPosition(0,0,0),r.applyMatrix4(o);const l=s.addGeometry(r,-1,-1,c);return s.setGeometryInfo(l,t),r.dispose(),{batchedObjectId:s.id,batchId:l}}addLine2(e,t){const i=e.material;let n=this._line2Batches.get(i.id);n==null&&(n=new hr(et.INITIAL_LINE_VERTEX_CAPACITY,i),this._line2Batches.set(i.id,n),this.add(n));const s=e.matrixWorld.clone(),r=new f.Vector3().setFromMatrixPosition(e.matrixWorld);s.setPosition(0,0,0);const o=this.cloneLineSegments2Geometry(e,s),c=n.addGeometry(o,-1,r);return n.setGeometryInfo(c,t),o.dispose(),{batchedObjectId:n.id,batchId:c}}addMesh(e,t,i){let n=e.material;e.matrixWorld.determinant()<0&&(n=i.getBackSideVariant(n),e.material=n);const s=this.getMatchedMeshBatches(e);let r=s.get(n.id);if(r==null){const d=Ie(n).drawOrder??0;r=new gl(et.INITIAL_MESH_VERTEX_CAPACITY,et.INITIAL_MESH_INDEX_CAPACITY,n),r.renderOrder=d,s.set(n.id,r),this.add(r)}const o=e.geometry.clone(),c=e.matrixWorld.clone(),l=new f.Vector3().setFromMatrixPosition(e.matrixWorld);c.setPosition(0,0,0),o.applyMatrix4(c);const h=r.addGeometry(o,-1,-1,l);return r.setGeometryInfo(h,t),o.dispose(),{batchedObjectId:r.id,batchId:h}}addPoint(e,t){const i=e.material;let n=this._pointBatches.get(i.id);n==null&&(n=new fl(et.INITIAL_POINT_VERTEX_CAPACITY,i),n.visible=e.visible,this._pointBatches.set(i.id,n),this.add(n));const s=e.geometry.clone(),r=e.matrixWorld.clone(),o=new f.Vector3().setFromMatrixPosition(e.matrixWorld);r.setPosition(0,0,0),s.applyMatrix4(r);const c=n.addGeometry(s,-1,o);return n.setGeometryInfo(c,t),s.dispose(),{batchedObjectId:n.id,batchId:c}}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}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){const t=new Set;let i=0;if(this.hasGeometry(e)){const n=e.geometry;if(Object.keys(n.attributes).forEach(s=>{const r=n.attributes[s],o=this.getAttributeArray(r);o&&!t.has(o.buffer)&&(i+=o.byteLength,t.add(o.buffer))}),n.index){const s=n.index.array;t.has(s.buffer)||(i+=s.byteLength,t.add(s.buffer))}}return i}getUnbatchedStats(){const e={count:0,geometrySize:0,byType:{line:0,mesh:0,point:0,other:0}};return this._unbatchedObjects.children.forEach(t=>{e.count+=1,e.geometrySize+=this.getGeometrySize(t),this.isLineObject(t)?e.byType.line+=1:t instanceof f.Mesh?e.byType.mesh+=1:t instanceof f.Points?e.byType.point+=1:e.byType.other+=1}),e}cloneUnbatchedObject(e){const t=e.clone();if(this.hasGeometry(e)&&this.hasGeometry(t)){const i=e.geometry.clone();i.applyMatrix4(e.matrixWorld),t.geometry=i}return this.hasMaterial(e)&&this.hasMaterial(t)&&(t.material=e.material,t.userData.styleMaterialId=e.userData.styleMaterialId??this.getMaterialId(e.material)),t.position.set(0,0,0),t.rotation.set(0,0,0),t.scale.set(1,1,1),t.updateMatrix(),t.updateMatrixWorld(!0),t}cloneLineSegments2Geometry(e,t){const i=e.geometry,n=i.getAttribute("instanceStart"),s=i.getAttribute("instanceEnd"),r=n.count,o=new Float32Array(r*6);for(let l=0,h=0;l<r;l++)Ti.fromBufferAttribute(n,l).applyMatrix4(t),Ii.fromBufferAttribute(s,l).applyMatrix4(t),o[h++]=Ti.x,o[h++]=Ti.y,o[h++]=Ti.z,o[h++]=Ii.x,o[h++]=Ii.y,o[h++]=Ii.z;const c=new Fe.LineSegmentsGeometry;return c.setPositions(o),i.hasAttribute("instanceColorStart")&&(c.setAttribute("instanceColorStart",i.getAttribute("instanceColorStart").clone()),c.setAttribute("instanceColorEnd",i.getAttribute("instanceColorEnd").clone())),c.computeBoundingBox(),c.computeBoundingSphere(),c}disposeObject(e){e.removeFromParent(),this.hasGeometry(e)&&e.geometry.dispose(),e.children.forEach(t=>this.disposeObject(t))}clearHighlightGroup(e){[...e.children].forEach(t=>this.disposeHighlightObject(t)),e.clear()}disposeHighlightObject(e){if(this.hasMaterial(e)){const t=e.material;Array.isArray(t)?t.forEach(i=>i.dispose()):t.dispose()}this.hasGeometry(e)&&e.userData.disposeGeometryOnRemove&&e.geometry.dispose()}hasMaterial(e){return"material"in e}hasGeometry(e){return"geometry"in e}getAttributeArray(e){return"array"in e&&e.array?e.array:"data"in e&&e.data&&e.data.array?e.data.array:null}isLineObject(e){return e instanceof f.Line?!0:!!e.isLineSegments2}getMaterialId(e){var t;return Array.isArray(e)?((t=e[0])==null?void 0:t.id)??-1:e.id}};ot.INITIAL_LINE_VERTEX_CAPACITY=128,ot.INITIAL_LINE_INDEX_CAPACITY=256,ot.INITIAL_MESH_VERTEX_CAPACITY=128,ot.INITIAL_MESH_INDEX_CAPACITY=256,ot.INITIAL_POINT_VERTEX_CAPACITY=16;let wl=ot;const Ti=new f.Vector3,Ii=new f.Vector3;class bl{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()}screenToWorld(e,t,i){const n=new f.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 u.AcGePoint2d(s.x,s.y)}worldToScreen(e,t,i){const n=new f.Vector3(e.x,e.y,0).project(this._camera);return new u.AcGePoint2d((n.x+1)/2*t,(-n.y+1)/2*i)}wcs2Ndc(e,t,i){const n=this.worldToScreen(e,t,i);return this.cwcs2Ndc(n,t,i)}cwcs2Ndc(e,t,i){return new u.AcGePoint2d(e.x/t*2-1,-(e.y/i)*2+1)}}class mr{constructor(e,t,i){this._frustum=400,this.events={viewChanged:new u.AcCmEventManager},this._renderer=e,this._width=t,this._height=i;const n=this.createCamera();this._camera=new bl(n),this._cameraControls=this.createCameraControls(),this._cameraControls.addEventListener("change",()=>{this.events.viewChanged.dispatch({view:this})}),this._raycaster=new f.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.screenToWorld({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()}screenToWorld(e){return this._camera.screenToWorld(e,this._width,this._height)}worldToScreen(e){return this._camera.worldToScreen(e,this._width,this._height)}pointToBox(e,t){const i=this.worldToScreen(e),n=this.screenToWorld({x:i.x+t,y:i.y+t}),s=this.screenToWorld({x:i.x-t,y:i.y-t});return new u.AcGeBox2d().setFromPoints([n,s])}resetRaycaster(e,t){const i=this._camera.wcs2Ndc(e,this._width,this._height);return this._raycaster.setFromCamera(new f.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 u.AcGeVector2d;e.getSize(i);const n=new u.AcGeVector2d;e.getCenter(n);const s=i.x*t,r=i.y*t,o=this._width/s,c=this._height/r,l=Math.min(o,c);this.flyTo(n,l),this.updateCameraFrustum()}flyTo(e,t){const i=new f.Vector3(e.x,e.y,0);this._camera.position.set(e.x,e.y,this._camera.position.z),this._camera.lookAt(i),this._camera.setRotationFromEuler(new f.Euler(0,0,0)),this._cameraControls.target=i,t!=null&&(this._camera.zoom=t),this._camera.updateProjectionMatrix()}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 f.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 Aa.OrbitControls(this._camera.internalCamera,this._renderer.domElement);return e.enableDamping=!1,e.autoRotate=!1,e.enableRotate=!1,e.zoomSpeed=5,e.zoomToCursor=!0,e.mouseButtons={MIDDLE:f.MOUSE.PAN},e.touches={ONE:f.TOUCH.PAN,TWO:f.TOUCH.DOLLY_PAN},e.update(),e}}class Ge extends mr{static calculateViewportWindowBox(e,t){const i=t.box,n=new u.AcGeBox2d;return n.expandByPoint(e.worldToScreen(i.min)),n.expandByPoint(e.worldToScreen(i.max)),n}static isDefaultPaperSpaceViewport(e){if(e.number===1)return!0;const t=1e-6;return Math.abs(e.centerPoint.x-e.viewCenter.x)<t&&Math.abs(e.centerPoint.y-e.viewCenter.y)<t}constructor(e,t,i){const n=Ge.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,1)}containsPaperPoint(e){const t=this._viewport.box;return e.x>=t.min.x&&e.x<=t.max.x&&e.y>=t.min.y&&e.y<=t.max.y}isNearPaperBorder(e,t){if(!this.containsPaperPoint(e))return!1;const i=this._viewport.box,n=Math.abs(e.x-i.min.x),s=Math.abs(e.x-i.max.x),r=Math.abs(e.y-i.min.y),o=Math.abs(e.y-i.max.y);return Math.min(n,s,r,o)<=t}paperPointToModel(e){const t=this._viewport.box,i=this._viewport.viewBox,n=t.max.x-t.min.x,s=t.max.y-t.min.y;if(n<=0||s<=0)return new u.AcGePoint2d((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2);const r=(e.x-t.min.x)/n,o=(e.y-t.min.y)/s;return new u.AcGePoint2d(i.min.x+r*(i.max.x-i.min.x),i.min.y+o*(i.max.y-i.min.y))}get paperToModelScale(){const e=this._viewport.box,t=this._viewport.viewBox,i=e.max.x-e.min.x;return i<=0?1:(t.max.x-t.min.x)/i}render(e){const t=Ge.calculateViewportWindowBox(this._parentView,this._viewport);if(!t.isEmpty()){const i=t.size.width,n=t.size.height;(i!==this._width||n!==this._height)&&(this._width=i,this._height=n,this._frustum=n/2,this.zoomTo(this._viewport.viewBox,1));const s=this._parentView.height-t.min.y-n;this._renderer.setViewport(t.min.x,s,i,n),this._renderer.internalRenderer.setScissor(t.min.x,s,i,n),this._renderer.internalRenderer.setScissorTest(!0),this._renderer.render(e,this._camera),this._renderer.internalRenderer.setScissorTest(!1)}}}class yr{convert(){const e=S.instance.curDocument,t=e.database.dxfOut(void 0,6),i=this.getBaseName(e.fileName||e.docTitle);this.createFileAndDownloadIt(t,`${i}.dxf`)}createFileAndDownloadIt(e,t){const i=new Blob([e],{type:"application/dxf;charset=utf-8"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}getBaseName(e){return((e==null?void 0:e.trim())||"drawing").replace(/\.[^.]+$/,"")||"drawing"}}class fr extends N{async execute(e){new yr().convert()}}class wr{convert(e,t){const i=S.instance.curView,n=i.renderer.internalRenderer,s=i.internalScene,r=i.internalCamera;if(!s||!r){console.error("[PNGOUT] Scene or camera not available");return}const o=i.width/Math.max(i.height,1),c=e?this.getBoundsAspect(e):o;let l=Math.max(1,Math.round(i.width)),h=Math.max(1,Math.round(i.height));if(t&&t>0){const O=this.resolveOutputSize(t,c);l=O.width,h=O.height}const d=this.resolveRenderSizeForCenterCrop(l,h,o),g=d.width,m=d.height,y=g!==l||m!==h,w=r.zoom,C=r.position.clone();if(e){const O=new u.AcGeVector2d;e.getSize(O);const k=new u.AcGeVector2d;e.getCenter(k);const E=Math.max(Math.abs(O.x),Number.EPSILON),M=Math.max(Math.abs(O.y),Number.EPSILON),F=i.width/E,z=i.height/M,U=Math.min(F,z);r.position.set(k.x,k.y,r.position.z),r.zoom=U,r.updateProjectionMatrix()}const b=new f.WebGLRenderTarget(g,m,{minFilter:f.LinearFilter,magFilter:f.LinearFilter,format:f.RGBAFormat,type:f.UnsignedByteType}),x=n.getRenderTarget();n.setRenderTarget(b),n.render(s,r);const A=new Uint8Array(g*m*4);n.readRenderTargetPixels(b,0,0,g,m,A),n.setRenderTarget(x),b.dispose(),r.zoom=w,r.position.copy(C),r.updateProjectionMatrix();const _=this.flipPixelsVertically(A,g,m),L=y?this.cropPixelsCentered(_,g,m,l,h):_,T=this.createCanvasFromPixels(L,l,h);this.createFileAndDownloadIt(T)}resolveOutputSize(e,t){const i=Math.max(1,Math.round(e)),n=Number.isFinite(t)&&t>Number.EPSILON?t:1;return n>=1?{width:i,height:Math.max(1,Math.round(i/n))}:{width:Math.max(1,Math.round(i*n)),height:i}}resolveRenderSizeForCenterCrop(e,t,i){const n=Number.isFinite(i)&&i>Number.EPSILON?i:1,s=e/Math.max(t,1);return Math.abs(s-n)<1e-6?{width:e,height:t}:n>s?{width:Math.max(e,Math.ceil(t*n)),height:t}:{width:e,height:Math.max(t,Math.ceil(e/n))}}cropPixelsCentered(e,t,i,n,s){if(t===n&&i===s)return e;const r=Math.floor((t-n)/2),o=Math.floor((i-s)/2),c=new Uint8Array(n*s*4);for(let l=0;l<s;l++){const h=((l+o)*t+r)*4,d=h+n*4,g=l*n*4;c.set(e.subarray(h,d),g)}return c}getBoundsAspect(e){const t=new u.AcGeVector2d;e.getSize(t);const i=Math.max(Math.abs(t.x),Number.EPSILON),n=Math.max(Math.abs(t.y),Number.EPSILON);return i/n}flipPixelsVertically(e,t,i){const n=new Uint8Array(t*i*4);for(let s=0;s<i;s++){const r=(i-1-s)*t*4,o=s*t*4;for(let c=0;c<t*4;c++)n[o+c]=e[r+c]}return n}createCanvasFromPixels(e,t,i){const n=document.createElement("canvas");n.width=t,n.height=i;const s=n.getContext("2d"),r=s.createImageData(t,i);return r.data.set(e),s.putImageData(r,0,0),n}createFileAndDownloadIt(e){const t=e.toDataURL("image/png"),i=document.createElement("a");i.href=t,i.download=`cad-export-${Date.now()}.png`,document.body.appendChild(i),i.click(),document.body.removeChild(i)}}const Ln=1024;class br extends N{async execute(e){const t=new wr,i=S.instance.curView;this.syncActiveLayoutViewSize(i);const n=new ti(p.t("jig.pngout.boundsFirstCorner"),p.t("jig.pngout.boundsSecondCorner"));n.disableOSnap=!0;const s=await S.instance.editor.getBox(n);let r;if(s.status===v.OK&&s.value)r=this.expandBoundsToEntityExtents(s.value,i).bounds;else if(s.status===v.None)r=this.getCurrentDrawingBounds();else return;const o=new X(`${p.t("jig.pngout.longSidePrompt")} <${Ln}>`);o.allowNone=!0,o.allowNegative=!1,o.allowZero=!1,o.defaultValue=Ln,o.useDefaultValue=!0;const c=await S.instance.editor.getDouble(o);if(c.status===v.Cancel||c.status===v.Error)return;const l=c.status===v.OK&&c.value!==void 0?c.value:Ln;t.convert(r,l)}getCurrentDrawingBounds(){const t=S.instance.curDocument.database.extents;return new u.AcGeBox2d(new u.AcGePoint2d(t.min.x,t.min.y),new u.AcGePoint2d(t.max.x,t.max.y))}expandBoundsToEntityExtents(e,t){const i=t.search(e),n=new u.AcGeBox2d;let s=!1;const r=l=>{var h;n.expandByPoint(new u.AcGePoint2d(l.minX,l.minY)),n.expandByPoint(new u.AcGePoint2d(l.maxX,l.maxY)),s=!0,(h=l.children)==null||h.forEach(d=>{n.expandByPoint(new u.AcGePoint2d(d.minX,d.minY)),n.expandByPoint(new u.AcGePoint2d(d.maxX,d.maxY))})};if(i.forEach(l=>r(l)),!s||n.isEmpty())return{bounds:e,expanded:!1};const o=new u.AcGeBox2d().expandByPoint(e.min).expandByPoint(e.max).expandByPoint(n.min).expandByPoint(n.max),c=o.min.x!==e.min.x||o.min.y!==e.min.y||o.max.x!==e.max.x||o.max.y!==e.max.y;return{bounds:o,expanded:c}}syncActiveLayoutViewSize(e){const t=e.activeLayoutView;t&&t.resize(e.width,e.height)}}class ke{constructor(){this._objectId="",this._ownerId="",this._layerName="",this._visible=!0,this._userData={},this._box=new u.AcGeBox2d,this._svg=""}get box(){return this._box}set box(e){this._box.copy(e)}get basePoint(){return this._basePoint}set basePoint(e){e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(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}addChild(e){}bakeTransformToChildren(){}}const xl=32;class vl extends ke{constructor(e){super();const t=e.getPoints(xl);let i="";for(const n of t){if(n.length===0)continue;const[s,...r]=n;i+=`M${s.x},${s.y}`;for(const o of r)i+=` L${o.x},${o.y}`;i+=" Z";for(const o of n)this._box.expandByPoint(o)}this.svg=`<path d="${i}" fill-rule="evenodd"/>`}}class Sl extends ke{constructor(e){if(super(),e.closed)this.svg=`
|
|
840
|
-
<
|
|
841
|
-
<
|
|
842
|
-
<
|
|
843
|
-
<
|
|
844
|
-
|
|
845
|
-
`)}}class Ll extends ke{constructor(e,t){super();const{text:i,height:n,position:s,rotation:r}=e,o=s.x,c=s.y,l=i.replace(/\{\\[^}]*\}/g,"").replace(/\\[PpNn]/g," ").replace(/\\~/g," ").trim(),h=t.extendedFont||t.font||"sans-serif",d=r!=null?r*180/Math.PI:0,g=d!==0?`translate(${o},${c}) scale(1,-1) rotate(${-d})`:`translate(${o},${c}) scale(1,-1)`;this.svg=`<text font-size="${n}" font-family="${h}" transform="${g}">${Tl(l)}</text>`;const m=l.length*n*.6;this._box.expandByPoint({x:o,y:c}),this._box.expandByPoint({x:o+m,y:c+n})}}function Tl(a){return a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const Il=.5;class El extends ke{constructor(e,t){super();const i=t.displaySize>0?t.displaySize/2:Il;this.svg=`<circle cx="${e.x}" cy="${e.y}" r="${i}" fill="currentColor" stroke="none"/>`,this._box.expandByPoint(e)}}class kl{constructor(){this._container=new Array,this._bbox=new u.AcGeBox2d,this._fontMapping={},this._subEntityTraits={color:new u.AcCmColor,rgbColor:0,lineType:{type:"ByLayer",name:"Continuous",standardFlag:0,description:"Solid line",totalPatternLength:0},lineTypeScale:1,lineWeight:u.AcGiLineWeight.ByLayer,fillType:{solidFill:!0,patternAngle:0,definitionLines:[]},transparency:new u.AcCmTransparency,thickness:0,layer:"0",drawOrder:0}}get subEntityTraits(){return this._subEntityTraits}setFontMapping(e){this._fontMapping=e}set ltscale(e){}set celtscale(e){}group(e){const t=new Cl(e);return this._container.push(t.svg),this._bbox.union(t.box),t}point(e,t){const i=new El(e,t);return this._container.push(i.svg),this._bbox.union(i.box),i}circularArc(e){const t=new Sl(e);return this._container.push(t.svg),this._bbox.union(t.box),t}ellipticalArc(e){const t=new Al(e);return this._container.push(t.svg),this._bbox.union(t.box),t}lines(e){const t=new _l(e);return this._container.push(t.svg),this._bbox.union(t.box),t}lineSegments(e,t,i){const n=new Pl(e,t,i);return this._container.push(n.svg),this._bbox.union(n.box),n}area(e){const t=new vl(e);return this._container.push(t.svg),this._bbox.union(t.box),t}mtext(e,t,i){const n=this._fontMapping[t.font]??t.font,s=n!==t.font?{...t,font:n}:t,r=new Ll(e,s);return this._container.push(r.svg),this._bbox.union(r.box),r}image(e,t){return Bl}export(){const e=this._container.join(`
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
</svg>`}}const Bl=new ke;class Dl{convert(){const e=S.instance.curDocument.database.tables.blockTable.modelSpace.newIterator(),t=new kl;for(const i of e)i.worldDraw(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 xr extends N{async execute(e){new Dl().convert()}}class Ei{static isFontLoaded(e){return B.FontManager.instance.isFontLoaded(e)}static getFontType(e){return B.FontManager.instance.getFontType(e)}static getShxCodePoints(e){var s;const t=B.FontManager.instance.getFontByName(e,!1);if(!t||t.type!=="shx")return[];const i=t.data;return Object.keys(((s=i.content)==null?void 0:s.data)??{}).map(r=>Number(r)).filter(r=>Number.isFinite(r)).sort((r,o)=>r-o)}static getLoadedShxFontData(e){const t=B.FontManager.instance.getFontByName(e,!1);if(!(!t||t.type!=="shx"))return t.data}static createShxParserFont(e){return new B.ShxParserFont(e)}static findFontInfoByName(e){var n;const t=((n=S.instance)==null?void 0:n.avaiableFonts)??[],i=e.trim().toLowerCase();if(i)return t.find(s=>s.name.some(r=>r.trim().toLowerCase()===i))}static getCatalogFontType(e){var t;return(t=Ei.findFontInfoByName(e))==null?void 0:t.type}static async ensureDrawingFontLoaded(e){const t=S.instance;t&&(Ei.isFontLoaded(e)||await t.loadFonts([e]))}}function kt(a){return u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.MEASUREMENTCOLOR,a)}function Tn(a,e){return`rgba(${a.red}, ${a.green}, ${a.blue}, ${e})`}function de(a){return a.cssColor??`rgb(${a.red}, ${a.green}, ${a.blue})`}function Be(a){const e=document.createElement("div");return e.style.cssText=`width:12px;height:12px;border-radius:50%;background:${de(a)};border:2px solid var(--ml-ui-border, #fff);box-sizing:border-box;pointer-events:none;transform:translate(-50%,-50%);`,e}function Bt(a,e=""){const t=document.createElement("div");return t.textContent=e,t.style.cssText=`background:var(--ml-ui-bg, rgba(255,255,255,0.95));color:${de(a)};font-size:13px;font-family:sans-serif;font-weight:500;padding:3px 14px;border-radius:20px;pointer-events:none;transform:translate(-50%,-50%);white-space:nowrap;box-shadow:var(--ml-ui-shadow, 0 1px 4px rgba(0,0,0,0.2));`,t}function Dt(a){const e=document.createElement("div");return e.style.cssText=`position:fixed;background:var(--ml-ui-bg, rgba(255,255,255,0.95));color:${de(a)};font-size:13px;font-family:sans-serif;font-weight:500;padding:3px 14px;border-radius:20px;pointer-events:none;transform:translate(-50%,-50%);white-space:nowrap;box-shadow:var(--ml-ui-shadow, 0 1px 4px rgba(0,0,0,0.2));z-index:99999;display:none;`,document.body.appendChild(e),e}function vr(a){const e=document.createElement("div");return e.style.cssText=`position:fixed;width:12px;height:12px;border-radius:50%;background:${de(a)};border:2px solid var(--ml-ui-border, #fff);box-sizing:border-box;pointer-events:none;transform:translate(-50%,-50%);z-index:99999;`,document.body.appendChild(e),e}function In(a){const e=document.createElement("div");return e.style.cssText=`position:fixed;width:10px;height:10px;border:2px solid ${de(a)};background:transparent;pointer-events:none;box-sizing:border-box;transform:translate(-50%,-50%);z-index:99998;display:none;`,document.body.appendChild(e),e}function qe(a){const e=document.createElement("canvas");return e.style.cssText="position:absolute;pointer-events:none;z-index:1;",a.appendChild(e),e}const Sr=a=>new u.AcGeBox3d(a.min,a.max),Ar=a=>new u.AcGeBox2d(a.min,a.max),Cr=a=>new f.Box3(a.min,a.max),_r=a=>new u.AcGeBox2d(a.min,a.max),Pr=a=>new f.Box2(a.min,a.max),Lr=a=>new u.AcGeBox2d(a.min,a.max),Tr=a=>{const e=new f.Box3;return e.min.set(a.min.x,a.min.y,0),e.max.set(a.max.x,a.max.y,0),e},ki={threeBo2dToGeBox2d:_r,geBox2dToThreeBox2d:Pr,threeBox3dToGeBox3d:Sr,geBox3dToThreeBox3d:Cr,goBox3dToGeBox2d:Ar,threeBox3dToGeBox2d:Lr,geBox2dToThreeBox3d:Tr};function pe(){return new Promise(a=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>a())})})}class Ir{build(e,t,i={}){return this.buildSync(e,t,i)}async buildAsync(e,t,i={}){await pe();const n=fe.buildViewerMetadata(t,{title:i.title,background:i.background}),s=[];e.layers.forEach(o=>{s.push({name:o.name,color:o.color.RGB??16777215,visible:!o.isOff&&!o.isFrozen})});const r=[];for(const[o,c]of e.layouts){const l=[],h=[];for(const[,d]of c.layers){const g=fe.collectBatchesFromObject3D(d.internalObject);l.push(...g.lineBatches),h.push(...g.meshBatches),await pe()}r.push({btrId:o,name:kr(t,o),isModelSpace:o===e.modelSpaceBtrId,lineBatches:l,meshBatches:h,osnap:fe.buildOsnapCatalog(t,o)}),await pe()}return{version:fe.ACEX_SNAPSHOT_VERSION,meta:Er(n,i),layers:s,layouts:r,activeLayoutBtrId:e.activeLayoutBtrId||e.modelSpaceBtrId}}buildSync(e,t,i){const n=fe.buildViewerMetadata(t,{title:i.title,background:i.background}),s=[];e.layers.forEach(o=>{s.push({name:o.name,color:o.color.RGB??16777215,visible:!o.isOff&&!o.isFrozen})});const r=[];return e.layouts.forEach((o,c)=>{const{lineBatches:l,meshBatches:h}=fe.collectBatchesFromObject3D(o.internalObject);r.push({btrId:c,name:kr(t,c),isModelSpace:c===e.modelSpaceBtrId,lineBatches:l,meshBatches:h,osnap:fe.buildOsnapCatalog(t,c)})}),{version:fe.ACEX_SNAPSHOT_VERSION,meta:Er(n,i),layers:s,layouts:r,activeLayoutBtrId:e.activeLayoutBtrId||e.modelSpaceBtrId}}}function Er(a,e){return{title:a.title,createdAt:new Date().toISOString(),extents:a.extents,units:a.units,background:a.background,locale:e.locale??p.currentLocale}}function kr(a,e){for(const t of a.tables.blockTable.newIterator())if(t.objectId===e)return t.name;return e}const Ml="./viewer-runtime.iife.js";class Br{constructor(){this._snapshotBuilder=new Ir}async convert(e){const t=S.instance;t.showBusyIndicator();try{await pe();const i=t.curDocument,n=t.curView,s=await this._snapshotBuilder.buildAsync(n.cadScene,i.database,{title:e??i.fileName,background:n.backgroundColor});await pe();const r=await this.loadViewerRuntime(t.htmlViewerRuntimeUrl);await pe();const o=fe.packHtml(s,{title:s.meta.title,viewerRuntime:r});await pe(),this.downloadHtml(o,this.resolveDownloadName(e??i.fileName))}finally{t.hideBusyIndicator()}}async packSnapshot(e,t){const i=S.instance;i.showBusyIndicator();try{await pe();const n=await this.loadViewerRuntime(i.htmlViewerRuntimeUrl);await pe();const s=fe.packHtml(e,{title:e.meta.title,viewerRuntime:n});await pe(),this.downloadHtml(s,t)}finally{i.hideBusyIndicator()}}async loadViewerRuntime(e){const t=e!=null?String(e):Ml,i=await fetch(t);if(!i.ok)throw new Error(`Failed to load HTML viewer runtime from "${t}" (${i.status}). Build @mlightcad/cad-html-exporter and copy viewer-runtime.iife.js to your app assets.`);return i.text()}resolveDownloadName(e){return`${e.replace(/\.(dwg|dxf)$/i,"")||"drawing"}.html`}downloadHtml(e,t){const i=new Blob([e],{type:"text/html;charset=utf-8"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}}class Dr extends N{async execute(e){await new Br().convert(e.doc.fileName)}}class Mr extends N{constructor(){super(),this._history=[],this.mode=j.Write}async execute(e){for(this._history=[];;){const t=await this.promptMainAction();if(!t)return;if(t.type==="keyword"){t.keyword==="Name"?await this.runNameBranch(e):this.runUndo(e);continue}this.deleteLayerByEntity(e,t.objectId)}}notify(e,t="info"){S.instance.editor.showMessage(e,t)}addKeyword(e,t){e.keywords.add(p.t(`jig.laydel.keywords.${t}.display`),p.t(`jig.laydel.keywords.${t}.global`),p.t(`jig.laydel.keywords.${t}.local`))}async promptMainAction(){const e=new Le(p.t("jig.laydel.selectPrompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(p.t("jig.laydel.invalidSelection")),this.addKeyword(e,"name"),this.addKeyword(e,"undo");const t=await S.instance.editor.getEntity(e);if(t.status===v.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===v.Keyword&&(t.stringResult==="Name"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runNameBranch(e){for(;;){const t=await this.promptLayerNameAction();if(!t)return;if(t.type==="keyword"){t.keyword==="?"?this.listLayers(e):this.runUndo(e);continue}this.deleteLayerByName(e,t.layerName)}}async promptLayerNameAction(){const e=new ce(p.t("jig.laydel.namePrompt"));e.allowSpaces=!0,e.allowEmpty=!0,this.addKeyword(e,"list"),this.addKeyword(e,"undo");const t=await S.instance.editor.getString(e);if(t.status===v.Keyword&&(t.stringResult==="?"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult};if(t.status!==v.OK)return;const i=(t.stringResult??"").trim();if(i)return{type:"name",layerName:i}}listLayers(e){const t=e.doc.database,i=[...t.tables.layerTable.newIterator()].map(n=>({name:n.name,current:t.clayer===n.name?"*":"",on:n.isOff?"No":"Yes",frozen:n.isFrozen?"Yes":"No",locked:n.isLocked?"Yes":"No"}));console.table(i),this.notify(p.t("jig.laydel.layerListSummary"),"info")}deleteLayerByEntity(e,t){var s;const i=e.doc.database.tables.blockTable.getEntityById(t),n=(s=i==null?void 0:i.layer)==null?void 0:s.trim();if(!n){this.notify(p.t("jig.laydel.invalidSelection"),"warning");return}this.deleteLayerByName(e,n)}deleteLayerByName(e,t){const i=e.doc.database,n=i.tables.layerTable.getAt(t);if(!n){this.notify(`${p.t("jig.laydel.layerNotFound")}: ${t}`);return}if(n.name==="0"){this.notify(p.t("jig.laydel.cannotDeleteZeroLayer"),"warning");return}if(n.name===i.clayer){this.notify(p.t("jig.laydel.cannotDeleteCurrent"),"warning");return}const s=this.collectLayerEntities(e,n.name);this.removeLayerEntities(e,s);const r=n.clone();i.tables.layerTable.remove(n.name),i.events.layerErased.dispatch({database:i,layer:n}),this._history.push({layer:r,entities:s}),e.view.selectionSet.clear(),S.instance.regen(),this.notify(`${p.t("jig.laydel.deleted")}: ${n.name}`,"success")}collectLayerEntities(e,t){const i=[];for(const n of e.doc.database.tables.blockTable.newIterator())for(const s of n.newIterator())s.layer===t&&i.push({ownerId:n.objectId,objectId:s.objectId,entity:s.clone()});return i}removeLayerEntities(e,t){const i=new Map;t.forEach(({ownerId:n,objectId:s})=>{const r=i.get(n)??[];r.push(s),i.set(n,r)}),i.forEach((n,s)=>{var r;(r=e.doc.database.tables.blockTable.getIdAt(s))==null||r.removeEntity(n)})}runUndo(e){const t=this._history.pop();if(!t){this.notify(p.t("jig.laydel.nothingToUndo"),"warning");return}const i=e.doc.database;i.tables.layerTable.has(t.layer.name)||i.tables.layerTable.add(t.layer.clone());const n=new Map;t.entities.forEach(({ownerId:s,entity:r})=>{const o=n.get(s)??[];o.push(r.clone()),n.set(s,o)}),n.forEach((s,r)=>{(i.tables.blockTable.getIdAt(r)??i.tables.blockTable.modelSpace).appendEntity(s)}),e.view.selectionSet.clear(),S.instance.regen(),this.notify(`${p.t("jig.laydel.restored")}: ${t.layer.name}`,"success")}}class Or extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=e.view.selectionSet,i=t.count>0?t.ids:await this.promptSelection();!i||i.length===0||this.moveObjectsToCurrentLayer(e,i)}async promptSelection(){var i;const e=new je(p.t("jig.laycur.prompt")),t=await S.instance.editor.getSelection(e);if(t.status===v.OK)return((i=t.value)==null?void 0:i.ids)??[]}moveObjectsToCurrentLayer(e,t){var l;const i=e.doc.database,n=(l=i.clayer)==null?void 0:l.trim(),s=n?i.tables.layerTable.getAt(n):void 0;if(!s){this.notify(p.t("jig.laycur.currentLayerNotFound"),"warning");return}const r=[];let o=0,c=0;if(new Set(t).forEach(h=>{const d=i.tables.blockTable.getEntityById(h);if(!d){c++;return}if(d.layer===s.name){o++;return}d.layer=s.name,r.push(d)}),r.length===0){this.notify(o>0?p.t("jig.laycur.alreadyCurrent"):p.t("jig.laycur.noObjects"),o>0&&c===0?"info":"warning");return}r.forEach(h=>h.triggerModifiedEvent()),e.view.selectionSet.clear(),S.instance.regen(),this.notify(`${p.t("jig.laycur.changed")}: ${r.length} (${s.name})`,"success")}notify(e,t="info"){S.instance.editor.showMessage(e,t)}}const Ol={viewportMode:"Freeze",blockSelectionMode:"None"},Ae=class Ae extends N{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=j.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=Ae._settings.viewportMode!=="Vpfreeze";;){const t=await this.promptSelection();if(!t)return;if(t.type==="keyword"){t.keyword==="Settings"?await this.runSettings():this.runUndo(e);continue}this.freezeEntityLayer(e,t.objectId)}}notify(e,t="info"){S.instance.editor.showMessage(e,t)}addKeyword(e,t){e.keywords.add(p.t(`jig.layfrz.keywords.${t}.display`),p.t(`jig.layfrz.keywords.${t}.global`),p.t(`jig.layfrz.keywords.${t}.local`))}async promptSelection(){const e=new Le(p.t("jig.layfrz.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(p.t("jig.layfrz.invalidSelection")),this.addKeyword(e,"settings"),this.addKeyword(e,"undo");const t=await S.instance.editor.getEntity(e);if(t.status===v.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===v.Keyword&&(t.stringResult==="Settings"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runSettings(){for(;;){const e=new Y(p.t("jig.layfrz.settingsPrompt"));e.allowNone=!0,this.addKeyword(e,"viewports"),this.addKeyword(e,"blockSelection");const t=await S.instance.editor.getKeywords(e);if(t.status!==v.OK)return;const i=t.stringResult;if(!i)return;i==="Viewports"?await this.promptViewportMode():await this.promptBlockSelectionMode()}}async promptViewportMode(){const e=new Y(p.t("jig.layfrz.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(p.t("jig.layfrz.keywords.freeze.display"),p.t("jig.layfrz.keywords.freeze.global"),p.t("jig.layfrz.keywords.freeze.local")),i=e.keywords.add(p.t("jig.layfrz.keywords.vpfreeze.display"),p.t("jig.layfrz.keywords.vpfreeze.global"),p.t("jig.layfrz.keywords.vpfreeze.local"));e.keywords.default=Ae._settings.viewportMode==="Vpfreeze"?i:t;const n=await S.instance.editor.getKeywords(e);if(n.status!==v.OK)return;const s=n.stringResult;s&&(Ae._settings.viewportMode=s,s==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.notify(p.t("jig.layfrz.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new Y(p.t("jig.layfrz.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(p.t("jig.layfrz.keywords.block.display"),p.t("jig.layfrz.keywords.block.global"),p.t("jig.layfrz.keywords.block.local")),i=e.keywords.add(p.t("jig.layfrz.keywords.entity.display"),p.t("jig.layfrz.keywords.entity.global"),p.t("jig.layfrz.keywords.entity.local")),n=e.keywords.add(p.t("jig.layfrz.keywords.none.display"),p.t("jig.layfrz.keywords.none.global"),p.t("jig.layfrz.keywords.none.local"));e.keywords.default=Ae._settings.blockSelectionMode==="Block"?t:Ae._settings.blockSelectionMode==="Entity"?i:n;const s=await S.instance.editor.getKeywords(e);if(s.status!==v.OK)return;const r=s.stringResult;r&&(Ae._settings.blockSelectionMode=r,this.notify(p.t("jig.layfrz.nestedSelectionLimited")))}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}freezeEntityLayer(e,t){var o;const i=e.doc.database,n=i.tables.blockTable.getEntityById(t),s=(o=n==null?void 0:n.layer)==null?void 0:o.trim();if(!s){this.notify(p.t("jig.layfrz.invalidSelection"),"warning");return}const r=i.tables.layerTable.getAt(s);if(!r){this.notify(`${p.t("jig.layfrz.layerNotFound")}: ${s}`,"warning");return}if(r.name===i.clayer){this.notify(p.t("jig.layfrz.cannotFreezeCurrent"),"warning");return}if(r.isFrozen){this.notify(`${p.t("jig.layfrz.alreadyFrozen")}: ${r.name}`,"info");return}Ae._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.notify(p.t("jig.layfrz.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:r.name,wasFrozen:r.isFrozen}),this.setLayerFrozen(r,!0),e.view.selectionSet.clear(),this.notify(`${p.t("jig.layfrz.frozen")}: ${r.name}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.notify(p.t("jig.layfrz.nothingToUndo"),"warning");return}const i=e.doc.database.tables.layerTable.getAt(t.layerName);if(!i){this.notify(`${p.t("jig.layfrz.layerNotFound")}: ${t.layerName}`,"warning");return}this.setLayerFrozen(i,t.wasFrozen),e.view.selectionSet.clear(),this.notify(`${p.t("jig.layfrz.restored")}: ${i.name}`,"success")}};Ae._settings={...Ol};let Bi=Ae;class Fr{static set(e){this._snapshot=e}static consume(){const e=this._snapshot;return this._snapshot=void 0,e}}function jr(a){return{isOff:a.isOff,isFrozen:a.isFrozen,isLocked:a.isLocked}}function Fl(a,e){return a.isOff===e.isOff&&a.isFrozen===e.isFrozen&&a.isLocked===e.isLocked}const jl={isolationMode:"Off",offMode:"Off"},oe=class oe extends N{constructor(){super(),this._vpfreezeHintShown=!1,this._lockFadeHintShown=!1,this.mode=j.Write}async execute(e){this._vpfreezeHintShown=oe._settings.offMode!=="Vpfreeze",this._lockFadeHintShown=oe._settings.isolationMode!=="LockAndFade";const t=e.view.selectionSet.ids;if(t.length>0){this.isolateSelectedObjectLayers(e,t);return}for(;;){const i=await this.promptSelection();if(!i)return;if(i.type==="keyword"){await this.runSettings();continue}this.isolateSelectedObjectLayers(e,i.objectIds);return}}notify(e,t="info"){S.instance.editor.showMessage(e,t)}addKeyword(e,t){e.keywords.add(p.t(`jig.layiso.keywords.${t}.display`),p.t(`jig.layiso.keywords.${t}.global`),p.t(`jig.layiso.keywords.${t}.local`))}async promptSelection(){var i;const e=new je(p.t("jig.layiso.prompt"));this.addKeyword(e,"settings");const t=await S.instance.editor.getSelection(e);if(t.status===v.OK)return{type:"selection",objectIds:((i=t.value)==null?void 0:i.ids)??[]};if(t.status===v.Keyword&&t.stringResult==="Settings")return{type:"keyword",keyword:t.stringResult}}async runSettings(){const e=new Y(p.t("jig.layiso.settingsPrompt"));e.allowNone=!0;const t=e.keywords.add(p.t("jig.layiso.keywords.off.display"),p.t("jig.layiso.keywords.off.global"),p.t("jig.layiso.keywords.off.local")),i=e.keywords.add(p.t("jig.layiso.keywords.lockAndFade.display"),p.t("jig.layiso.keywords.lockAndFade.global"),p.t("jig.layiso.keywords.lockAndFade.local"));e.keywords.default=oe._settings.isolationMode==="LockAndFade"?i:t;const n=await S.instance.editor.getKeywords(e);if(n.status!==v.OK)return;const s=n.stringResult;if(s){if(oe._settings.isolationMode=s,s==="Off"){await this.promptOffMode();return}this._lockFadeHintShown=!0,this.notify(p.t("jig.layiso.lockFadeFallback"))}}async promptOffMode(){const e=new Y(p.t("jig.layiso.offModePrompt"));e.allowNone=!0;const t=e.keywords.add(p.t("jig.layiso.keywords.off.display"),p.t("jig.layiso.keywords.off.global"),p.t("jig.layiso.keywords.off.local")),i=e.keywords.add(p.t("jig.layiso.keywords.vpfreeze.display"),p.t("jig.layiso.keywords.vpfreeze.global"),p.t("jig.layiso.keywords.vpfreeze.local"));e.keywords.default=oe._settings.offMode==="Vpfreeze"?i:t;const n=await S.instance.editor.getKeywords(e);if(n.status!==v.OK)return;const s=n.stringResult;s&&(oe._settings.offMode=s,s==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.notify(p.t("jig.layiso.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}isolateSelectedObjectLayers(e,t){const i=this.collectSelectedLayerNames(e,t);if(i.length===0){this.notify(p.t("jig.layiso.noLayers"),"warning");return}const n=e.doc.database,s=n.tables.layerTable,r=new Set(i),o=s.getAt(i[0]),c=n.clayer,l=new Map;for(const g of s.newIterator())l.set(g.name,jr(g));o&&(n.clayer=o.name);const h=new Set;for(const g of s.newIterator()){if(r.has(g.name)){g.isOff&&(g.isOff=!1,h.add(g.name)),g.isFrozen&&(this.setLayerFrozen(g,!1),h.add(g.name)),g.isLocked&&(this.setLayerLocked(g,!1),h.add(g.name));continue}if(oe._settings.isolationMode==="Off"){g.isOff||(g.isOff=!0,h.add(g.name));continue}g.isLocked||(this.setLayerLocked(g,!0),h.add(g.name))}const d=[];for(const g of s.newIterator()){const m=l.get(g.name);if(!m)continue;const y=jr(g);Fl(m,y)||d.push({name:g.name,before:m,isolated:y})}Fr.set({currentLayerBefore:c,currentLayerAfter:n.clayer,layers:d}),oe._settings.isolationMode==="Off"&&oe._settings.offMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.notify(p.t("jig.layiso.vpfreezeFallback")),this._vpfreezeHintShown=!0),oe._settings.isolationMode==="LockAndFade"&&!this._lockFadeHintShown&&(this.notify(p.t("jig.layiso.lockFadeFallback")),this._lockFadeHintShown=!0),e.view.selectionSet.clear(),this.notify(`${p.t("jig.layiso.isolated")}: ${i.join(", ")} (${p.t("jig.layiso.affectedLayers")}: ${h.size})`,"success")}collectSelectedLayerNames(e,t){const i=e.doc.database,n=new Set,s=new Set;return t.forEach(r=>{var h;const o=i.tables.blockTable.getEntityById(r),c=(h=o==null?void 0:o.layer)==null?void 0:h.trim();if(!c)return;const l=i.tables.layerTable.getAt(c);l?n.add(l.name):s.add(c)}),s.size>0&&this.notify(`${p.t("jig.layiso.layerNotFound")}: ${[...s].join(", ")}`,"warning"),[...n]}};oe._settings={...jl};let Di=oe;class Nr extends N{constructor(){super(),this.mode=j.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.lockEntityLayer(e,t)}}async promptSelection(){const e=new Le(p.t("jig.laylck.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(p.t("jig.laylck.invalidSelection"));const t=await S.instance.editor.getEntity(e);if(t.status===v.OK&&t.objectId)return t.objectId}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}lockEntityLayer(e,t){var o;const i=e.doc.database,n=i.tables.blockTable.getEntityById(t),s=(o=n==null?void 0:n.layer)==null?void 0:o.trim();if(!s){this.notify(p.t("jig.laylck.invalidSelection"),"warning");return}const r=i.tables.layerTable.getAt(s);if(!r){this.notify(`${p.t("jig.laylck.layerNotFound")}: ${s}`,"warning");return}if(r.isLocked){this.notify(`${p.t("jig.laylck.alreadyLocked")}: ${r.name}`,"info");return}this.setLayerLocked(r,!0),e.view.selectionSet.clear(),this.notify(`${p.t("jig.laylck.locked")}: ${r.name}`,"success")}notify(e,t="info"){S.instance.editor.showMessage(e,t)}}class Rr extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=[...e.doc.database.tables.layerTable.newIterator()];let i=0;if(t.forEach(n=>{n.isOff&&(n.isOff=!1,i++)}),e.view.selectionSet.clear(),i===0){this.notify(p.t("jig.layon.alreadyOn"));return}this.notify(`${p.t("jig.layon.turnedOn")}: ${i}`,"success")}notify(e,t="info"){S.instance.editor.showMessage(e,t)}}const Nl={viewportMode:"Off",blockSelectionMode:"None"},Ce=class Ce extends N{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=j.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=Ce._settings.viewportMode!=="Vpfreeze";;){const t=await this.promptSelection();if(!t)return;if(t.type==="keyword"){t.keyword==="Settings"?await this.runSettings():this.runUndo(e);continue}this.turnOffEntityLayer(e,t.objectId)}}notify(e,t="info"){S.instance.editor.showMessage(e,t)}addKeyword(e,t){e.keywords.add(p.t(`jig.layoff.keywords.${t}.display`),p.t(`jig.layoff.keywords.${t}.global`),p.t(`jig.layoff.keywords.${t}.local`))}async promptSelection(){const e=new Le(p.t("jig.layoff.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(p.t("jig.layoff.invalidSelection")),this.addKeyword(e,"settings"),this.addKeyword(e,"undo");const t=await S.instance.editor.getEntity(e);if(t.status===v.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===v.Keyword&&(t.stringResult==="Settings"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runSettings(){for(;;){const e=new Y(p.t("jig.layoff.settingsPrompt"));e.allowNone=!0,this.addKeyword(e,"viewports"),this.addKeyword(e,"blockSelection");const t=await S.instance.editor.getKeywords(e);if(t.status!==v.OK)return;const i=t.stringResult;if(!i)return;i==="Viewports"?await this.promptViewportMode():await this.promptBlockSelectionMode()}}async promptViewportMode(){const e=new Y(p.t("jig.layoff.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(p.t("jig.layoff.keywords.off.display"),p.t("jig.layoff.keywords.off.global"),p.t("jig.layoff.keywords.off.local")),i=e.keywords.add(p.t("jig.layoff.keywords.vpfreeze.display"),p.t("jig.layoff.keywords.vpfreeze.global"),p.t("jig.layoff.keywords.vpfreeze.local"));e.keywords.default=Ce._settings.viewportMode==="Vpfreeze"?i:t;const n=await S.instance.editor.getKeywords(e);if(n.status!==v.OK)return;const s=n.stringResult;s&&(Ce._settings.viewportMode=s,s==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.notify(p.t("jig.layoff.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new Y(p.t("jig.layoff.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(p.t("jig.layoff.keywords.block.display"),p.t("jig.layoff.keywords.block.global"),p.t("jig.layoff.keywords.block.local")),i=e.keywords.add(p.t("jig.layoff.keywords.entity.display"),p.t("jig.layoff.keywords.entity.global"),p.t("jig.layoff.keywords.entity.local")),n=e.keywords.add(p.t("jig.layoff.keywords.none.display"),p.t("jig.layoff.keywords.none.global"),p.t("jig.layoff.keywords.none.local"));e.keywords.default=Ce._settings.blockSelectionMode==="Block"?t:Ce._settings.blockSelectionMode==="Entity"?i:n;const s=await S.instance.editor.getKeywords(e);if(s.status!==v.OK)return;const r=s.stringResult;r&&(Ce._settings.blockSelectionMode=r,this.notify(p.t("jig.layoff.nestedSelectionLimited")))}turnOffEntityLayer(e,t){var o;const i=e.doc.database,n=i.tables.blockTable.getEntityById(t),s=(o=n==null?void 0:n.layer)==null?void 0:o.trim();if(!s){this.notify(p.t("jig.layoff.invalidSelection"),"warning");return}const r=i.tables.layerTable.getAt(s);if(!r){this.notify(`${p.t("jig.layoff.layerNotFound")}: ${s}`,"warning");return}if(r.name===i.clayer){this.notify(p.t("jig.layoff.cannotTurnOffCurrent"),"warning");return}if(r.isOff){this.notify(`${p.t("jig.layoff.alreadyOff")}: ${r.name}`,"info");return}Ce._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.notify(p.t("jig.layoff.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:r.name,wasOff:r.isOff}),r.isOff=!0,e.view.selectionSet.clear(),this.notify(`${p.t("jig.layoff.turnedOff")}: ${r.name}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.notify(p.t("jig.layoff.nothingToUndo"),"warning");return}const i=e.doc.database.tables.layerTable.getAt(t.layerName);if(!i){this.notify(`${p.t("jig.layoff.layerNotFound")}: ${t.layerName}`,"warning");return}i.isOff=t.wasOff,e.view.selectionSet.clear(),this.notify(`${p.t("jig.layoff.restored")}: ${i.name}`,"success")}};Ce._settings={...Nl};let Mi=Ce;class Rl{constructor(){this.previousSnapshot=null}captureState(e){const t=e.doc.database;this.previousSnapshot={clayer:t.clayer,states:[...t.tables.layerTable.newIterator()].map(i=>({name:i.name,isOn:!i.isOff,isFrozen:i.isFrozen,isLocked:this.isLayerLocked(i)}))}}restorePreviousState(e){if(!this.previousSnapshot)return!1;const t=e.doc.database,i=this.previousSnapshot;i.states.forEach(s=>{const r=t.tables.layerTable.getAt(s.name);r&&(r.isOff=!s.isOn,this.setLayerFrozen(r,s.isFrozen),this.setLayerLocked(r,s.isLocked))});const n=t.tables.layerTable.getAt(i.clayer);return n?(n.isOff=!1,this.setLayerFrozen(n,!1),t.clayer=n.name,!0):!1}clearPreviousState(){this.previousSnapshot=null}isLayerLocked(e){return((e.standardFlags??0)&4)!==0}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}}const En=new Rl;function zl(){return En}class zr extends N{constructor(){super(),this.mode=j.Write}async execute(e){En.restorePreviousState(e)?this.notify(p.t("jig.layerp.restored"),"success"):this.notify(p.t("jig.layerp.noPreviousState")),e.view.selectionSet.clear()}notify(e,t="info"){S.instance.editor.showMessage(e,t)}}function Vl(a){En.captureState(a)}class Vr extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=[...e.doc.database.tables.layerTable.newIterator()];let i=0;if(t.forEach(n=>{n.isFrozen&&(this.setLayerFrozen(n,!1),i++)}),e.view.selectionSet.clear(),i===0){this.notify(p.t("jig.laythw.alreadyThawed"));return}this.notify(`${p.t("jig.laythw.thawed")}: ${i}`,"success")}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}notify(e,t="info"){S.instance.editor.showMessage(e,t)}}class Gr extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=Fr.consume();if(!t){this.notify(p.t("jig.layuniso.noPrevious"),"warning");return}const i=e.doc.database,n=i.tables.layerTable;let s=0;for(const r of t.layers){const o=n.getAt(r.name);if(!o){this.notify(`${p.t("jig.layuniso.layerNotFound")}: ${r.name}`,"warning");continue}this.restoreLayerIfUnchanged(o,r)&&s++}if(i.clayer===t.currentLayerAfter&&t.currentLayerBefore!==t.currentLayerAfter&&n.getAt(t.currentLayerBefore)&&(i.clayer=t.currentLayerBefore),e.view.selectionSet.clear(),s===0){this.notify(p.t("jig.layuniso.nothingRestored"));return}this.notify(`${p.t("jig.layuniso.restored")}: ${s}`,"success")}restoreLayerIfUnchanged(e,t){let i=!1;return e.isOff===t.isolated.isOff&&e.isOff!==t.before.isOff&&(e.isOff=t.before.isOff,i=!0),e.isFrozen===t.isolated.isFrozen&&e.isFrozen!==t.before.isFrozen&&(this.setLayerFrozen(e,t.before.isFrozen),i=!0),e.isLocked===t.isolated.isLocked&&e.isLocked!==t.before.isLocked&&(this.setLayerLocked(e,t.before.isLocked),i=!0),i}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}notify(e,t="info"){S.instance.editor.showMessage(e,t)}}class $r extends N{constructor(){super(),this.mode=j.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.unlockEntityLayer(e,t)}}async promptSelection(){const e=new Le(p.t("jig.layulk.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(p.t("jig.layulk.invalidSelection"));const t=await S.instance.editor.getEntity(e);if(t.status===v.OK&&t.objectId)return t.objectId}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}unlockEntityLayer(e,t){var o;const i=e.doc.database,n=i.tables.blockTable.getEntityById(t),s=(o=n==null?void 0:n.layer)==null?void 0:o.trim();if(!s){this.notify(p.t("jig.layulk.invalidSelection"),"warning");return}const r=i.tables.layerTable.getAt(s);if(!r){this.notify(`${p.t("jig.layulk.layerNotFound")}: ${s}`,"warning");return}if(!r.isLocked){this.notify(`${p.t("jig.layulk.alreadyUnlocked")}: ${r.name}`,"info");return}this.setLayerLocked(r,!1),e.view.selectionSet.clear(),this.notify(`${p.t("jig.layulk.unlocked")}: ${r.name}`,"success")}notify(e,t="info"){S.instance.editor.showMessage(e,t)}}class Kr extends N{async execute(e){J.emit("close-layer-manager",{})}}class Ur extends N{constructor(){super(),this.mode=j.Write}async execute(e){for(;;){const t=await this.promptMainKeyword();if(!t)return;switch(t){case"?":this.listLayers(e);break;case"Make":await this.runMake(e);break;case"Set":await this.runSet(e);break;case"New":await this.runNew(e);break;case"On":await this.runOnOff(e,!1);break;case"Off":await this.runOnOff(e,!0);break;case"Color":await this.runColor(e);break;case"Freeze":await this.runFreeze(e,!0);break;case"Thaw":await this.runFreeze(e,!1);break;case"Lock":await this.runLock(e,!0);break;case"Unlock":await this.runLock(e,!1);break;case"Description":await this.runDescription(e);break}}}async promptMainKeyword(){const e=new Y(p.t("jig.layer.main"));e.allowNone=!0,this.addKeyword(e,"list"),this.addKeyword(e,"make"),this.addKeyword(e,"set"),this.addKeyword(e,"new"),this.addKeyword(e,"on"),this.addKeyword(e,"off"),this.addKeyword(e,"color"),this.addKeyword(e,"freeze"),this.addKeyword(e,"thaw"),this.addKeyword(e,"lock"),this.addKeyword(e,"unlock"),this.addKeyword(e,"description");const t=await S.instance.editor.getKeywords(e);return t.status!==v.OK?void 0:t.stringResult}addKeyword(e,t){e.keywords.add(p.t(`jig.layer.keywords.${t}.display`),p.t(`jig.layer.keywords.${t}.global`),p.t(`jig.layer.keywords.${t}.local`))}notify(e,t="info"){S.instance.editor.showMessage(e,t)}listLayers(e){const t=e.doc.database,n=[...t.tables.layerTable.newIterator()].map(s=>({name:s.name,current:t.clayer===s.name?"*":"",on:s.isOff?"No":"Yes",frozen:s.isFrozen?"Yes":"No",locked:s.isLocked?"Yes":"No",color:s.color.toString()}));console.table(n),this.notify(`${p.t("jig.layer.listSummary")} (${n.length})`,"info")}parseLayerNameInput(e,t){const i=e.trim();if(!i)return[];if(i==="*")return[...t];const n=i.split(",").map(s=>s.trim()).filter(Boolean);return[...new Set(n)]}resolveLayers(e,t){const i=e.doc.database.tables.layerTable,n=[],s=[];return t.forEach(r=>{const o=i.getAt(r);o?n.push(o):s.push(r)}),{layers:n,missing:s}}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}async promptLayerNames(e,t){const i=new ce(e);i.allowSpaces=!1;const n=await S.instance.editor.getString(i);if(n.status!==v.OK)return;const s=[...t.doc.database.tables.layerTable.newIterator()].map(o=>o.name),r=this.parseLayerNameInput(n.stringResult??"",s);if(!r.length){this.notify(p.t("jig.layer.emptyInput"),"warning");return}return r}async promptSingleLayerName(e){const t=new ce(e);t.allowSpaces=!0;const i=await S.instance.editor.getString(t);return i.status!==v.OK?void 0:(i.stringResult??"").trim()||void 0}async runNew(e){const t=await this.promptLayerNames(p.t("jig.layer.newPrompt"),e);if(!t)return;const i=e.doc.database.tables.layerTable;let n=0;const s=[];t.forEach(r=>{if(i.has(r)){s.push(r);return}i.add(new u.AcDbLayerTableRecord({name:r,isOff:!1,isPlottable:!0,color:new u.AcCmColor(u.AcCmColorMethod.ByACI,7),linetype:"Continuous"})),n++}),n>0&&this.notify(`${p.t("jig.layer.created")}: ${n}`,"success"),s.length>0&&this.notify(`${p.t("jig.layer.alreadyExists")}: ${s.join(", ")}`,"warning")}async runSet(e){const t=await this.promptSingleLayerName(p.t("jig.layer.setPrompt"));if(!t)return;const i=e.doc.database.tables.layerTable.getAt(t);if(!i){this.notify(`${p.t("jig.layer.notFound")}: ${t}`,"warning");return}i.isOff=!1,this.setLayerFrozen(i,!1),e.doc.database.clayer=i.name}async runMake(e){const t=await this.promptSingleLayerName(p.t("jig.layer.makePrompt"));if(!t)return;const i=e.doc.database.tables.layerTable;let n=i.getAt(t);n||(n=new u.AcDbLayerTableRecord({name:t,isOff:!1,isPlottable:!0,color:new u.AcCmColor(u.AcCmColorMethod.ByACI,7),linetype:"Continuous"}),i.add(n)),n.isOff=!1,this.setLayerFrozen(n,!1),e.doc.database.clayer=n.name}async runOnOff(e,t){const i=await this.promptLayerNames(t?p.t("jig.layer.offPrompt"):p.t("jig.layer.onPrompt"),e);if(!i)return;const n=e.doc.database,{layers:s,missing:r}=this.resolveLayers(e,i);r.length>0&&this.notify(`${p.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const o=[];s.forEach(c=>{if(t&&c.name===n.clayer){o.push(c.name);return}c.isOff=t}),o.length>0&&this.notify(p.t("jig.layer.cannotChangeCurrent"),"warning")}async runFreeze(e,t){const i=await this.promptLayerNames(t?p.t("jig.layer.freezePrompt"):p.t("jig.layer.thawPrompt"),e);if(!i)return;const n=e.doc.database,{layers:s,missing:r}=this.resolveLayers(e,i);r.length>0&&this.notify(`${p.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const o=[];s.forEach(c=>{if(t&&c.name===n.clayer){o.push(c.name);return}this.setLayerFrozen(c,t)}),o.length>0&&this.notify(p.t("jig.layer.cannotChangeCurrent"),"warning")}async runLock(e,t){const i=await this.promptLayerNames(t?p.t("jig.layer.lockPrompt"):p.t("jig.layer.unlockPrompt"),e);if(!i)return;const{layers:n,missing:s}=this.resolveLayers(e,i);s.length>0&&this.notify(`${p.t("jig.layer.notFound")}: ${s.join(", ")}`,"warning"),n.forEach(r=>this.setLayerLocked(r,t))}parseColorInput(e){const t=e.trim();if(!t)return;if(/^\d+$/.test(t)){const n=Number(t);return n>=1&&n<=255?new u.AcCmColor(u.AcCmColorMethod.ByACI,n):void 0}const i=u.AcCmColor.fromString(t);if(i){if(i.isByACI){const n=i.colorIndex;if(n==null||n<1||n>255)return}if(!(i.isByLayer||i.isByBlock))return i}}async runColor(e){const t=await this.promptLayerNames(p.t("jig.layer.colorLayerPrompt"),e);if(!t)return;const{layers:i,missing:n}=this.resolveLayers(e,t);if(n.length>0&&this.notify(`${p.t("jig.layer.notFound")}: ${n.join(", ")}`,"warning"),i.length===0)return;const s=new ce(p.t("jig.layer.colorValuePrompt"));s.allowSpaces=!1;const r=await S.instance.editor.getString(s);if(r.status!==v.OK)return;const o=this.parseColorInput(r.stringResult??"");if(!o){this.notify(p.t("jig.layer.invalidColor"),"warning");return}i.forEach(c=>{c.color=o.clone()})}async runDescription(e){const t=await this.promptSingleLayerName(p.t("jig.layer.descriptionLayerPrompt"));if(!t)return;const i=e.doc.database.tables.layerTable.getAt(t);if(!i){this.notify(`${p.t("jig.layer.notFound")}: ${t}`,"warning");return}const n=new ce(p.t("jig.layer.descriptionValuePrompt"));n.allowSpaces=!0,n.allowEmpty=!0;const s=await S.instance.editor.getString(n);s.status===v.OK&&(i.description=s.stringResult??"")}}const Gl={x:0,y:0,z:1},$l={x:0,y:0,z:-1};function Oi(a){const e=a%u.TAU;return e>=0?e:e+u.TAU}function $e(a,e){return Math.hypot(e.x-a.x,e.y-a.y)}function kn(a,e){return Math.atan2(e.y-a.y,e.x-a.x)*180/Math.PI}function ge(a,e,t){const i=e.x-a.x,n=e.y-a.y,s=t===1?Math.atan2(n,i):Math.atan2(n,-i);return Oi(s)}function Wr(a){return a===1?Gl:$l}function Hr(a){return a.normal.z>=0?1:-1}function Mt(a){return new u.AcDbArc(a.center,a.radius,a.startAngle,a.endAngle,Wr(a.normalSign))}function Yr(a,e){a.center=e.center,a.radius=e.radius,a.startAngle=e.startAngle,a.endAngle=e.endAngle,a.normal=Wr(e.normalSign)}function me(a){return{center:{x:a.x,y:a.y,z:0},radius:1e-6,startAngle:0,endAngle:Math.PI/2,normalSign:1}}function Kl(a,e,t){const i=t.x-a.x,n=t.y-a.y,s=Math.hypot(i,n);if(u.AcGeTol.isNonPositive(s))return;const r=e/s;return{x:a.x+i*r,y:a.y+n*r,z:0}}function Xr(a,e,t){const i=Oi(t-a);return Oi(e-a)<=i+1e-7}function Ul(a,e,t,i){const n=ge(a,e,1),s=ge(a,t,1),r=ge(a,i,1),o=Xr(n,s,r),c=ge(a,e,-1),l=ge(a,t,-1),h=ge(a,i,-1),d=Xr(c,l,h);return o&&!d?1:!o&&d?-1:(t.x-e.x)*(i.y-e.y)-(t.y-e.y)*(i.x-e.x)>=0?1:-1}function qr(a,e,t,i=!1){const n=a.x,s=a.y,r=e.x,o=e.y,c=t.x,l=t.y,h=2*(n*(o-l)+r*(l-s)+c*(s-o));if(u.AcGeTol.equalToZero(h))return;const d=((n*n+s*s)*(o-l)+(r*r+o*o)*(l-s)+(c*c+l*l)*(s-o))/h,g=((n*n+s*s)*(c-r)+(r*r+o*o)*(n-c)+(c*c+l*l)*(r-n))/h,m={x:d,y:g,z:0},y=$e(m,a);if(!Number.isFinite(y)||u.AcGeTol.isNonPositive(y))return;const w=Ul(m,a,e,t),C=i?-w:w;return{center:m,radius:y,startAngle:ge(m,a,C),endAngle:ge(m,t,C),normalSign:C}}function at(a,e,t,i){const n=$e(a,e),s=$e(a,t);if(u.AcGeTol.isNonPositive(n)||u.AcGeTol.isNonPositive(s))return;const r=Math.max(u.FLOAT_TOL,n*u.FLOAT_TOL);if(!(Math.abs(n-s)>r))return{center:{x:a.x,y:a.y,z:0},radius:n,startAngle:ge(a,e,i),endAngle:ge(a,t,i),normalSign:i}}function Fi(a,e,t,i){const n=$e(a,e);if(u.AcGeTol.isNonPositive(n))return;const s=Kl(a,n,t);if(s)return at(a,e,s,i)}function ct(a,e,t){const i=$e(a,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||!u.AcGeTol.great(u.TAU-n,0))return;const s=t>=0?1:-1,r=ge(a,e,s),o=Oi(r+n);return{center:{x:a.x,y:a.y,z:0},radius:i,startAngle:r,endAngle:o,normalSign:s}}function Ot(a,e,t){const i=$e(a,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||u.AcGeTol.great(n,2*i))return;const s=Math.max(-1,Math.min(1,n/(2*i))),r=2*Math.asin(s),o=t>=0?r:-r;return ct(a,e,o)}function Bn(a,e,t){const i=$e(a,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||!u.AcGeTol.great(u.TAU-n,0))return;const s=Math.sin(n/2);if(u.AcGeTol.equalToZero(s))return;const r=i/(2*s),o=r*r-i*i/4;if(u.AcGeTol.less(o,0))return;const c=Math.sqrt(Math.max(0,o)),l=(a.x+e.x)/2,h=(a.y+e.y)/2,d=e.x-a.x,m=-(e.y-a.y)/i,y=d/i,w=t>=0,b=w&&n<=Math.PI||!w&&n>Math.PI?1:-1,x={x:l+m*c*b,y:h+y*c*b};return at(x,a,e,w?1:-1)}function Dn(a,e,t){const i=Math.cos(t),n=Math.sin(t),s=e.x-a.x,r=e.y-a.y,o=-n,c=i,l=2*(s*o+r*c);if(u.AcGeTol.equalToZero(l))return;const h=(s*s+r*r)/l;if(!Number.isFinite(h))return;const d={x:a.x+o*h,y:a.y+c*h},g=a.x-d.x,m=a.y-d.y,y=g*n-m*i;if(u.AcGeTol.equalToZero(y))return;const w=y>=0?1:-1;return at(d,a,e,w)}function Mn(a,e,t){const i=Math.abs(t),n=$e(a,e);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||u.AcGeTol.great(n,2*i))return;const s=(a.x+e.x)/2,r=(a.y+e.y)/2,o=e.x-a.x,l=-(e.y-a.y)/n,h=o/n,d=Math.sqrt(Math.max(0,i*i-n*n/4)),g=t>=0?1:-1,m={x:s+l*d*g,y:r+h*d*g},y=t>=0?1:-1;return at(m,a,e,y)}class Ft extends ${constructor(e,t,i){super(e),this._builder=t,this._arc=Mt(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==Hr(this._arc)){this.end(),this._arc=Mt(t);return}Yr(this._arc,t)}}}class lt extends ${constructor(e,t,i){super(e),this._builder=t,this._arc=Mt(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==Hr(this._arc)){this.end(),this._arc=Mt(t);return}Yr(this._arc,t)}}}const Wl={"3p":"threePoint","3point":"threePoint",threepoint:"threePoint",startcenter:"startCenter",sc:"startCenter",startcenterend:"startCenterEnd",sce:"startCenterEnd",startcenterangle:"startCenterAngle",sca:"startCenterAngle",startcenterlength:"startCenterLength",startcenterchordlength:"startCenterLength",scl:"startCenterLength",startend:"startEnd",se:"startEnd",startendangle:"startEndAngle",sea:"startEndAngle",startenddirection:"startEndDirection",sed:"startEndDirection",startendradius:"startEndRadius",ser:"startEndRadius",center:"centerStart",c:"centerStart",centerstart:"centerStart",cs:"centerStart",centerstartend:"centerStartEnd",cse:"centerStartEnd",centerstartangle:"centerStartAngle",csa:"centerStartAngle",centerstartlength:"centerStartLength",centerstartchordlength:"centerStartLength",csl:"centerStartLength"};class Zr extends N{constructor(){super(),this.mode=j.Write}async execute(e){S.instance.editor.resetInputToggles();const t=this.consumeEntryMode();if(t!=="default"){await this.executeEntryMode(e,t);return}const i=new D(p.t("jig.arc.startPointOrCenter"));this.addKeyword(i,"center");const n=await S.instance.editor.getPoint(i);if(n.status===v.Keyword){n.stringResult==="Center"&&await this.runCenterStartFlow(e);return}n.status===v.OK&&await this.runStartFlow(e,n.value)}async executeEntryMode(e,t){switch(t){case"threePoint":await this.runExactThreePointFlow(e);return;case"startCenter":await this.runStartCenterFlowFromEntry(e);return;case"startCenterEnd":await this.runExactStartCenterFlow(e,"end");return;case"startCenterAngle":await this.runExactStartCenterFlow(e,"angle");return;case"startCenterLength":await this.runExactStartCenterFlow(e,"chordLength");return;case"startEnd":await this.runStartEndFlowFromEntry(e);return;case"startEndAngle":await this.runExactStartEndFlow(e,"angle");return;case"startEndDirection":await this.runExactStartEndFlow(e,"direction");return;case"startEndRadius":await this.runExactStartEndFlow(e,"radius");return;case"centerStart":await this.runCenterStartFlow(e);return;case"centerStartEnd":await this.runExactCenterStartFlow(e,"end");return;case"centerStartAngle":await this.runExactCenterStartFlow(e,"angle");return;case"centerStartLength":await this.runExactCenterStartFlow(e,"chordLength");return}}consumeEntryMode(){const e=S.instance.editor.peekScriptInput();if(e==null)return"default";const t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""),i=Wl[t];return i?(S.instance.editor.consumeScriptInput(),i):"default"}addKeyword(e,t){e.keywords.add(p.t(`jig.arc.keywords.${t}.display`),p.t(`jig.arc.keywords.${t}.global`),p.t(`jig.arc.keywords.${t}.local`))}appendArc(e,t){e.doc.database.tables.blockTable.modelSpace.appendEntity(Mt(t))}warnInvalidGeometry(e){J.emit("message",{message:p.t(`jig.arc.invalid.${e}`),type:"warning"})}async promptStartPoint(){const e=new D(p.t("jig.arc.startPoint")),t=await S.instance.editor.getPoint(e);return t.status===v.OK?t.value:void 0}async promptCenterPoint(e){const t=new D(p.t("jig.arc.centerPoint"));e&&(t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e));const i=await S.instance.editor.getPoint(t);return i.status===v.OK?i.value:void 0}async promptEndPoint(e){const t=new D(p.t("jig.arc.endPoint"));e&&(t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e));const i=await S.instance.editor.getPoint(t);return i.status===v.OK?i.value:void 0}async promptSecondPoint(e){const t=new D(p.t("jig.arc.secondPoint"));t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e);const i=await S.instance.editor.getPoint(t);return i.status===v.OK?i.value:void 0}async runExactThreePointFlow(e){const t=await this.promptStartPoint();if(!t)return;const i=await this.promptSecondPoint(t);i&&await this.finishThreePointArc(e,t,i)}async runStartCenterFlowFromEntry(e){const t=await this.promptStartPoint();t&&await this.runStartCenterFlow(e,t)}async runExactStartCenterFlow(e,t){const i=await this.promptStartPoint();if(!i)return;const n=await this.promptCenterPoint(i);if(!n)return;if(t==="end"){await this.finishExactCenterStartEnd(e,n,i);return}if(t==="angle"){const l=new xe(p.t("jig.arc.includedAngle"));l.allowNegative=!0,l.allowZero=!1,l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(n),l.baseAngle=kn(n,i),l.jig=new lt(e.view,m=>ct(n,i,this.applyCtrlDirectionValue(this.degToRad(m))),me(i));const h=await S.instance.editor.getAngle(l),d=h.status===v.OK?h.value:void 0;if(d==null)return;const g=ct(n,i,this.applyCtrlDirectionValue(this.degToRad(d)));g?this.appendArc(e,g):this.warnInvalidGeometry("angle");return}const s=new he(p.t("jig.arc.chordLength"));s.allowNegative=!0,s.allowZero=!1,s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(i),s.jig=new lt(e.view,l=>Ot(n,i,this.applyCtrlDirectionValue(l)),me(i));const r=await S.instance.editor.getDistance(s),o=r.status===v.OK?r.value:void 0;if(o==null)return;const c=Ot(n,i,this.applyCtrlDirectionValue(o));c?this.appendArc(e,c):this.warnInvalidGeometry("chordLength")}async runExactCenterStartFlow(e,t){const i=await this.promptCenterPoint();if(!i)return;const n=await this.promptStartPointFromCenter(i);if(!n)return;if(t==="end"){await this.finishExactCenterStartEnd(e,i,n);return}if(t==="angle"){const l=new xe(p.t("jig.arc.includedAngle"));l.allowNegative=!0,l.allowZero=!1,l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(i),l.baseAngle=kn(i,n),l.jig=new lt(e.view,m=>ct(i,n,this.applyCtrlDirectionValue(this.degToRad(m))),me(n));const h=await S.instance.editor.getAngle(l),d=h.status===v.OK?h.value:void 0;if(d==null)return;const g=ct(i,n,this.applyCtrlDirectionValue(this.degToRad(d)));g?this.appendArc(e,g):this.warnInvalidGeometry("angle");return}const s=new he(p.t("jig.arc.chordLength"));s.allowNegative=!0,s.allowZero=!1,s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(n),s.jig=new lt(e.view,l=>Ot(i,n,this.applyCtrlDirectionValue(l)),me(n));const r=await S.instance.editor.getDistance(s),o=r.status===v.OK?r.value:void 0;if(o==null)return;const c=Ot(i,n,this.applyCtrlDirectionValue(o));c?this.appendArc(e,c):this.warnInvalidGeometry("chordLength")}async runExactStartEndFlow(e,t){const i=await this.promptStartPoint();if(!i)return;const n=await this.promptEndPoint(i);if(!n)return;if(t==="angle"){const l=new xe(p.t("jig.arc.includedAngle"));l.allowNegative=!0,l.allowZero=!1,l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(i),l.baseAngle=kn(i,n),l.jig=new lt(e.view,m=>Bn(i,n,this.applyCtrlDirectionValue(this.degToRad(m))),me(i));const h=await S.instance.editor.getAngle(l),d=h.status===v.OK?h.value:void 0;if(d==null)return;const g=Bn(i,n,this.applyCtrlDirectionValue(this.degToRad(d)));g?this.appendArc(e,g):this.warnInvalidGeometry("angle");return}if(t==="direction"){const l=new D(p.t("jig.arc.tangentDirection"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(i),l.jig=new Ft(e.view,y=>Dn(i,n,Math.atan2(y.y-i.y,y.x-i.x)),me(i));const h=await S.instance.editor.getPoint(l),d=h.status===v.OK?h.value:void 0;if(!d)return;const g=Math.atan2(d.y-i.y,d.x-i.x),m=Dn(i,n,g);m?this.appendArc(e,m):this.warnInvalidGeometry("direction");return}const s=new he(p.t("jig.arc.radius"));s.allowNegative=!0,s.allowZero=!1,s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(i),s.jig=new lt(e.view,l=>Mn(i,n,this.applyCtrlDirectionValue(l)),me(i));const r=await S.instance.editor.getDistance(s),o=r.status===v.OK?r.value:void 0;if(o==null)return;const c=Mn(i,n,this.applyCtrlDirectionValue(o));c?this.appendArc(e,c):this.warnInvalidGeometry("radius")}async runStartEndFlowFromEntry(e){const t=await this.promptStartPoint();t&&await this.runStartEndFlow(e,t)}async promptStartPointFromCenter(e){const t=new D(p.t("jig.arc.startPoint"));t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e);const i=await S.instance.editor.getPoint(t);return i.status===v.OK?i.value:void 0}async finishExactCenterStartEnd(e,t,i){const n=new D(p.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(i),n.jig=new Ft(e.view,o=>Fi(t,i,o,this.applyCtrlDirectionSign(1)),me(i));const s=await S.instance.editor.getPoint(n);if(s.status!==v.OK)return;const r=Fi(t,i,s.value,this.applyCtrlDirectionSign(1));r?this.appendArc(e,r):this.warnInvalidGeometry("center")}getArcDirectionFactor(){return S.instance.editor.getInputToggles().ctrlArcFlip?-1:1}applyCtrlDirectionSign(e){return e*this.getArcDirectionFactor()}applyCtrlDirectionValue(e){return e*this.getArcDirectionFactor()}isCtrlDirectionFlipped(){return S.instance.editor.getInputToggles().ctrlArcFlip}async runStartFlow(e,t){const i=new D(p.t("jig.arc.secondPointOrOptions"));this.addKeyword(i,"center"),this.addKeyword(i,"end"),i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await S.instance.editor.getPoint(i);if(n.status===v.OK){await this.finishThreePointArc(e,t,n.value);return}if(n.status===v.Keyword){if(n.stringResult==="Center"){await this.runStartCenterFlow(e,t);return}n.stringResult==="End"&&await this.runStartEndFlow(e,t)}}async finishThreePointArc(e,t,i){const n=new D(p.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t),n.jig=new Ft(e.view,o=>qr(t,i,o,this.isCtrlDirectionFlipped()),me(t));const s=await S.instance.editor.getPoint(n);if(s.status!==v.OK)return;const r=qr(t,i,s.value,this.isCtrlDirectionFlipped());r?this.appendArc(e,r):this.warnInvalidGeometry("threePoint")}async runCenterStartFlow(e){const t=new D(p.t("jig.arc.centerPoint")),i=await S.instance.editor.getPoint(t);if(i.status!==v.OK)return;const n=i.value,s=new D(p.t("jig.arc.startPoint"));s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(n);const r=await S.instance.editor.getPoint(s);r.status===v.OK&&await this.finishCenterStartFlow(e,n,r.value)}async runStartCenterFlow(e,t){const i=new D(p.t("jig.arc.centerPoint"));i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await S.instance.editor.getPoint(i);n.status===v.OK&&await this.finishCenterStartFlow(e,n.value,t)}async finishCenterStartFlow(e,t,i){const n=new D(p.t("jig.arc.endPointOrOptions"));this.addKeyword(n,"angle"),this.addKeyword(n,"chordLength"),n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(i),n.jig=new Ft(e.view,r=>Fi(t,i,r,this.applyCtrlDirectionSign(1)),me(i));const s=await S.instance.editor.getPoint(n);if(s.status===v.OK){const r=Fi(t,i,s.value,this.applyCtrlDirectionSign(1));r?this.appendArc(e,r):this.warnInvalidGeometry("center");return}if(s.status===v.Keyword){if(s.stringResult==="Angle"){const r=new X(p.t("jig.arc.includedAngle"));r.allowZero=!1,r.allowNegative=!0;const o=await S.instance.editor.getDouble(r);if(o.status!==v.OK)return;const c=ct(t,i,this.applyCtrlDirectionValue(this.degToRad(o.value)));c?this.appendArc(e,c):this.warnInvalidGeometry("angle");return}if(s.stringResult==="ChordLength"){const r=new he(p.t("jig.arc.chordLength"));r.allowZero=!1,r.allowNegative=!0,r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new u.AcGePoint3d(i);const o=await S.instance.editor.getDistance(r);if(o.status!==v.OK)return;const c=Ot(t,i,this.applyCtrlDirectionValue(o.value));c?this.appendArc(e,c):this.warnInvalidGeometry("chordLength")}}}async runStartEndFlow(e,t){const i=new D(p.t("jig.arc.endPoint"));i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await S.instance.editor.getPoint(i);if(n.status!==v.OK)return;const s=n.value,r=new D(p.t("jig.arc.centerPointOrOptions"));this.addKeyword(r,"angle"),this.addKeyword(r,"direction"),this.addKeyword(r,"radius"),r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new u.AcGePoint3d(t),r.jig=new Ft(e.view,c=>at(c,t,s,this.applyCtrlDirectionSign(1)),me(t));const o=await S.instance.editor.getPoint(r);if(o.status===v.OK){const c=at(o.value,t,s,this.applyCtrlDirectionSign(1));c?this.appendArc(e,c):this.warnInvalidGeometry("center");return}if(o.status===v.Keyword){if(o.stringResult==="Angle"){const c=new X(p.t("jig.arc.includedAngle"));c.allowZero=!1,c.allowNegative=!0;const l=await S.instance.editor.getDouble(c);if(l.status!==v.OK)return;const h=Bn(t,s,this.applyCtrlDirectionValue(this.degToRad(l.value)));h?this.appendArc(e,h):this.warnInvalidGeometry("angle");return}if(o.stringResult==="Direction"){const c=new D(p.t("jig.arc.tangentDirection"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(t);const l=await S.instance.editor.getPoint(c);if(l.status!==v.OK)return;const h=l.value,d=Math.atan2(h.y-t.y,h.x-t.x),g=Dn(t,s,d);g?this.appendArc(e,g):this.warnInvalidGeometry("direction");return}if(o.stringResult==="Radius"){const c=new he(p.t("jig.arc.radius"));c.allowZero=!1,c.allowNegative=!0,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(t);const l=await S.instance.editor.getDistance(c);if(l.status!==v.OK)return;const h=Mn(t,s,this.applyCtrlDirectionValue(l.value));h?this.appendArc(e,h):this.warnInvalidGeometry("radius")}}}degToRad(e){return e*Math.PI/180}}function Jr(a){return{center:{x:a.x,y:a.y,z:0},radius:1e-6}}function On(a,e){a.keywords.add(p.t(`jig.circle.keywords.${e}.display`),p.t(`jig.circle.keywords.${e}.global`),p.t(`jig.circle.keywords.${e}.local`))}function Hl(a,e){a.center=e.center,a.radius=e.radius}function Qr(a,e){if(!(!Number.isFinite(e)||u.AcGeTol.isNonPositive(e)))return{center:{x:a.x,y:a.y,z:0},radius:e}}function eo(a,e){const t=e.x-a.x,i=e.y-a.y,n=Math.hypot(t,i);if(!u.AcGeTol.isNonPositive(n))return{center:{x:(a.x+e.x)/2,y:(a.y+e.y)/2,z:0},radius:n/2}}function to(a,e,t){const i=a.x,n=a.y,s=e.x,r=e.y,o=t.x,c=t.y,l=2*(i*(r-c)+s*(c-n)+o*(n-r));if(u.AcGeTol.equalToZero(l))return;const h=((i*i+n*n)*(r-c)+(s*s+r*r)*(c-n)+(o*o+c*c)*(n-r))/l,d=((i*i+n*n)*(o-s)+(s*s+r*r)*(i-o)+(o*o+c*c)*(s-i))/l,g=Math.hypot(h-i,d-n);if(!(!Number.isFinite(g)||u.AcGeTol.isNonPositive(g)))return{center:{x:h,y:d,z:0},radius:g}}class ji extends ${constructor(e,t){super(e),this._circle=new u.AcDbCircle(t,0)}get entity(){return this._circle}update(e){this._circle.radius=e}}class io extends ${constructor(e,t,i){super(e),this._circle=new u.AcDbCircle(i.center,i.radius),this._builder=t}get entity(){return this._circle}update(e){const t=this._builder(e);t&&Hl(this._circle,t)}}class no extends N{constructor(){super(),this.mode=j.Write}async execute(e){let t;class i{constructor(d,g){this.cmd=d,this.machine=g}buildPrompt(){const d=new D(p.t("jig.circle.centerOrOptions"));return On(d,"threeP"),On(d,"twoP"),d}async handleResult(d){if(d.status===v.OK)return t=await this.cmd.runCenterFlow(e,d.value),"finish";if(d.status!==v.Keyword)return"finish";const g=d.stringResult??"";return g==="3P"?(this.machine.setState(new r(this.cmd,this.machine)),"continue"):g==="2P"?(this.machine.setState(new n(this.cmd,this.machine)),"continue"):"finish"}}class n{constructor(d,g){this.cmd=d,this.machine=g}buildPrompt(){return new D(p.t("jig.circle.twoPointFirst"))}async handleResult(d){return d.status!==v.OK?"finish":(this.machine.setState(new s(this.cmd,d.value)),"continue")}}class s{constructor(d,g){this.cmd=d,this.firstPoint=g}buildPrompt(){const d=new D(p.t("jig.circle.twoPointSecond"));return d.useBasePoint=!0,d.useDashedLine=!0,d.basePoint=new u.AcGePoint3d(this.firstPoint),d.jig=new io(e.view,g=>eo(this.firstPoint,g),Jr(this.firstPoint)),d}async handleResult(d){return d.status===v.OK&&(t=this.cmd.createFromTwoPoints(this.firstPoint,d.value)),"finish"}}class r{constructor(d,g){this.cmd=d,this.machine=g}buildPrompt(){return new D(p.t("jig.circle.threePointFirst"))}async handleResult(d){return d.status!==v.OK?"finish":(this.machine.setState(new o(this.cmd,this.machine,d.value)),"continue")}}class o{constructor(d,g,m){this.cmd=d,this.machine=g,this.firstPoint=m}buildPrompt(){const d=new D(p.t("jig.circle.threePointSecond"));return d.useBasePoint=!0,d.useDashedLine=!0,d.basePoint=new u.AcGePoint3d(this.firstPoint),d}async handleResult(d){return d.status!==v.OK?"finish":(this.machine.setState(new c(this.cmd,this.firstPoint,d.value)),"continue")}}class c{constructor(d,g,m){this.cmd=d,this.firstPoint=g,this.secondPoint=m}buildPrompt(){const d=new D(p.t("jig.circle.threePointThird"));return d.useBasePoint=!0,d.useDashedLine=!0,d.basePoint=new u.AcGePoint3d(this.secondPoint),d.jig=new io(e.view,g=>to(this.firstPoint,this.secondPoint,g),Jr(this.firstPoint)),d}async handleResult(d){return d.status===v.OK&&(t=this.cmd.createFromThreePoints(this.firstPoint,this.secondPoint,d.value)),"finish"}}const l=new Te;l.setState(new i(this,l)),await l.run(h=>S.instance.editor.getPoint(h)),t&&e.doc.database.tables.blockTable.modelSpace.appendEntity(new u.AcDbCircle(t.center,t.radius))}async runCenterFlow(e,t){const i=new he(p.t("jig.circle.radiusOrDiameter"));On(i,"diameter"),i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t),i.jig=new ji(e.view,t);const n=await S.instance.editor.getDistance(i);if(n.status===v.OK)return Qr(t,n.value??0);if(n.status===v.Keyword&&n.stringResult==="Diameter")return await this.promptDiameterCircle(e,t)}async promptDiameterCircle(e,t){const i=new he(p.t("jig.circle.diameter"));i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t),i.jig=new ji(e.view,t);const n=await S.instance.editor.getDistance(i);if(n.status!==v.OK)return;const s=(n.value??0)/2;return Qr(t,s)}createFromTwoPoints(e,t){return eo(e,t)}createFromThreePoints(e,t,i){return to(e,t,i)}}class so extends ${constructor(e,t,i,n){super(e),this._dimBlockName="*UDIM",this._db=t,new u.AcDbDataGenerator(t).createArrowBlock(),this._dim=new u.AcDbAlignedDimension(i,n,i),this._dim.rotation=0}get entity(){return this._dim}update(e){this._dim.dimLinePoint=e,this._dim.rotation=this.calculateAngle(this._dim.xLine1Point,this._dim.xLine2Point),this._dim.dimensionText=this._dim.xLine1Point.distanceTo(this._dim.xLine2Point).toFixed(3);const t=this._dimBlockName;this._db.tables.blockTable.remove(t),this._db.tables.blockTable.add(this._dim.createDimBlock(t)),this._dim.dimBlockId=t}end(){super.end(),this._db.tables.blockTable.remove(this._dimBlockName)}calculateAngle(e,t){const i=t.x-e.x,n=t.y-e.y;return Math.atan2(n,i)}}class ro extends N{constructor(){super(),this.mode=j.Review}async execute(e){const t=new D(p.t("jig.dimlinear.xLine1Point")),i=await S.instance.editor.getPoint(t);if(i.status!==v.OK)return;const n=i.value,s=new D(p.t("jig.dimlinear.xLine2Point"));s.useBasePoint=!0;const r=await S.instance.editor.getPoint(s);if(r.status!==v.OK)return;const o=r.value,c=new D(p.t("jig.dimlinear.dimLinePoint"));c.jig=new so(e.view,e.doc.database,n,o);const l=await S.instance.editor.getPoint(c);if(l.status!==v.OK)return;const h=l.value,d=e.doc.database,g=new u.AcDbAlignedDimension(n,o,h),m=this.getAvaiableDimBlockName(d);d.tables.blockTable.add(g.createDimBlock(m)),g.dimBlockId=m,d.tables.blockTable.modelSpace.appendEntity(g)}getAvaiableDimBlockName(e){const t=e.tables.blockTable.newIterator();let i=0;for(const n of t){const s=n.name;if(!s.startsWith("*D"))continue;const r=Number(s.slice(2));Number.isInteger(r)&&r>i&&(i=r)}return`*D${i+1}`}}class Ni extends ${constructor(e,t){super(e),this._line=new u.AcDbLine(t,t)}get entity(){return this._line}update(e){this._line.endPoint=e}}class Ze extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=e.doc.database,i=[],n=[],s=()=>!!Ze._lastEndpoint,r=()=>Ze._lastEndpoint?new u.AcGePoint3d(Ze._lastEndpoint):void 0,o=()=>{const b=l();b&&(Ze._lastEndpoint=new u.AcGePoint3d(b))},c=b=>{i.push(new u.AcGePoint3d(b))},l=()=>i[i.length-1],h=b=>{const x=l();if(!x)return;const A=new u.AcDbLine(new u.AcGePoint3d(x),b);t.tables.blockTable.modelSpace.appendEntity(A),n.push(A),c(b)},d=()=>{var b;n.length<=0||i.length<=1||((b=n.pop())==null||b.erase(),i.pop())},g=()=>{if(i.length<=1)return;const b=i[0],x=l();if(!x)return;b.x===x.x&&b.y===x.y&&b.z===x.z||h(b)},m=new D(s()?p.t("jig.line.firstPointOrContinue"):p.t("jig.line.firstPoint"));s()&&m.keywords.add(p.t("jig.line.keywords.continue.display"),p.t("jig.line.keywords.continue.global"),p.t("jig.line.keywords.continue.local"));const y=await S.instance.editor.getPoint(m);if(y.status===v.OK)c(y.value);else if(y.status===v.Keyword&&y.stringResult==="Continue"&&s())c(r());else return;class w{buildPrompt(){const x=new D(p.t("jig.line.nextPointWithOptions"));x.keywords.add(p.t("jig.line.keywords.undo.display"),p.t("jig.line.keywords.undo.global"),p.t("jig.line.keywords.undo.local")),i.length>1&&x.keywords.add(p.t("jig.line.keywords.close.display"),p.t("jig.line.keywords.close.global"),p.t("jig.line.keywords.close.local"));const A=l();return A&&(x.useDashedLine=!0,x.useBasePoint=!0,x.basePoint=new u.AcGePoint3d(A),x.jig=new Ni(e.view,A)),x}async handleResult(x){if(x.status===v.OK)return h(x.value),"continue";if(x.status===v.Keyword){const A=x.stringResult??"";return A==="Undo"?(d(),"continue"):A==="Close"&&i.length>1?(g(),"finish"):"continue"}return"finish"}}const C=new Te;C.setState(new w),await C.run(b=>S.instance.editor.getPoint(b)),o()}}const Fn={x:0,y:0,z:1};function Ri(a,e){return Math.hypot(e.x-a.x,e.y-a.y)}function Yl(a,e){return{x:(a.x+e.x)/2,y:(a.y+e.y)/2,z:0}}function oo(a,e){const t=Math.hypot(a,e);if(!(!Number.isFinite(t)||u.AcGeTol.isNonPositive(t)))return{x:a/t,y:e/t,z:0}}function Xl(a){return{x:-a.y,y:a.x,z:0}}function jn(a){return a*Math.PI/180}function ql(a){return a*180/Math.PI}function Zl(a){return ql(Math.atan2(a.y,a.x))}function zi(a,e,t){const i=jn(a);return Math.atan2(e*Math.sin(i),t*Math.cos(i))}function Jl(a,e){return oo(e.x-a.x,e.y-a.y)}function Vi(a,e,t,i,n=0,s=u.TAU){if(!(!Number.isFinite(t)||!Number.isFinite(i)||u.AcGeTol.isNonPositive(t)||u.AcGeTol.isNonPositive(i)))return t>=i?{center:{x:a.x,y:a.y,z:0},majorAxis:e,majorRadius:t,minorRadius:i,startAngle:n,endAngle:s}:{center:{x:a.x,y:a.y,z:0},majorAxis:Xl(e),majorRadius:i,minorRadius:t,startAngle:n,endAngle:s}}function ao(a){return new u.AcDbEllipse(a,Fn,{x:1,y:0,z:0},1e-6,1e-6,0,u.TAU)}function co(a,e){a.center=e.center,a.normal=Fn,a.majorAxisRadius=e.majorRadius,a.minorAxisRadius=e.minorRadius,a.startAngle=e.startAngle,a.endAngle=e.endAngle;const t=a;t._geo&&(t._geo.majorAxis=e.majorAxis)}class Ql extends ${constructor(e,t,i){super(e),this._builder=t,this._ellipse=ao(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&co(this._ellipse,t)}}class Nn extends ${constructor(e,t,i){super(e),this._builder=t,this._ellipse=ao(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&co(this._ellipse,t)}}class lo extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=new D(p.t("jig.ellipse.axisEndpointOrOptions"));this.addKeyword(t,"arc"),this.addKeyword(t,"center");const i=await S.instance.editor.getPoint(t);if(i.status===v.Keyword){const n=i.stringResult??"";n==="Center"?await this.runCenterFlow(e,!1):n==="Arc"&&await this.runArcEntryFlow(e);return}i.status===v.OK&&await this.runAxisEndFlow(e,i.value,!1)}addKeyword(e,t){e.keywords.add(p.t(`jig.ellipse.keywords.${t}.display`),p.t(`jig.ellipse.keywords.${t}.global`),p.t(`jig.ellipse.keywords.${t}.local`))}appendEllipse(e,t){const i=new u.AcDbEllipse(t.center,Fn,t.majorAxis,t.majorRadius,t.minorRadius,t.startAngle,t.endAngle);e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){J.emit("message",{message:p.t(`jig.ellipse.invalid.${e}`),type:"warning"})}async runArcEntryFlow(e){const t=new D(p.t("jig.ellipse.arcAxisEndpointOrCenter"));this.addKeyword(t,"center");const i=await S.instance.editor.getPoint(t);if(i.status===v.Keyword){i.stringResult==="Center"&&await this.runCenterFlow(e,!0);return}i.status===v.OK&&await this.runAxisEndFlow(e,i.value,!0)}async runCenterFlow(e,t){const i=new D(p.t("jig.ellipse.center")),n=await S.instance.editor.getPoint(i);if(n.status!==v.OK)return;const s=n.value,r=new D(p.t("jig.ellipse.firstAxisEndpoint"));r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(s),r.jig=new Ni(e.view,s);const o=await S.instance.editor.getPoint(r);if(o.status!==v.OK)return;const c=Jl(s,o.value);if(!c){this.warnInvalidInput("axis");return}const l=Ri(s,o.value),h=await this.promptOtherAxis(e,s,c,l,t);h&&this.appendEllipse(e,h)}async runAxisEndFlow(e,t,i){const n=new D(p.t("jig.ellipse.secondAxisEndpoint"));n.useDashedLine=!0,n.useBasePoint=!0,n.basePoint=new u.AcGePoint3d(t),n.jig=new Ni(e.view,t);const s=await S.instance.editor.getPoint(n);if(s.status!==v.OK)return;const r=s.value,o=r.x-t.x,c=r.y-t.y,l=oo(o,c);if(!l){this.warnInvalidInput("axis");return}const h=Yl(t,r),d=Ri(t,r)/2,g=await this.promptOtherAxis(e,h,l,d,i);g&&this.appendEllipse(e,g)}async promptOtherAxis(e,t,i,n,s){for(;;){const r=new D(p.t("jig.ellipse.otherAxisOrRotation"));this.addKeyword(r,"rotation"),r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(t),r.jig=new Ql(e.view,h=>{const d=Ri(t,h);return Vi(t,i,n,d)},t);const o=await S.instance.editor.getPoint(r);if(o.status===v.Keyword){if(o.stringResult!=="Rotation")return;const h=new X(p.t("jig.ellipse.rotationAngle"));h.allowNegative=!1,h.allowZero=!0,h.jig=new Nn(e.view,y=>{const w=n*Math.abs(Math.cos(jn(y)));return Vi(t,i,n,w)},t);const d=await S.instance.editor.getDouble(h);if(d.status!==v.OK)return;const g=n*Math.abs(Math.cos(jn(d.value??0))),m=Vi(t,i,n,g);if(!m){this.warnInvalidInput("rotation");continue}return s?await this.promptArcAngles(e,m):m}if(o.status!==v.OK)return;const c=Ri(t,o.value),l=Vi(t,i,n,c);if(!l){this.warnInvalidInput("otherAxis");continue}return s?await this.promptArcAngles(e,l):l}}async promptArcAngles(e,t){const i=Zl(t.majorAxis),n=new xe(p.t("jig.ellipse.arcStartAngle"));n.allowNegative=!0,n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t.center),n.baseAngle=i,n.jig=new Nn(e.view,l=>({...t,startAngle:zi(l,t.majorRadius,t.minorRadius),endAngle:u.TAU}),t.center);const s=await S.instance.editor.getAngle(n);if(s.status!==v.OK)return;const r=zi(s.value??0,t.majorRadius,t.minorRadius),o=new xe(p.t("jig.ellipse.arcEndAngle"));o.allowNegative=!0,o.useBasePoint=!0,o.useDashedLine=!0,o.basePoint=new u.AcGePoint3d(t.center),o.baseAngle=i,o.jig=new Nn(e.view,l=>({...t,startAngle:r,endAngle:zi(l,t.majorRadius,t.minorRadius)}),t.center);const c=await S.instance.editor.getAngle(o);if(c.status===v.OK)return{...t,startAngle:r,endAngle:zi(c.value??0,t.majorRadius,t.minorRadius)}}}const en=class en extends N{constructor(){super(),this.mode=j.Write}get settings(){return en._lastSettings}normalizeSysVarNumber(e,t){const i=Number(e);return Number.isFinite(i)?i:t}normalizePositiveSysVarNumber(e,t){const i=this.normalizeSysVarNumber(e,t);return i>0?i:t}sysVarRadiansToDegrees(e){return Math.round(e*180/Math.PI*1e6)/1e6}getSysVar(e,t,i){try{return e.getVar(t,i)}catch{return}}getDatabaseSysVarSettings(e){const t=this.settings;if(!(e instanceof u.AcDbDatabase))return t;try{const i=u.AcDbSysVarManager.instance(),n=this.getSysVar(i,u.AcDbSystemVariables.HPASSOC,e);return{...t,patternName:this.normalizePatternName(this.getSysVar(i,u.AcDbSystemVariables.HPNAME,e)??t.patternName),patternScale:this.normalizePositiveSysVarNumber(this.getSysVar(i,u.AcDbSystemVariables.HPSCALE,e),t.patternScale),patternAngleDeg:this.sysVarRadiansToDegrees(this.normalizeSysVarNumber(this.getSysVar(i,u.AcDbSystemVariables.HPANG,e),t.patternAngleDeg*Math.PI/180)),associative:n==null?t.associative:Number(n)!==0}}catch{return t}}getActiveSettings(){var e;return this.getDatabaseSysVarSettings((e=S.instance.curDocument)==null?void 0:e.database)}setActiveSysVar(e,t){var n;const i=(n=S.instance.curDocument)==null?void 0:n.database;i&&u.AcDbSysVarManager.instance().setVar(e,t,i)}normalizePatternName(e){const t=e.trim().toUpperCase();return t.length>0?t:u.HATCH_PATTERN_SOLID}styleToKeyword(e){switch(e){case u.AcDbHatchStyle.Outer:return"Outer";case u.AcDbHatchStyle.Ignore:return"Ignore";case u.AcDbHatchStyle.Normal:default:return"Normal"}}keywordToStyle(e){switch(e){case"Outer":return u.AcDbHatchStyle.Outer;case"Ignore":return u.AcDbHatchStyle.Ignore;case"Normal":default:return u.AcDbHatchStyle.Normal}}buildEdgesFromPolyline(e){var s;if(!e.closed||e.numberOfVertices<2)return[];const t=(s=e._geo)==null?void 0:s.vertices,i=t&&t.length>1?t.map(r=>({x:r.x,y:r.y,bulge:r.bulge})):Array.from({length:e.numberOfVertices},(r,o)=>{const c=e.getPoint2dAt(o);return{x:c.x,y:c.y,bulge:0}});if(i.length<2)return[];const n=[];for(let r=0;r<i.length;r++){const o=i[r],c=i[(r+1)%i.length],l=o.bulge??0;Math.abs(l)>1e-12?n.push(new u.AcGeCircArc2d(o,c,l)):n.push(new u.AcGeLine2d(o,c))}return n}buildEdgesFromEntity(e){if(e instanceof u.AcDbPolyline)return this.buildEdgesFromPolyline(e);if(e instanceof u.AcDbCircle){const t=e.center;return[new u.AcGeCircArc2d({x:t.x,y:t.y},e.radius,0,Math.PI*2,!1)]}if(e instanceof u.AcDbArc){if(!e.closed)return[];const t=e.center;return[new u.AcGeCircArc2d({x:t.x,y:t.y},e.radius,e.startAngle,e.endAngle,!1)]}return e instanceof u.AcDbLine?[new u.AcGeLine2d(e.startPoint,e.endPoint)]:[]}collectLoopsFromIds(e,t){const i=e.doc.database.tables.blockTable.modelSpace,n=[];return t.forEach(s=>{const r=i.getIdAt(s);r&&n.push(...this.buildEdgesFromEntity(r))}),this.buildLoopsFromEdges(n)}collectLoopsFromAllBoundaries(e){const t=e.doc.database.tables.blockTable.modelSpace,i=[];for(const n of t.newIterator())i.push(...this.buildEdgesFromEntity(n));return this.buildLoopsFromEdges(i)}buildLoopsFromEdges(e){if(e.length===0)return[];const t=[1e-6,1e-5,1e-4,.001];let i=[];for(const n of t){const s=u.AcGeLoop2d.buildFromEdges(e,n).filter(r=>r.closed&&r.numberOfEdges>0);s.length>i.length&&(i=s)}return i}signedArea(e){if(e.length<3)return 0;let t=0;for(let i=0,n=e.length-1;i<e.length;n=i++){const s=e[n],r=e[i];t+=s.x*r.y-r.x*s.y}return t*.5}isPointOnSegment(e,t,i,n,s,r,o=1e-8){const c=s-i,l=r-n,h=e-i,d=t-n;if(Math.abs(c*d-l*h)>o)return!1;const m=h*c+d*l;if(m<-o)return!1;const y=c*c+l*l;return!(m-y>o)}isPointInPolygon(e,t){if(t.length<3)return!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[s],o=t[n];if(this.isPointOnSegment(e.x,e.y,r.x,r.y,o.x,o.y))return!0}let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n].x,o=t[n].y,c=t[s].x,l=t[s].y;o>e.y!=l>e.y&&e.x<(c-r)*(e.y-o)/(l-o+Number.EPSILON)+r&&(i=!i)}return i}buildLoopInfos(e){const t=[];e.forEach(i=>{const n=i.getPoints(128).map(s=>({x:s.x,y:s.y}));n.length<3||t.push({loop:i,points:n,area:Math.abs(this.signedArea(n)),parent:null,children:[]})});for(let i=0;i<t.length;i++){const n=t[i].points[0];let s=null,r=Number.POSITIVE_INFINITY;for(let o=0;o<t.length;o++)i!==o&&(t[o].area<=t[i].area||this.isPointInPolygon(n,t[o].points)&&t[o].area<r&&(r=t[o].area,s=o));t[i].parent=s,s!=null&&t[s].children.push(i)}return t}resolveLoopsForPickPoint(e,t){const i=this.buildLoopInfos(t);if(!i.length)return[];const n=i.map((o,c)=>this.isPointInPolygon(e,o.points)?c:-1).filter(o=>o>=0);if(!n.length)return[];n.sort((o,c)=>i[o].area-i[c].area);const s=n[0],r=new Set([s]);return this.settings.style!==u.AcDbHatchStyle.Ignore&&i[s].children.forEach(o=>r.add(o)),[...r].map(o=>i[o].loop)}appendHatch(e,t){if(!t.length)return!1;const i=new u.AcDbHatch;e.doc.database instanceof u.AcDbDatabase&&(i.database=e.doc.database);const n=this.getDatabaseSysVarSettings(e.doc.database),s=this.normalizePatternName(n.patternName),r=s===u.HATCH_PATTERN_SOLID;return i.patternName=s,i.patternType=u.AcDbHatchPatternType.Predefined,i.patternScale=n.patternScale,i.patternAngle=n.patternAngleDeg*Math.PI/180,i.hatchStyle=n.style,i.isSolidFill=r,this.configureHatch(i),t.forEach(o=>i.add(o)),e.doc.database.tables.blockTable.modelSpace.appendEntity(i),!0}configureHatch(e){}async promptPatternName(){const e=new ce(p.t("jig.hatch.patternName"));e.allowEmpty=!1;const t=this.getActiveSettings();e.defaultValue=t.patternName,e.useDefaultValue=!0;const i=await S.instance.editor.getString(e);if(i.status!==v.OK)return;const n=this.normalizePatternName(i.stringResult??e.defaultValue);this.settings.patternName=n,this.setActiveSysVar(u.AcDbSystemVariables.HPNAME,n)}async promptPatternScale(){const e=new X(p.t("jig.hatch.scale"));e.allowNone=!0,e.allowNegative=!1,e.allowZero=!1;const t=this.getActiveSettings();e.defaultValue=t.patternScale,e.useDefaultValue=!0;const i=await S.instance.editor.getDouble(e);if(i.status!==v.OK)return;const n=i.value??e.defaultValue;n>0&&(this.settings.patternScale=n,this.setActiveSysVar(u.AcDbSystemVariables.HPSCALE,n))}async promptPatternAngle(){const e=new X(p.t("jig.hatch.angle"));e.allowNone=!0,e.allowNegative=!0,e.allowZero=!0;const t=this.getActiveSettings();e.defaultValue=t.patternAngleDeg,e.useDefaultValue=!0;const i=await S.instance.editor.getDouble(e);if(i.status!==v.OK)return;const n=i.value??e.defaultValue;this.settings.patternAngleDeg=n,this.setActiveSysVar(u.AcDbSystemVariables.HPANG,n*Math.PI/180)}async promptStyle(){const e=this.getActiveSettings(),t=this.styleToKeyword(e.style),i=new Y(`${p.t("jig.hatch.style")} <${t}>`);i.allowNone=!0,i.keywords.add(p.t("jig.hatch.keywords.normal.display"),p.t("jig.hatch.keywords.normal.global"),p.t("jig.hatch.keywords.normal.local")),i.keywords.add(p.t("jig.hatch.keywords.outer.display"),p.t("jig.hatch.keywords.outer.global"),p.t("jig.hatch.keywords.outer.local")),i.keywords.add(p.t("jig.hatch.keywords.ignore.display"),p.t("jig.hatch.keywords.ignore.global"),p.t("jig.hatch.keywords.ignore.local"));const n=await S.instance.editor.getKeywords(i);(n.status===v.OK||n.status===v.Keyword)&&n.stringResult&&(this.settings.style=this.keywordToStyle(n.stringResult))}async promptAssociative(){const t=this.getActiveSettings().associative?"Yes":"No",i=new Y(`${p.t("jig.hatch.associative")} <${t}>`);i.allowNone=!0,i.keywords.add(p.t("jig.hatch.keywords.yes.display"),p.t("jig.hatch.keywords.yes.global"),p.t("jig.hatch.keywords.yes.local")),i.keywords.add(p.t("jig.hatch.keywords.no.display"),p.t("jig.hatch.keywords.no.global"),p.t("jig.hatch.keywords.no.local"));const n=await S.instance.editor.getKeywords(i);if(n.status===v.OK||n.status===v.Keyword){const s=n.stringResult==="Yes";this.settings.associative=s,this.setActiveSysVar(u.AcDbSystemVariables.HPASSOC,s?1:0)}}async doSelectObjects(e){const t=new je(p.t("jig.hatch.select")),i=await S.instance.editor.getSelection(t);if(i.status!==v.OK||!i.value)return!1;const n=this.collectLoopsFromIds(e,i.value.ids);return n.length?this.appendHatch(e,n):!1}async doPickPoints(e){const t=this.collectLoopsFromAllBoundaries(e);if(!t.length)return!1;let i=!1;for(;;){const n=new D(p.t("jig.hatch.pickPoint"));n.allowNone=!0;const s=await S.instance.editor.getPoint(n);if(s.status!==v.OK||!s.value)break;const r=this.resolveLoopsForPickPoint(s.value,t);r.length&&this.appendHatch(e,r)&&(i=!0)}return i}async execute(e){let t=!0;for(;t;){const i=new Le(p.t("jig.hatch.prompt"));i.allowNone=!0,i.setRejectMessage(p.t("jig.hatch.invalidBoundary")),i.addAllowedClass("Polyline"),i.addAllowedClass("Circle"),i.addAllowedClass("Arc"),i.addAllowedClass("Line"),i.keywords.add(p.t("jig.hatch.keywords.pick.display"),p.t("jig.hatch.keywords.pick.global"),p.t("jig.hatch.keywords.pick.local")),i.keywords.add(p.t("jig.hatch.keywords.select.display"),p.t("jig.hatch.keywords.select.global"),p.t("jig.hatch.keywords.select.local")),i.keywords.add(p.t("jig.hatch.keywords.pattern.display"),p.t("jig.hatch.keywords.pattern.global"),p.t("jig.hatch.keywords.pattern.local")),i.keywords.add(p.t("jig.hatch.keywords.scale.display"),p.t("jig.hatch.keywords.scale.global"),p.t("jig.hatch.keywords.scale.local")),i.keywords.add(p.t("jig.hatch.keywords.angle.display"),p.t("jig.hatch.keywords.angle.global"),p.t("jig.hatch.keywords.angle.local")),i.keywords.add(p.t("jig.hatch.keywords.style.display"),p.t("jig.hatch.keywords.style.global"),p.t("jig.hatch.keywords.style.local")),i.keywords.add(p.t("jig.hatch.keywords.associative.display"),p.t("jig.hatch.keywords.associative.global"),p.t("jig.hatch.keywords.associative.local"));const n=await S.instance.editor.getEntity(i);if(n.status===v.OK&&n.objectId){const s=this.collectLoopsFromIds(e,[n.objectId]);if(!s.length)continue;this.appendHatch(e,s);continue}if(n.status===v.Keyword){const s=n.stringResult??"";s==="PickPoints"?await this.doPickPoints(e):s==="SelectObjects"?await this.doSelectObjects(e):s==="Pattern"?await this.promptPatternName():s==="Scale"?await this.promptPatternScale():s==="Angle"?await this.promptPatternAngle():s==="HatchStyle"?await this.promptStyle():s==="AssociativeMode"&&await this.promptAssociative();continue}t=!1}}};en._lastSettings={patternName:u.HATCH_PATTERN_SOLID,patternScale:1,patternAngleDeg:0,style:u.AcDbHatchStyle.Normal,associative:!0};let Gi=en;class ho extends ${constructor(e,t,i){if(super(e),this._mline=new u.AcDbMLine,this._points=t,this._resolveState=i,t.length>0){const n=this._resolveState();Rn(this._mline,t,n.styleName,n.justification,n.scale,!1,n.elementOffsets)}}get entity(){return this._mline}update(e){if(this._points.length<=0)return;const t=[...this._points,new u.AcGePoint3d(e)],i=this._resolveState();Rn(this._mline,t,i.styleName,i.justification,i.scale,!1,i.elementOffsets)}}class uo extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=e.doc.database;let i=u.AcDbMLineJustification.Zero,n=t.cmlscale??1,s=t.cmlstyle||"STANDARD";const r=[];let o=!1;const c=()=>{const _=t.objects.mlineStyle.getAt(s);return nh((_==null?void 0:_.elements)??[],i,n)},l=_=>r.push(new u.AcGePoint3d(_)),h=()=>{r.length>1&&r.pop()},d=()=>{if(r.length<=1)return;const _=r[0],L=r[r.length-1];rh(_,L)||l(_),o=!0},g=async()=>{const _=new Y(p.t("jig.mline.justificationPrompt"));_.allowNone=!0,_.keywords.add(p.t("jig.mline.keywords.top.display"),p.t("jig.mline.keywords.top.global"),p.t("jig.mline.keywords.top.local")),_.keywords.add(p.t("jig.mline.keywords.zero.display"),p.t("jig.mline.keywords.zero.global"),p.t("jig.mline.keywords.zero.local")),_.keywords.add(p.t("jig.mline.keywords.bottom.display"),p.t("jig.mline.keywords.bottom.global"),p.t("jig.mline.keywords.bottom.local"));const L=await S.instance.editor.getKeywords(_);if(L.status===v.None)return!0;if(L.status!==v.Keyword)return!1;const T=L.stringResult??"";return T==="Top"?i=u.AcDbMLineJustification.Top:T==="Bottom"?i=u.AcDbMLineJustification.Bottom:i=u.AcDbMLineJustification.Zero,!0},m=async()=>{const _=new X(p.t("jig.mline.scalePrompt"));_.allowNone=!0,_.allowZero=!0,_.allowNegative=!0,_.useDefaultValue=!0,_.defaultValue=n;const L=await S.instance.editor.getDouble(_);return L.status===v.None?!0:L.status!==v.OK?!1:(n=L.value??n,!0)},y=()=>{const _=[...t.objects.mlineStyle.entries()].map(([L])=>L);if(_.length<=0){S.instance.editor.showMessage(p.t("jig.mline.styleListEmpty"),"warning");return}S.instance.editor.showMessage(`${p.t("jig.mline.styleListHeader")} ${_.join(", ")}`,"info")},w=async()=>{for(;;){const _=new ce(p.t("jig.mline.stylePrompt"));_.allowEmpty=!1,_.allowSpaces=!1;const L=await S.instance.editor.getString(_);if(L.status!==v.OK)return!1;const T=(L.stringResult??"").trim();if(T){if(T==="?"){y();continue}return s=T,!0}}},C=async _=>_==="Justification"?await g():_==="Scale"?await m():_==="Style"?await w():!0;for(;;){const _=new D(p.t("jig.mline.startPointWithOptions"));_.keywords.add(p.t("jig.mline.keywords.justification.display"),p.t("jig.mline.keywords.justification.global"),p.t("jig.mline.keywords.justification.local")),_.keywords.add(p.t("jig.mline.keywords.scale.display"),p.t("jig.mline.keywords.scale.global"),p.t("jig.mline.keywords.scale.local")),_.keywords.add(p.t("jig.mline.keywords.style.display"),p.t("jig.mline.keywords.style.global"),p.t("jig.mline.keywords.style.local"));const L=await S.instance.editor.getPoint(_);if(L.status===v.OK){l(L.value);break}if(L.status!==v.Keyword||!await C(L.stringResult??""))return}class b{buildPrompt(){const L=new D(p.t("jig.mline.nextPointWithOptions"));return L.keywords.add(p.t("jig.mline.keywords.justification.display"),p.t("jig.mline.keywords.justification.global"),p.t("jig.mline.keywords.justification.local")),L.keywords.add(p.t("jig.mline.keywords.scale.display"),p.t("jig.mline.keywords.scale.global"),p.t("jig.mline.keywords.scale.local")),L.keywords.add(p.t("jig.mline.keywords.style.display"),p.t("jig.mline.keywords.style.global"),p.t("jig.mline.keywords.style.local")),L.keywords.add(p.t("jig.mline.keywords.undo.display"),p.t("jig.mline.keywords.undo.global"),p.t("jig.mline.keywords.undo.local")),r.length>1&&L.keywords.add(p.t("jig.mline.keywords.close.display"),p.t("jig.mline.keywords.close.global"),p.t("jig.mline.keywords.close.local")),L.useDashedLine=!0,L.useBasePoint=!0,L.basePoint=new u.AcGePoint3d(r[r.length-1]),L.jig=new ho(e.view,r,()=>({justification:i,scale:n,styleName:s,elementOffsets:c()})),L}async handleResult(L){if(L.status===v.OK)return l(L.value),"continue";if(L.status!==v.Keyword)return"finish";const T=L.stringResult??"";return T==="Undo"?(h(),"continue"):T==="Close"&&r.length>1?(d(),"finish"):await C(T)?"continue":"finish"}}const x=new Te;if(x.setState(new b),await x.run(_=>S.instance.editor.getPoint(_)),r.length<2)return;const A=new u.AcDbMLine;Rn(A,r,s,i,n,o,c()),t.tables.blockTable.modelSpace.appendEntity(A),t.cmlstyle=s,t.cmlscale=n}}function Rn(a,e,t,i,n,s,r){if(e.length<=0){a.clearSegments();return}if(a.styleName=t,a.styleObjectHandle="",a.justification=i,a.scale=n,a.styleCount=r.length,a.closed=s,a.startPosition=e[0],e.length<2){a.clearSegments();return}a.segments=eh(e,r)}function eh(a,e){const t=th(a);return a.slice(1).map((i,n)=>{const s=n+1,r=ih(t,s);return{position:i,direction:t[Math.min(s,t.length-1)],miterDirection:r.direction,elements:e.map(o=>({parameterCount:1,parameters:[o*r.offsetScale],fillCount:0,fillParameters:[]}))}})}function th(a){const e=[];for(let t=0;t<a.length-1;t++){const i=a[t],n=a[t+1],s=zn({x:n.x-i.x,y:n.y-i.y,z:n.z-i.z});e.push(s??{x:1,y:0,z:0})}return e}function ih(a,e){if(a.length<=0)return{direction:{x:0,y:1,z:0},offsetScale:1};if(e<=0)return{direction:$i(a[0]),offsetScale:1};if(e>=a.length)return{direction:$i(a[a.length-1]),offsetScale:1};const t=$i(a[e-1]),i=$i(a[e]),n=zn({x:t.x+i.x,y:t.y+i.y,z:t.z+i.z});if(!n)return{direction:i,offsetScale:1};const s=Math.abs(sh(n,i));return u.AcGeTol.isNonPositive(s)?{direction:n,offsetScale:1}:{direction:n,offsetScale:1/s}}function nh(a,e,t){if(a.length<=0)return[];let i=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const r of a)r.offset<i&&(i=r.offset),r.offset>n&&(n=r.offset);let s=0;return e===u.AcDbMLineJustification.Top?s=-n:e===u.AcDbMLineJustification.Bottom&&(s=-i),a.map(r=>(r.offset+s)*t)}function $i(a){return zn({x:-a.y,y:a.x,z:0})??{x:0,y:1,z:0}}function zn(a){const e=Math.sqrt(a.x*a.x+a.y*a.y+a.z*a.z);if(u.AcGeTol.isPositive(e))return{x:a.x/e,y:a.y/e,z:a.z/e}}function sh(a,e){return a.x*e.x+a.y*e.y+a.z*e.z}function rh(a,e){return u.DEFAULT_TOL.equalPoint3d(a,e)}class po extends N{constructor(){super(),this.mtextEditor=new Re,this.mode=j.Write}async execute(e){const t=new ti(p.t("main.inputManager.firstCorner"),p.t("main.inputManager.secondCorner"));t.useBasePoint=!1,t.useDashedLine=!1;const i=await S.instance.editor.getBox(t);if(i.status!==v.OK||!i.value)return;const n=i.value,s=Math.max(Math.abs(n.max.x-n.min.x),1e-4),r=e.view,o=this.pixelsToWorldY(r,24),c={x:n.min.x,y:n.max.y,z:0},l=Array.from(new Set(S.instance.avaiableFonts.flatMap(m=>m.name).map(m=>m.trim()).filter(m=>m.length>0))),h=await this.mtextEditor.open({view:r,location:c,width:s,textHeight:o,toolbarFontFamilies:l});if(!h||!h.contents.trim())return;const g=new u.AcDbMText;g.location=h.location,g.contents=h.contents,g.width=h.width,g.height=h.height,g.lineSpacingFactor=h.lineSpacingFactor,g.attachmentPoint=h.attachmentPoint,e.doc.database.tables.blockTable.modelSpace.appendEntity(g)}pixelsToWorldY(e,t){const i=e.screenToWorld({x:0,y:0}),n=e.screenToWorld({x:0,y:t});return Math.max(Math.abs(n.y-i.y),1e-4)}}class go extends N{constructor(){super(),this.mode=j.Write}async execute(e){for(;;){const t=new D(p.t("jig.point.point")),i=await S.instance.editor.getPoint(t);if(i.status!==v.OK||!i.value)return;const n=new u.AcDbPoint;n.position=new u.AcGePoint3d(i.value),e.doc.database.tables.blockTable.modelSpace.appendEntity(n)}}}const oh=3,ah=1024;function ch(a,e){return Math.hypot(e.x-a.x,e.y-a.y)}function Vn(a,e){a.reset(!1),e.forEach((t,i)=>a.addVertexAt(i,t)),a.closed=!0}function mo(a,e,t,i){const n=ch(a,t);if(u.AcGeTol.isNonPositive(n))return;const s=Math.PI*2/e,r=Math.atan2(t.y-a.y,t.x-a.x),o=i==="Inscribed"?n:n/Math.cos(Math.PI/e);if(!Number.isFinite(o)||u.AcGeTol.isNonPositive(o))return;const c=i==="Inscribed"?r:r+s/2,l=[];for(let h=0;h<e;h++){const d=c+h*s;l.push(new u.AcGePoint2d(a.x+o*Math.cos(d),a.y+o*Math.sin(d)))}return l}function yo(a,e,t){const i=e.x-a.x,n=e.y-a.y,s=Math.hypot(i,n);if(u.AcGeTol.isNonPositive(s))return;const r=Math.PI*2/t,o=[new u.AcGePoint2d(a),new u.AcGePoint2d(e)];let c=e.x,l=e.y,h=i,d=n;for(let g=2;g<t;g++){const m=h*Math.cos(r)-d*Math.sin(r),y=h*Math.sin(r)+d*Math.cos(r);c+=m,l+=y,o.push(new u.AcGePoint2d(c,l)),h=m,d=y}return o}class lh extends ${constructor(e,t,i,n){super(e),this._polyline=new u.AcDbPolyline,this._center=t,this._sides=i,this._modeProvider=n}get entity(){return this._polyline}update(e){const t=mo(this._center,this._sides,e,this._modeProvider());t&&Vn(this._polyline,t)}}class hh extends ${constructor(e,t,i){super(e),this._polyline=new u.AcDbPolyline,this._firstPoint=t,this._sides=i}get entity(){return this._polyline}update(e){const t=yo(this._firstPoint,e,this._sides);t&&Vn(this._polyline,t)}}const Wt=class Wt extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=await this.promptSides();if(t==null)return;const i=new D(p.t("jig.polygon.centerOrEdge"));this.addKeyword(i,"edge");const n=await S.instance.editor.getPoint(i);if(n.status===v.Keyword){n.stringResult==="Edge"&&await this.runEdgeFlow(e,t);return}n.status===v.OK&&await this.runCenterFlow(e,t,n.value)}addKeyword(e,t){e.keywords.add(p.t(`jig.polygon.keywords.${t}.display`),p.t(`jig.polygon.keywords.${t}.global`),p.t(`jig.polygon.keywords.${t}.local`))}appendPolygon(e,t){const i=new u.AcDbPolyline;Vn(i,t),e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){J.emit("message",{message:p.t(`jig.polygon.invalid.${e}`),type:"warning"})}async promptSides(){for(;;){const e=Wt._lastSides,t=new ce(`${p.t("jig.polygon.numberOfSides")} <${e}>`);t.allowEmpty=!0,t.allowSpaces=!1;const i=await S.instance.editor.getString(t);if(i.status!==v.OK)return;const n=(i.stringResult??"").trim(),s=n===""?e:Number(n);if(Number.isInteger(s)&&s>=oh&&s<=ah)return Wt._lastSides=s,s;this.warnInvalidInput("sides")}}async runCenterFlow(e,t,i){let n="Inscribed";for(;;){const s=new D(p.t("jig.polygon.radiusOrType"));this.addKeyword(s,"inscribed"),this.addKeyword(s,"circumscribed"),s.useDashedLine=!0,s.useBasePoint=!0,s.basePoint=new u.AcGePoint3d(i),s.jig=new lh(e.view,i,t,()=>n);const r=await S.instance.editor.getPoint(s);if(r.status===v.Keyword){const c=r.stringResult??"";if(c==="Inscribed"){n="Inscribed";continue}if(c==="Circumscribed"){n="Circumscribed";continue}return}if(r.status!==v.OK)return;const o=mo(i,t,r.value,n);if(!o){this.warnInvalidInput("radius");continue}this.appendPolygon(e,o);return}}async runEdgeFlow(e,t){const i=new D(p.t("jig.polygon.edgeStart")),n=await S.instance.editor.getPoint(i);if(n.status!==v.OK)return;const s=n.value,r=new D(p.t("jig.polygon.edgeEnd"));r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(s),r.jig=new hh(e.view,s,t);const o=await S.instance.editor.getPoint(r);if(o.status!==v.OK)return;const c=yo(s,o.value,t);if(!c){this.warnInvalidInput("edge");return}this.appendPolygon(e,c)}};Wt._lastSides=4;let Ki=Wt;class fo extends ${constructor(e,t,i,n,s){super(e),this._hasTemp=!1,this._polyline=new u.AcDbPolyline,this._points=t,this._bulges=i,this._currentBulge=n,this._bulgeProvider=s,this._baseCount=t.length,this._appliedBulge=this._bulges[this._baseCount-1],this.addBaseVertices()}get entity(){return this._polyline}update(e){var s;if(this._baseCount===0)return;this._hasTemp&&(this._polyline.removeVertexAt(this._baseCount),this._hasTemp=!1);const t=this._baseCount-1,n=((s=this._bulgeProvider)==null?void 0:s.call(this,e))??this._currentBulge??this._bulges[t];if(n!==this._appliedBulge){const r=this._points[t];this._polyline.removeVertexAt(t),this._polyline.addVertexAt(t,r,n),this._appliedBulge=n}this._polyline.addVertexAt(this._baseCount,new u.AcGePoint2d(e),void 0),this._hasTemp=!0}addBaseVertices(){this._points.forEach((e,t)=>this._polyline.addVertexAt(t,e,this._bulges[t]))}}class uh extends ${constructor(e,t,i){super(e),this._polyline=new u.AcDbPolyline,t.forEach((n,s)=>this._polyline.addVertexAt(s,n,i[s]))}get entity(){return this._polyline}update(e){}}class wo extends N{constructor(){super(),this.mode=j.Write}complementBulge(e){if(u.AcGeTol.equalToZero(e))return e;const t=4*Math.atan(e),n=(Math.sign(t)||1)*(Math.PI*2-Math.abs(t));return u.AcGeTol.equalToZero(n)?e:Math.tan(n/4)}flipArcBulgeForCtrl(e){return-this.complementBulge(e)}computeArcCenterFromBulge(e,t,i){const n=t.x-e.x,s=t.y-e.y,r=Math.hypot(n,s);if(u.AcGeTol.isNonPositive(r))return;const o=(e.x+t.x)/2,c=(e.y+t.y)/2,l=-s/r,h=n/r,d=r/2*i;return{x:o+l*d,y:c+h*d}}getGeometricTangentAtPoint(e,t,i){const n=e.x-t.x,s=e.y-t.y;return i?Math.atan2(-s,n):Math.atan2(s,-n)}getArcTangentAtEnd(e,t,i){const n=this.computeArcCenterFromBulge(e,t,i);if(n)return this.getGeometricTangentAtPoint(t,n,i>=0)}getIncomingTangentRadians(e,t){if(e.length<2)return 0;const i=e[e.length-1],n=e[e.length-2],s=t[e.length-2];return s==null||u.AcGeTol.equalToZero(s)?Math.atan2(i.y-n.y,i.x-n.x):this.getArcTangentAtEnd(n,i,s)??Math.atan2(i.y-n.y,i.x-n.x)}computeBulgeFromTangentDirection(e,t,i){const n=Math.cos(i),s=Math.sin(i),r=t.x-e.x,o=t.y-e.y,c=-s,l=n,h=2*(r*c+o*l);if(u.AcGeTol.equalToZero(h))return;const d=(r*r+o*o)/h;if(!Number.isFinite(d))return;const g={x:e.x+c*d,y:e.y+l*d};return this.computeBulgeFromCenterWithTangent(e,t,g,i)}computeBulgeFromCenterWithTangent(e,t,i,n){const s=e.x-i.x,r=e.y-i.y,o=t.x-i.x,c=t.y-i.y,l=Math.cos(n),h=Math.sin(n),d=t.x-e.x,g=t.y-e.y,m=s*h-r*l;let y;u.AcGeTol.isPositive(Math.abs(m))?y=m>0:y=d*h-g*l>=0;const w=Math.atan2(r,s),C=Math.atan2(c,o);let b;if(y?(b=C-w,u.AcGeTol.isNonPositive(b)&&(b+=Math.PI*2)):(b=w-C,u.AcGeTol.isNonPositive(b)&&(b+=Math.PI*2)),!!u.AcGeTol.great(u.TAU-b,0))return y?Math.tan(b/4):-Math.tan(b/4)}computeBulgeFromTangentAndIncludedAngle(e,t,i,n){const s=Math.cos(i),r=Math.sin(i),o=t.x-e.x,c=t.y-e.y,l=-r,h=s,d=2*(o*l+c*h);if(u.AcGeTol.equalToZero(d))return;const g=(o*o+c*c)/d;if(!Number.isFinite(g))return;const m={x:e.x+l*g,y:e.y+h*g},y=this.computeBulgeFromCenterWithTangent(e,t,m,i);if(y==null)return;const w=Math.tan(n/4);if(Number.isFinite(w))return Math.sign(y)*Math.abs(w)}computeBulgeFromCenter(e,t,i){const n=e.x-i.x,s=e.y-i.y,r=t.x-i.x,o=t.y-i.y,c=n*o-s*r,l=n*r+s*o,h=Math.atan2(c,l);if(Number.isFinite(h))return Math.tan(h/4)}computeCircleCenter(e,t,i){const n=e.x,s=e.y,r=t.x,o=t.y,c=i.x,l=i.y,h=n-r,d=s-o,g=n-c,m=s-l,y=(n*n-r*r+s*s-o*o)/2,w=(n*n-c*c+s*s-l*l)/2,C=h*m-d*g;if(u.AcGeTol.equalToZero(C))return;const b=(m*y-d*w)/C,x=(-g*y+h*w)/C;return new u.AcGePoint2d(b,x)}computeBulgeFromThreePoints(e,t,i){const n=this.computeCircleCenter(e,t,i);if(n)return this.computeBulgeFromCenter(e,i,n)}computeBulgeFromRadius(e,t,i){const n=Math.abs(i),s=t.x-e.x,r=t.y-e.y,o=Math.hypot(s,r);if(o===0||o>2*n)return;const c=(e.x+t.x)/2,l=(e.y+t.y)/2,h=Math.sqrt(Math.max(0,n*n-o*o/4)),d=-r/o,g=s/o,m=i>=0?1:-1,y=c+d*h*m,w=l+g*h*m,C=new u.AcGePoint2d(y,w);return this.computeBulgeFromCenter(e,t,C)}async execute(e){S.instance.editor.resetInputToggles();const t=[],i=[];let n=!1;const s=k=>k==null?k:S.instance.editor.getInputToggles().ctrlArcFlip?this.flipArcBulgeForCtrl(k):k,r=(k,E,M)=>this.computeBulgeFromCenter(k,E,M),o=(k,E,M)=>this.computeBulgeFromThreePoints(k,E,M),c=(k,E,M)=>this.computeBulgeFromRadius(k,E,M),l=()=>this.getIncomingTangentRadians(t,i),h=k=>{const E=y();if(E)return this.computeBulgeFromTangentDirection(E,k,l())},d=(k,E,M,F)=>this.computeBulgeFromTangentAndIncludedAngle(k,E,M,F),g=()=>new uh(e.view,t,i),m=(k,E)=>new fo(e.view,t,i,k,E),y=()=>t[t.length-1],w=k=>{t.length>0&&(i[t.length-1]=k)},C=k=>{t.push(new u.AcGePoint2d(k)),i.push(void 0)},b=()=>{t.length<=1||(t.pop(),i.pop(),i[i.length-1]=void 0)},x=k=>k!==v.OK&&k!==v.Keyword;class A{constructor(E){this.machine=E}buildPrompt(){const E=new D(p.t("jig.polyline.nextPointWithOptions"));E.keywords.add(p.t("jig.polyline.keywords.arc.display"),p.t("jig.polyline.keywords.arc.global"),p.t("jig.polyline.keywords.arc.local")),E.keywords.add(p.t("jig.polyline.keywords.undo.display"),p.t("jig.polyline.keywords.undo.global"),p.t("jig.polyline.keywords.undo.local")),E.keywords.add(p.t("jig.polyline.keywords.close.display"),p.t("jig.polyline.keywords.close.global"),p.t("jig.polyline.keywords.close.local")),E.useDashedLine=!0,E.useBasePoint=!0;const M=y();return M&&(E.basePoint=new u.AcGePoint3d(M)),E.jig=m(void 0),E}async handleResult(E){if(E.status===v.Keyword){const M=E.stringResult??"";if(M==="Arc")this.machine.setState(new _(this.machine));else if(M==="Undo")b();else if(M==="Close"&&t.length>1)return n=!0,w(void 0),"finish";return"continue"}return E.status===v.OK?(w(void 0),C(E.value),"continue"):"finish"}}class _{constructor(E){this.machine=E}buildPrompt(){const E=new D(p.t("jig.polyline.nextPointWithArcOptions"));E.keywords.add(p.t("jig.polyline.keywords.angle.display"),p.t("jig.polyline.keywords.angle.global"),p.t("jig.polyline.keywords.angle.local")),E.keywords.add(p.t("jig.polyline.keywords.center.display"),p.t("jig.polyline.keywords.center.global"),p.t("jig.polyline.keywords.center.local")),E.keywords.add(p.t("jig.polyline.keywords.secondPoint.display"),p.t("jig.polyline.keywords.secondPoint.global"),p.t("jig.polyline.keywords.secondPoint.local")),E.keywords.add(p.t("jig.polyline.keywords.radius.display"),p.t("jig.polyline.keywords.radius.global"),p.t("jig.polyline.keywords.radius.local")),E.keywords.add(p.t("jig.polyline.keywords.line.display"),p.t("jig.polyline.keywords.line.global"),p.t("jig.polyline.keywords.line.local")),E.keywords.add(p.t("jig.polyline.keywords.undo.display"),p.t("jig.polyline.keywords.undo.global"),p.t("jig.polyline.keywords.undo.local")),E.keywords.add(p.t("jig.polyline.keywords.close.display"),p.t("jig.polyline.keywords.close.global"),p.t("jig.polyline.keywords.close.local")),E.useDashedLine=!0,E.useBasePoint=!0;const M=y();return M&&(E.basePoint=new u.AcGePoint3d(M)),E.jig=m(void 0,F=>s(h(F))),E}async handleResult(E){if(E.status===v.OK){const z=h(E.value);return z===void 0||(w(s(z)),C(E.value)),"continue"}if(E.status!==v.Keyword)return"finish";const M=E.stringResult??"";if(M==="Line")return this.machine.setState(new A(this.machine)),"continue";if(M==="Undo")return b(),"continue";if(M==="Close"&&t.length>1)return n=!0,w(void 0),"finish";const F=y();if(!F)return"finish";if(M==="Angle"){const z=new X(p.t("jig.polyline.arcAngle"));z.jig=g();const U=await S.instance.editor.getDouble(z);if(x(U.status))return"finish";const V=new D(p.t("jig.polyline.arcEndPoint"));V.useDashedLine=!0,V.useBasePoint=!0,V.basePoint=new u.AcGePoint3d(F);const K=(U.value??0)*(Math.PI/180),G=l();V.jig=m(void 0,_e=>s(d(F,_e,G,K)));const W=await S.instance.editor.getPoint(V);if(x(W.status))return"finish";const ee=d(F,W.value,G,K);return ee===void 0||(w(s(ee)),C(W.value)),"continue"}if(M==="Center"){const z=new D(p.t("jig.polyline.arcCenter"));z.jig=g();const U=await S.instance.editor.getPoint(z);if(x(U.status))return"finish";const V=new D(p.t("jig.polyline.arcEndPoint"));V.useDashedLine=!0,V.useBasePoint=!0,V.basePoint=new u.AcGePoint3d(F),V.jig=m(void 0,W=>s(r(F,W,U.value)));const K=await S.instance.editor.getPoint(V);if(x(K.status))return"finish";const G=r(F,K.value,U.value);return G===void 0||(w(s(G)),C(K.value)),"continue"}if(M==="SecondPoint"){const z=new D(p.t("jig.polyline.arcSecondPoint"));z.jig=g(),z.useDashedLine=!0,z.useBasePoint=!0,z.basePoint=new u.AcGePoint3d(F);const U=await S.instance.editor.getPoint(z);if(x(U.status))return"finish";const V=new D(p.t("jig.polyline.arcEndPoint"));V.useDashedLine=!0,V.useBasePoint=!0,V.basePoint=new u.AcGePoint3d(F),V.jig=m(void 0,W=>s(o(F,U.value,W)));const K=await S.instance.editor.getPoint(V);if(x(K.status))return"finish";const G=o(F,U.value,K.value);return G===void 0||(w(s(G)),C(K.value)),"continue"}if(M==="Radius"){const z=new X(p.t("jig.polyline.arcRadius"));z.jig=g();const U=await S.instance.editor.getDouble(z);if(x(U.status))return"finish";const V=new D(p.t("jig.polyline.arcEndPoint"));V.useDashedLine=!0,V.useBasePoint=!0,V.basePoint=new u.AcGePoint3d(F),V.jig=m(void 0,W=>s(c(F,W,U.value??0)));const K=await S.instance.editor.getPoint(V);if(x(K.status))return"finish";const G=c(F,K.value,U.value??0);return G===void 0||(w(s(G)),C(K.value)),"continue"}return"continue"}}const L=new D(p.t("jig.polyline.firstPoint")),T=await S.instance.editor.getPoint(L);if(T.status!==v.OK)return;C(T.value);const O=new Te;if(O.setState(new A(O)),await O.run(k=>S.instance.editor.getPoint(k)),t.length>=2){const k=e.doc.database,E=new u.AcDbPolyline;t.forEach((M,F)=>E.addVertexAt(F,M,i[F])),n&&(E.closed=!0),k.tables.blockTable.modelSpace.appendEntity(E)}}}function bo(a,e){const t=new u.AcGePoint3d(e).sub(a);if(u.AcGeTol.isPositive(t.length()))return t.normalize()}class dh extends ${constructor(e,t){super(e),this._startPoint=new u.AcGePoint3d(t),this._ray=new u.AcDbRay,this._ray.basePoint=new u.AcGePoint3d(t),this._ray.unitDir=new u.AcGePoint3d(1,0,0)}get entity(){return this._ray}update(e){const t=bo(this._startPoint,e);t&&(this._ray.basePoint=new u.AcGePoint3d(this._startPoint),this._ray.unitDir=t)}}class xo extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=e.doc.database,i=new D(p.t("jig.ray.startPoint")),n=await S.instance.editor.getPoint(i);if(n.status!==v.OK)return;const s=new u.AcGePoint3d(n.value);for(;;){const r=new D(p.t("jig.ray.throughPoint"));r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(s),r.jig=new dh(e.view,s);const o=await S.instance.editor.getPoint(r);if(o.status!==v.OK)break;const c=bo(s,o.value);if(!c)continue;const l=new u.AcDbRay;l.basePoint=new u.AcGePoint3d(s),l.unitDir=c,t.tables.blockTable.modelSpace.appendEntity(l)}}}const ph=Math.tan(Math.PI/8),gh={chamferDist1:0,chamferDist2:0,filletRadius:0,width:0,elevation:0,thickness:0,rotation:0};function Ke(a,e){a.keywords.add(p.t(`jig.rect.keywords.${e}.display`),p.t(`jig.rect.keywords.${e}.global`),p.t(`jig.rect.keywords.${e}.local`))}function mh(a,e){a.keywords.add(p.t(`jig.rect.keywords.${e}.display`),p.t(`jig.rect.keywords.${e}.global`),p.t(`jig.rect.keywords.${e}.local`))}function Gn(a){J.emit("message",{message:p.t(`jig.rect.${a}`),type:"warning"})}function yh(a,e,t){const i=Math.cos(t),n=Math.sin(t);return new u.AcGePoint2d(a.x+e.x*i-e.y*n,a.y+e.x*n+e.y*i)}function fh(a,e,t){const i=e.x-a.x,n=e.y-a.y,s=Math.cos(t),r=Math.sin(t);return new u.AcGePoint2d(i*s+n*r,-i*r+n*s)}function ht(a){return Number.isFinite(a??NaN)?Math.max(0,a??0):0}function $n(a,e){return[{point:new u.AcGePoint2d(0,0)},{point:new u.AcGePoint2d(a,0)},{point:new u.AcGePoint2d(a,e)},{point:new u.AcGePoint2d(0,e)}]}function vo(a,e,t,i){const n=a>=0?1:-1,s=e>=0?1:-1,r=Math.abs(a),o=Math.abs(e),c=Math.min(ht(t),r/2),l=Math.min(ht(i),o/2);if(u.AcGeTol.isNonPositive(c)&&u.AcGeTol.isNonPositive(l))return $n(a,e);const h=new u.AcGePoint2d(n*c,0),d=new u.AcGePoint2d(0,s*l),g=new u.AcGePoint2d(a-n*c,0),m=new u.AcGePoint2d(a,s*l),y=new u.AcGePoint2d(a,e-s*l),w=new u.AcGePoint2d(a-n*c,e),C=new u.AcGePoint2d(n*c,e),b=new u.AcGePoint2d(0,e-s*l);return[{point:h},{point:g},{point:m},{point:y},{point:w},{point:C},{point:b},{point:d}]}function wh(a,e,t){const i=Math.abs(a),n=Math.abs(e),s=Math.min(ht(t),i/2,n/2);if(u.AcGeTol.isNonPositive(s))return $n(a,e);const r=vo(a,e,s,s),c=(a*e>=0?1:-1)*ph;return r.map((l,h)=>({point:l.point,bulge:h%2===1?c:void 0}))}function bh(a,e,t){return u.AcGeTol.isPositive(t.filletRadius)?wh(a,e,t.filletRadius):u.AcGeTol.isPositive(t.chamferDist1)||u.AcGeTol.isPositive(t.chamferDist2)?vo(a,e,t.chamferDist1,t.chamferDist2):$n(a,e)}function Kn(a,e,t,i){let n=0,s=0;if(t.mode==="corner"){const c=fh(e,t.secondPoint,i.rotation);n=c.x,s=c.y}else n=t.length,s=t.width;if(u.AcGeTol.equalToZero(n)||u.AcGeTol.equalToZero(s))return!1;a.reset(!1);const r=bh(n,s,i),o=ht(i.width);return r.forEach((c,l)=>{const h=yh(e,c.point,i.rotation);u.AcGeTol.isPositive(o)?a.addVertexAt(l,h,c.bulge,o,o):a.addVertexAt(l,h,c.bulge)}),a.elevation=i.elevation,a.closed=!0,!0}class So extends ${constructor(e,t,i){super(e),this._rect=new u.AcDbPolyline,this._firstPoint=new u.AcGePoint2d(t),this._settingsProvider=i}get entity(){return this._rect}update(e){Kn(this._rect,this._firstPoint,{mode:"corner",secondPoint:e},this._settingsProvider())}}class ut extends ${constructor(e,t,i,n){super(e),this._rect=new u.AcDbPolyline,Kn(this._rect,t,i,n)}get entity(){return this._rect}update(e){}}function Un(a){return{chamferDist1:a.chamferDist1,chamferDist2:a.chamferDist2,filletRadius:a.filletRadius,width:a.width,elevation:a.elevation,thickness:a.thickness,rotation:a.rotation}}function De(a){return Number.isFinite(a??NaN)&&u.AcGeTol.isPositive(a??0)}const Ht=class Ht extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=Un(Ht._settings),i=await this.promptFirstCorner(t);if(!i)return;const n=await this.promptSecondInput(e,i,t);if(!n)return;const s=new u.AcDbPolyline;if(!Kn(s,i,n,t)){Gn("invalidRect");return}u.AcGeTol.isPositive(t.thickness)&&Gn("thicknessNotSupported"),e.doc.database.tables.blockTable.modelSpace.appendEntity(s),Ht._settings=Un(t)}async promptFirstCorner(e){for(;;){const t=new D(p.t("jig.rect.firstPointWithOptions"));Ke(t,"chamfer"),Ke(t,"elevation"),Ke(t,"fillet"),Ke(t,"thickness"),Ke(t,"width");const i=await S.instance.editor.getPoint(t);if(i.status===v.OK)return i.value;if(i.status!==v.Keyword)return;const n=i.stringResult??"";if(n==="Chamfer"){if(!await this.promptChamfer(e))return}else if(n==="Elevation"){if(!await this.promptElevation(e))return}else if(n==="Fillet"){if(!await this.promptFillet(e))return}else if(n==="Thickness"){if(!await this.promptThickness(e))return}else if(n==="Width"&&!await this.promptWidth(e))return}}async promptSecondInput(e,t,i){let n;class s{constructor(c){this.cmd=c}buildPrompt(){const c=new D(p.t("jig.rect.otherCornerWithOptions"));return Ke(c,"area"),Ke(c,"dimensions"),Ke(c,"rotation"),c.useDashedLine=!1,c.useBasePoint=!0,c.basePoint=new u.AcGePoint3d(t),c.jig=new So(e.view,t,()=>i),c}async handleResult(c){if(c.status===v.OK)return n={mode:"corner",secondPoint:c.value},"finish";if(c.status!==v.Keyword)return"finish";const l=c.stringResult??"";if(l==="Rotation")return await this.cmd.promptRotation(e,t,i)?"continue":"finish";if(l==="Dimensions"){const h=await this.cmd.promptDimensions(e,t,i);return h&&(n=h),"finish"}if(l==="Area"){const h=await this.cmd.promptArea(e,t,i);return h&&(n=h),"finish"}return"continue"}}const r=new Te;return r.setState(new s(this)),await r.run(o=>S.instance.editor.getPoint(o)),n}async promptPositiveDouble(e,t){for(;;){const i=new X(e);i.allowNegative=!1,i.allowZero=!1,t&&(i.jig=t);const n=await S.instance.editor.getDouble(i);if(n.status!==v.OK)return;if(De(n.value))return n.value;Gn("invalidPositive")}}async promptChamfer(e){const t=await this.promptPositiveDouble(p.t("jig.rect.chamferFirst"));if(!De(t))return!1;const i=await this.promptPositiveDouble(p.t("jig.rect.chamferSecond"));return De(i)?(e.chamferDist1=t,e.chamferDist2=i,e.filletRadius=0,!0):!1}async promptFillet(e){const t=await this.promptPositiveDouble(p.t("jig.rect.filletRadius"));return De(t)?(e.filletRadius=t,e.chamferDist1=0,e.chamferDist2=0,!0):!1}async promptWidth(e){const t=new X(p.t("jig.rect.segmentWidth"));t.allowNegative=!1,t.allowZero=!0;const i=await S.instance.editor.getDouble(t);return i.status!==v.OK?!1:(e.width=ht(i.value),!0)}async promptElevation(e){const t=new X(p.t("jig.rect.elevationValue"));t.allowNegative=!0,t.allowZero=!0;const i=await S.instance.editor.getDouble(t);return i.status!==v.OK?!1:(e.elevation=i.value??0,!0)}async promptThickness(e){const t=new X(p.t("jig.rect.thicknessValue"));t.allowNegative=!1,t.allowZero=!0;const i=await S.instance.editor.getDouble(t);return i.status!==v.OK?!1:(e.thickness=ht(i.value),!0)}async promptRotation(e,t,i){const n=new xe(p.t("jig.rect.rotationAngle"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t),n.allowNegative=!0,n.allowZero=!0,n.jig=new ut(e.view,t,{mode:"dimensions",length:1,width:1},i);const s=await S.instance.editor.getAngle(n);return s.status!==v.OK?!1:(i.rotation=(s.value??0)*Math.PI/180,!0)}async promptDimensions(e,t,i){const n={mode:"dimensions",length:1,width:1},s=await this.promptPositiveDouble(p.t("jig.rect.dimensionLength"),new ut(e.view,t,n,i));if(!De(s))return;const r=await this.promptPositiveDouble(p.t("jig.rect.dimensionWidth"),new ut(e.view,t,{mode:"dimensions",length:s,width:1},i));if(De(r))return{mode:"dimensions",length:s,width:r}}async promptArea(e,t,i){const n=await this.promptPositiveDouble(p.t("jig.rect.areaValue"),new ut(e.view,t,{mode:"dimensions",length:1,width:1},i));if(!De(n))return;const s=new X(p.t("jig.rect.areaLengthOrWidth"));mh(s,"rectWidth"),s.allowNegative=!1,s.allowZero=!1,s.jig=new ut(e.view,t,{mode:"dimensions",length:1,width:1},i);const r=await S.instance.editor.getDouble(s);if(r.status===v.Keyword){if(r.stringResult!=="Width")return;const c=await this.promptPositiveDouble(p.t("jig.rect.areaSpecifyWidth"),new ut(e.view,t,{mode:"dimensions",length:1,width:1},i));return De(c)?{mode:"dimensions",length:(n??0)/(c??1),width:c}:void 0}if(r.status!==v.OK||!De(r.value))return;const o=r.value;return{mode:"dimensions",length:o,width:(n??0)/o}}};Ht._settings=Un(gh);let Ui=Ht;class Ao extends ${constructor(e,t,i,n){super(e),this._points=t,this._settings=i,this._closed=n,this._spline=this.createSpline(t)}get entity(){return this._spline}update(e){const t=new u.AcGePoint2d(e),i=this._points[this._points.length-1],s=!i||!Sh(i,t)?[...this._points,t]:[...this._points];try{this.rebuildSpline(s)}catch{this.rebuildSpline(this._points)}}createSpline(e){return Wn(e,this._settings,this._closed)}rebuildSpline(e){if(e.length<2){const r=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],o=1,c=jt(r.length,o);this._spline.rebuild(r,c,void 0,o);return}const t=e.map(r=>new u.AcGePoint3d(r.x,r.y,0)),i=_o(t.length,this._settings),n=this._closed&&t.length>=3;if(this._settings.method==="fit"){this._spline.rebuild(t,Po(this._settings.knotsType),i,n);return}const s=jt(t.length,i);this._spline.rebuild(t,s,void 0,i,!1),n&&(this._spline.closed=!0)}}class Co extends N{constructor(){super(),this.mode=j.Write}async execute(e){const t=[],i={method:"fit",knotsType:"chord",degree:3};let n=!1;const s=x=>{t.push(new u.AcGePoint2d(x))},r=()=>{t.length<=1||t.pop()},o=()=>t[t.length-1],c=()=>t.length>=3,l=()=>new Ao(e.view,t,i,n),h=()=>new xh(e.view,t,i,n),d=async()=>{const x=new Y(p.t("jig.spline.methodPrompt"));x.keywords.add(p.t("jig.spline.keywords.fit.display"),p.t("jig.spline.keywords.fit.global"),p.t("jig.spline.keywords.fit.local")),x.keywords.add(p.t("jig.spline.keywords.cv.display"),p.t("jig.spline.keywords.cv.global"),p.t("jig.spline.keywords.cv.local"));const A=await S.instance.editor.getKeywords(x);return A.status!==v.OK?!1:(A.stringResult==="Fit"?i.method="fit":A.stringResult==="CV"&&(i.method="cv"),!0)},g=async()=>{const x=new Y(p.t("jig.spline.knotsPrompt"));x.jig=h(),x.keywords.add(p.t("jig.spline.keywords.chord.display"),p.t("jig.spline.keywords.chord.global"),p.t("jig.spline.keywords.chord.local")),x.keywords.add(p.t("jig.spline.keywords.sqrtChord.display"),p.t("jig.spline.keywords.sqrtChord.global"),p.t("jig.spline.keywords.sqrtChord.local")),x.keywords.add(p.t("jig.spline.keywords.uniform.display"),p.t("jig.spline.keywords.uniform.global"),p.t("jig.spline.keywords.uniform.local"));const A=await S.instance.editor.getKeywords(x);return A.status!==v.OK?!1:(A.stringResult==="Chord"?i.knotsType="chord":A.stringResult==="SqrtChord"?i.knotsType="sqrtChord":A.stringResult==="Uniform"&&(i.knotsType="uniform"),!0)},m=async()=>{const x=new on(p.t("jig.spline.degreePrompt"),1,10);x.jig=h();const A=await S.instance.editor.getInteger(x);if(A.status!==v.OK)return!1;const _=Math.floor(A.value??i.degree);return i.degree=Math.max(1,_),!0},y=x=>{x.useDashedLine=!0,x.useBasePoint=!0;const A=o();A&&(x.basePoint=new u.AcGePoint3d(A)),x.jig=l()};class w{constructor(A){this.machine=A}buildPrompt(){const A=new D(p.t("jig.spline.nextPointWithFitOptions"));return A.keywords.add(p.t("jig.spline.keywords.method.display"),p.t("jig.spline.keywords.method.global"),p.t("jig.spline.keywords.method.local")),A.keywords.add(p.t("jig.spline.keywords.knots.display"),p.t("jig.spline.keywords.knots.global"),p.t("jig.spline.keywords.knots.local")),A.keywords.add(p.t("jig.spline.keywords.undo.display"),p.t("jig.spline.keywords.undo.global"),p.t("jig.spline.keywords.undo.local")),A.keywords.add(p.t("jig.spline.keywords.close.display"),p.t("jig.spline.keywords.close.global"),p.t("jig.spline.keywords.close.local")),y(A),A}async handleResult(A){if(A.status===v.OK)return s(A.value),"continue";if(A.status!==v.Keyword)return"finish";const _=A.stringResult??"";return _==="Method"?await d()?(i.method==="cv"&&this.machine.setState(new C(this.machine)),"continue"):"finish":_==="Knots"?await g()?"continue":"finish":_==="Undo"?(r(),"continue"):_==="Close"&&c()?(n=!0,"finish"):"continue"}}class C{constructor(A){this.machine=A}buildPrompt(){const A=new D(p.t("jig.spline.nextPointWithCvOptions"));return A.keywords.add(p.t("jig.spline.keywords.method.display"),p.t("jig.spline.keywords.method.global"),p.t("jig.spline.keywords.method.local")),A.keywords.add(p.t("jig.spline.keywords.degree.display"),p.t("jig.spline.keywords.degree.global"),p.t("jig.spline.keywords.degree.local")),A.keywords.add(p.t("jig.spline.keywords.undo.display"),p.t("jig.spline.keywords.undo.global"),p.t("jig.spline.keywords.undo.local")),A.keywords.add(p.t("jig.spline.keywords.close.display"),p.t("jig.spline.keywords.close.global"),p.t("jig.spline.keywords.close.local")),y(A),A}async handleResult(A){if(A.status===v.OK)return s(A.value),"continue";if(A.status!==v.Keyword)return"finish";const _=A.stringResult??"";return _==="Method"?await d()?(i.method==="fit"&&this.machine.setState(new w(this.machine)),"continue"):"finish":_==="Degree"?await m()?"continue":"finish":_==="Undo"?(r(),"continue"):_==="Close"&&c()?(n=!0,"finish"):"continue"}}for(;t.length===0;){const x=new D(p.t("jig.spline.firstPointWithOptions"));x.keywords.add(p.t("jig.spline.keywords.method.display"),p.t("jig.spline.keywords.method.global"),p.t("jig.spline.keywords.method.local"));const A=await S.instance.editor.getPoint(x);if(A.status===v.OK){s(A.value);break}if(A.status===v.Keyword&&A.stringResult==="Method"){if(!await d())return;continue}return}const b=new Te;if(b.setState(i.method==="fit"?new w(b):new C(b)),await b.run(x=>S.instance.editor.getPoint(x)),t.length>=2){const x=e.doc.database,A=Wn(t,i,n);x.tables.blockTable.modelSpace.appendEntity(A)}}}class xh extends ${constructor(e,t,i,n){super(e),this._spline=Wn(t,i,n)}get entity(){return this._spline}update(e){}}function Wn(a,e,t){if(a.length<2){const l=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],h=1,d=jt(l.length,h);return new u.AcDbSpline(l,d,void 0,h)}const i=a.map(l=>new u.AcGePoint3d(l.x,l.y,0)),n=e.method==="fit"?vh(i):i;if(n.length<2){const l=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],h=1,d=jt(l.length,h);return new u.AcDbSpline(l,d,void 0,h)}const s=_o(n.length,e),r=t&&n.length>=3;if(e.method==="fit")return new u.AcDbSpline(n,Po(e.knotsType),s,r);const o=jt(n.length,s),c=new u.AcDbSpline(n,o,void 0,s,!1);return r&&(c.closed=!0),c}function _o(a,e){const t=Math.max(1,a-1);return e.method==="fit"?Math.min(3,t):Math.min(Math.max(1,e.degree),t)}function vh(a){if(a.length<=1)return a;const e=[new u.AcGePoint3d(a[0])];for(let t=1;t<a.length;t++){const i=e[e.length-1],n=a[t];Ah(i,n)||e.push(new u.AcGePoint3d(n))}return e}function Sh(a,e){return u.DEFAULT_TOL.equalPoint2d(a,e)}function Ah(a,e){return u.DEFAULT_TOL.equalPoint3d(a,e)}function Po(a){switch(a){case"chord":return"Chord";case"sqrtChord":return"SqrtChord";case"uniform":default:return"Uniform"}}function jt(a,e){const t=[],i=a+e+1;for(let n=0;n<i;n++)n<e+1?t.push(0):n>=i-e-1?t.push(1):t.push((n-e)/(a-e));return t}const dt=1e6;class Lo extends N{constructor(){super(),this.mode=j.Write}async execute(e){let t="point";for(;;){const i=new D(p.t("jig.xline.firstPointOrOptions"));i.keywords.add(p.t("jig.xline.keywords.hor.display"),p.t("jig.xline.keywords.hor.global"),p.t("jig.xline.keywords.hor.local")),i.keywords.add(p.t("jig.xline.keywords.ver.display"),p.t("jig.xline.keywords.ver.global"),p.t("jig.xline.keywords.ver.local")),i.keywords.add(p.t("jig.xline.keywords.ang.display"),p.t("jig.xline.keywords.ang.global"),p.t("jig.xline.keywords.ang.local"));const n=await S.instance.editor.getPoint(i);if(n.status===v.Keyword)n.stringResult==="Hor"?t="hor":n.stringResult==="Ver"?t="ver":n.stringResult==="Ang"&&(t="ang");else if(n.status===v.OK&&n.value){t="point";const h=new D(p.t("jig.xline.secondPoint"));h.useBasePoint=!0,h.useDashedLine=!0,h.basePoint=new u.AcGePoint3d(n.value);const d=await S.instance.editor.getPoint(h);if(d.status!==v.OK||!d.value)return;const g={x:d.value.x-n.value.x,y:d.value.y-n.value.y,z:d.value.z-n.value.z};this.appendFiniteXLine(e,n.value,g)||S.instance.editor.showMessage(p.t("jig.xline.invalidDirection"),"warning");continue}else return;if(t==="hor"){const h=new D(p.t("jig.xline.throughPoint")),d=await S.instance.editor.getPoint(h);if(d.status!==v.OK||!d.value)return;this.appendFiniteXLine(e,d.value,{x:1,y:0,z:0});continue}if(t==="ver"){const h=new D(p.t("jig.xline.throughPoint")),d=await S.instance.editor.getPoint(h);if(d.status!==v.OK||!d.value)return;this.appendFiniteXLine(e,d.value,{x:0,y:1,z:0});continue}const s=new X(p.t("jig.xline.angle")),r=await S.instance.editor.getDouble(s);if(r.status!==v.OK||r.value==null)return;const o=new D(p.t("jig.xline.throughPoint")),c=await S.instance.editor.getPoint(o);if(c.status!==v.OK||!c.value)return;const l=r.value*Math.PI/180;this.appendFiniteXLine(e,c.value,{x:Math.cos(l),y:Math.sin(l),z:0})}}appendFiniteXLine(e,t,i){const n=this.normalizeDirection(i);if(!n)return!1;const s=new u.AcGePoint3d(t.x-n.x*dt,t.y-n.y*dt,t.z-n.z*dt),r=new u.AcGePoint3d(t.x+n.x*dt,t.y+n.y*dt,t.z+n.z*dt);return e.doc.database.tables.blockTable.modelSpace.appendEntity(new u.AcDbLine(s,r)),!0}normalizeDirection(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);if(u.AcGeTol.isPositive(t))return{x:e.x/t,y:e.y/t,z:e.z/t}}}const Hn=[];function pt(a){Hn.push(a)}function Yn(a){Hn.forEach(e=>e()),Hn.length=0,a.htmlTransientManager.clear("measurement")}class Xn extends N{constructor(){super(),this.mode=j.Read}async execute(e){Yn(e.view)}}const Ch=Object.freeze(Object.defineProperty({__proto__:null,AcApClearMeasurementsCmd:Xn,clearAllMeasurements:Yn,registerMeasurementCleanup:pt},Symbol.toStringTag,{value:"Module"}));function To(a,e,t){const i=e.x-a.x,n=e.y-a.y,s=t.x-a.x,r=t.y-a.y,o=i*s+n*r,c=i*r-n*s;return Math.atan2(Math.abs(c),o)*180/Math.PI}const _h=a=>(a%(2*Math.PI)+2*Math.PI)%(2*Math.PI);function qn(a,e,t,i,n){const s=e.canvas.getBoundingClientRect(),r=window.devicePixelRatio||1,o=Math.round(s.width),c=Math.round(s.height),l=e.canvasToContainer({x:0,y:0});a.style.left=`${l.x}px`,a.style.top=`${l.y}px`,a.style.width=`${o}px`,a.style.height=`${c}px`,(a.width!==o*r||a.height!==c*r)&&(a.width=o*r,a.height=c*r);const h=a.getContext("2d");if(!h)return;h.clearRect(0,0,a.width,a.height),h.save(),h.scale(r,r);const d=e.worldToScreen(t),g=e.worldToScreen(i);h.beginPath(),h.moveTo(d.x,d.y),h.lineTo(g.x,g.y),h.strokeStyle=de(n),h.lineWidth=2,h.setLineDash([8,5]),h.stroke(),h.setLineDash([]),h.restore()}function Io(a,e,t,i,n,s){const r=e.canvas.getBoundingClientRect(),o=window.devicePixelRatio||1,c=Math.round(r.width),l=Math.round(r.height),h=e.canvasToContainer({x:0,y:0});a.style.left=`${h.x}px`,a.style.top=`${h.y}px`,a.style.width=`${c}px`,a.style.height=`${l}px`,(a.width!==c*o||a.height!==l*o)&&(a.width=c*o,a.height=l*o);const d=a.getContext("2d");if(!d)return;d.clearRect(0,0,a.width,a.height),d.save(),d.scale(o,o);const g=e.worldToScreen(t),m=e.worldToScreen(i),y=e.worldToScreen(n),w=Math.hypot(m.x-g.x,m.y-g.y),C=Math.hypot(y.x-g.x,y.y-g.y),b=Math.max(Math.min(w,C)*.3,15),x=Math.atan2(m.y-g.y,m.x-g.x),A=Math.atan2(y.y-g.y,y.x-g.x),_=_h(A-x)>Math.PI;d.beginPath(),d.arc(g.x,g.y,b,x,A,_),d.strokeStyle=de(s),d.lineWidth=2,d.stroke(),d.restore()}class Ph extends ${constructor(e,t,i){super(e),this._line=new u.AcDbLine(t,t),this._line.color=i,this._line.lineWeight=u.AcGiLineWeight.LineWeight070}get entity(){return this._line}update(e){this._line.endPoint=e}}class Lh extends ${constructor(e,t,i,n,s,r){super(e),this._vertex=i,this._arm1=n,this._view=e,this._canvas=s,this._color=r,this._db=t,this._line=new u.AcDbLine(i,i),this._line.color=r,this._line.lineWeight=u.AcGiLineWeight.LineWeight070,this._badge=Dt(r)}get entity(){return this._line}update(e){this._line.endPoint=e,qn(this._canvas,this._view,this._vertex,this._arm1,this._color);const t=To(this._vertex,this._arm1,e);this._badge.textContent=this._db.formatter.formatAngle(t*Math.PI/180,{showUnits:!0,showApproximate:!0,applyAngbaseAngdir:!1}),this._badge.style.display="block";const i=this._view.canvas.getBoundingClientRect(),n=this._view.worldToScreen(this._vertex);this._badge.style.left=`${n.x+i.left}px`,this._badge.style.top=`${n.y+i.top-30}px`}end(){super.end(),this._badge.remove()}}class Eo extends N{constructor(){super(),this.mode=j.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=kt(i);await e.view.withMode(se.SELECTION,()=>t.withCursor(be.Crosshair,async()=>{const s=new D(p.t("jig.measureAngle.vertex")),r=await t.getPoint(s);if(r.status!==v.OK)return;const o=r.value,c=new D(p.t("jig.measureAngle.arm1"));c.useBasePoint=!0,c.jig=new Ph(e.view,o,n);const l=await t.getPoint(c);if(l.status!==v.OK)return;const h=l.value,d=qe(e.view.container);qn(d,e.view,o,h,n);const g=()=>qn(d,e.view,o,h,n);e.view.events.viewChanged.addEventListener(g);const m=new D(p.t("jig.measureAngle.arm2"));m.jig=new Lh(e.view,i,o,h,d,n);let y;try{const Qe=await t.getPoint(m);if(Qe.status!==v.OK){e.view.events.viewChanged.removeEventListener(g),d.remove();return}y=Qe.value}catch{e.view.events.viewChanged.removeEventListener(g),d.remove();return}e.view.events.viewChanged.removeEventListener(g),d.remove();const w=To(o,h,y),C=new u.AcDbLine(o,h);C.color=n,C.lineWeight=u.AcGiLineWeight.LineWeight070,e.view.addTransientEntity(C);const b=new u.AcDbLine(o,y);b.color=n,b.lineWeight=u.AcGiLineWeight.LineWeight070,e.view.addTransientEntity(b);const x=qe(e.view.container);Io(x,e.view,o,h,y,n);const A=()=>Io(x,e.view,o,h,y,n);e.view.events.viewChanged.addEventListener(A);const _=e.view.htmlTransientManager,L=`angle-${Date.now()}`;_.add(`${L}-dotV`,Be(n),o,"measurement"),_.add(`${L}-dot1`,Be(n),h,"measurement"),_.add(`${L}-dot2`,Be(n),y,"measurement");const T=h.x-o.x,O=h.y-o.y,k=y.x-o.x,E=y.y-o.y,M=Math.hypot(T,O),F=Math.hypot(k,E),z=M>0?T/M:1,U=M>0?O/M:0,V=F>0?k/F:1,K=F>0?E/F:0;let G=z+V,W=U+K;const ee=Math.hypot(G,W);ee>0?(G/=ee,W/=ee):(G=-U,W=z);const _e=Math.max(Math.min(M,F)*.4,Math.max(M,F)*.15),wt={x:o.x+G*_e,y:o.y+W*_e};_.add(`${L}-badge`,Bt(n,i.formatter.formatAngle(w*Math.PI/180,{showUnits:!0,applyAngbaseAngdir:!1})),wt,"measurement"),pt(()=>{e.view.removeTransientEntity(C.objectId),e.view.removeTransientEntity(b.objectId),x.remove(),e.view.events.viewChanged.removeEventListener(A),_.remove(`${L}-dotV`),_.remove(`${L}-dot1`),_.remove(`${L}-dot2`),_.remove(`${L}-badge`)})}))}}class Th extends ${constructor(e,t,i,n){super(e),this._line=new u.AcDbLine(t,t),this._line.color=i,this._line.lineWeight=u.AcGiLineWeight.LineWeight070,this._onMove=n}get entity(){return this._line}update(e){this._line.endPoint=e,this._onMove(e)}}function Ih(a,e,t,i){const n=e.x-a.x,s=e.y-a.y,r=i.x-t.x,o=i.y-t.y,c=n*o-s*r;if(Math.abs(c)<1e-10)return!1;const l=t.x-a.x,h=t.y-a.y,d=(l*o-h*r)/c,g=(l*s-h*n)/c;return d>0&&d<1&&g>0&&g<1}function ko(a){let e=0;const t=a.length;for(let i=0;i<t;i++){const n=(i+1)%t;e+=a[i].x*a[n].y,e-=a[n].x*a[i].y}return Math.abs(e)/2}function Bo(a){const e=a.reduce((i,n)=>i+n.x,0)/a.length,t=a.reduce((i,n)=>i+n.y,0)/a.length;return{x:e,y:t}}function Do(a,e,t,i){const n=e.canvas.getBoundingClientRect(),s=window.devicePixelRatio||1,r=Math.round(n.width),o=Math.round(n.height),c=e.canvasToContainer({x:0,y:0});a.style.left=`${c.x}px`,a.style.top=`${c.y}px`,a.style.width=`${r}px`,a.style.height=`${o}px`,(a.width!==r*s||a.height!==o*s)&&(a.width=r*s,a.height=o*s);const l=a.getContext("2d");if(!l||t.length<3)return;l.clearRect(0,0,a.width,a.height),l.save(),l.scale(s,s);const h=t.map(d=>e.worldToScreen(d));l.beginPath(),l.moveTo(h[0].x,h[0].y);for(let d=1;d<h.length;d++)l.lineTo(h[d].x,h[d].y);l.closePath(),l.fillStyle=Tn(i,.2),l.fill(),l.strokeStyle=de(i),l.lineWidth=2.5,l.stroke(),l.restore()}class Mo extends N{constructor(){super(),this.mode=j.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=kt(i),s=[],r=qe(e.view.container),o=Dt(n);await e.view.withMode(se.SELECTION,()=>t.withCursor(be.Crosshair,async()=>{const c=x=>{const A=e.view.canvas.getBoundingClientRect(),_=window.devicePixelRatio||1,L=Math.round(A.width),T=Math.round(A.height),O=e.view.canvasToContainer({x:0,y:0});r.style.left=`${O.x}px`,r.style.top=`${O.y}px`,r.style.width=`${L}px`,r.style.height=`${T}px`,(r.width!==L*_||r.height!==T*_)&&(r.width=L*_,r.height=T*_);const k=r.getContext("2d");if(!k||s.length<1)return;k.clearRect(0,0,r.width,r.height),k.save(),k.scale(_,_);const E=s.map(F=>e.view.worldToScreen(F)),M=x?[...E,e.view.worldToScreen(x)]:E;if(M.length>=3){k.beginPath(),k.moveTo(M[0].x,M[0].y);for(let F=1;F<M.length;F++)k.lineTo(M[F].x,M[F].y);k.closePath(),k.fillStyle=Tn(n,.2),k.fill()}if(E.length>=2){k.beginPath(),k.moveTo(E[0].x,E[0].y);for(let F=1;F<E.length;F++)k.lineTo(E[F].x,E[F].y);k.strokeStyle=de(n),k.lineWidth=2.5,k.setLineDash([8,5]),k.stroke(),k.setLineDash([])}k.restore()},l=()=>c();e.view.events.viewChanged.addEventListener(l);const h=await t.getPoint(new D(p.t("jig.measureArea.firstPoint")));if(h.status!==v.OK)return;const d=h.value;s.push(d),c();try{for(;s.length<50;){const x=new D(p.t("jig.measureArea.nextPoint"));x.useBasePoint=!0,x.allowNone=!0;const A=T=>{if(s.length<2)return;const O=[...s,T],k=ko(O);o.textContent=`${i.formatter.formatLength(k,{showUnits:!0,showApproximate:!0})}²`,o.style.display="";const E=Bo(O),M=e.view.canvas.getBoundingClientRect(),F=e.view.worldToScreen(E);o.style.left=`${F.x+M.left}px`,o.style.top=`${F.y+M.top}px`,c(T)};x.jig=new Th(e.view,s[s.length-1],n,A);const _=await t.getPoint(x);if(_.status!==v.OK)break;const L=_.value;if(o.style.display="none",s.length>=3){const T=e.view.worldToScreen(L),O=k=>{const E=e.view.worldToScreen(k),M=T.x-E.x,F=T.y-E.y;return M*M+F*F<=14*14};if(O(s[0])||O(s[s.length-1]))break}if(s.length>=3){const T=s[s.length-1];let O=!1;for(let k=0;k<s.length-2;k++)if(Ih(T,L,s[k],s[k+1])){O=!0;break}if(O)break}s.push(L),c()}}catch{}if(o.remove(),e.view.events.viewChanged.removeEventListener(l),r.remove(),s.length<3)return;const g=ko(s),m=qe(e.view.container);Do(m,e.view,s,n);const y=()=>Do(m,e.view,s,n);e.view.events.viewChanged.addEventListener(y);const w=e.view.htmlTransientManager,C=`area-${Date.now()}`,b=Bo(s);w.add(`${C}-badge`,Bt(n,`${i.formatter.formatLength(g,{showUnits:!0,showApproximate:!0})}²`),b,"measurement"),s.forEach((x,A)=>{w.add(`${C}-dot${A}`,Be(n),x,"measurement")}),pt(()=>{m.remove(),e.view.events.viewChanged.removeEventListener(y),w.remove(`${C}-badge`),s.forEach((x,A)=>{w.remove(`${C}-dot${A}`)})})}))}}function Zn(a,e){const t=Math.atan2(a.y-e.cy,a.x-e.cx);return{x:e.cx+e.r*Math.cos(t),y:e.cy+e.r*Math.sin(t),z:0}}function Oo(a,e,t){const i=Math.atan2(a.y-t.cy,a.x-t.cx),n=Math.atan2(e.y-t.cy,e.x-t.cx),r=(o=>(o%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(n-i);return Math.min(r,2*Math.PI-r)*t.r}function Fo(a,e,t){const i=Math.atan2(a.y-t.cy,a.x-t.cx),n=Math.atan2(e.y-t.cy,e.x-t.cx),r=(c=>(c%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(n-i),o=r<=Math.PI?i+r/2:i-(2*Math.PI-r)/2;return{x:t.cx+t.r*Math.cos(o),y:t.cy+t.r*Math.sin(o),z:0}}function Wi(a,e,t,i,n,s){const r=e.canvas.getBoundingClientRect(),o=window.devicePixelRatio||1,c=Math.round(r.width),l=Math.round(r.height),h=e.canvasToContainer({x:0,y:0});a.style.left=`${h.x}px`,a.style.top=`${h.y}px`,a.style.width=`${c}px`,a.style.height=`${l}px`,(a.width!==c*o||a.height!==l*o)&&(a.width=c*o,a.height=l*o);const d=a.getContext("2d");if(!d)return;d.clearRect(0,0,a.width,a.height),d.save(),d.scale(o,o);const g=e.worldToScreen({x:t.cx,y:t.cy}),m=e.worldToScreen(i),y=e.worldToScreen(n),w=Math.hypot(m.x-g.x,m.y-g.y),C=Math.atan2(m.y-g.y,m.x-g.x),b=Math.atan2(y.y-g.y,y.x-g.x),_=(L=>(L%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(b-C)>Math.PI;d.beginPath(),d.arc(g.x,g.y,w,C,b,_),d.strokeStyle=de(s),d.lineWidth=4,d.stroke(),d.restore()}class Eh extends ${constructor(e,t,i){super(e.view),this._ctx=e,this._onSnap=i;const n={x:0,y:0,z:0};this._dummy=new u.AcDbLine(n,n),this._indicator=In(t)}get entity(){return this._dummy}update(e){const t=this._ctx.view.pick(e),i=this._ctx.doc.database.tables.blockTable.modelSpace;let n=null,s=Number.MAX_VALUE;for(const r of t){const o=i.getIdAt(r.id);let c=null;if(o instanceof u.AcDbCircle?c={cx:o.center.x,cy:o.center.y,r:o.radius}:o instanceof u.AcDbArc&&(c={cx:o.center.x,cy:o.center.y,r:o.radius}),c){const l=Math.hypot(e.x-c.cx,e.y-c.cy),h=Math.abs(l-c.r);h<s&&(s=h,n=c)}}if(n){const r=Zn(e,n),o=this._ctx.view.worldToScreen(e),c=this._ctx.view.worldToScreen(r);if(Math.hypot(o.x-c.x,o.y-c.y)<=20){const h=this._ctx.view.canvas.getBoundingClientRect();this._indicator.style.left=`${c.x+h.left}px`,this._indicator.style.top=`${c.y+h.top}px`,this._indicator.style.display="block",this._onSnap(n,r);return}}this._indicator.style.display="none",this._onSnap(null,null)}end(){super.end(),this._indicator.remove()}}class kh extends ${constructor(e,t,i,n){super(e.view),this._ctx=e,this._geom=t,this._onMove=n;const s={x:0,y:0,z:0};this._dummy=new u.AcDbLine(s,s),this._indicator=In(i),this._indicator.style.display="block"}get entity(){return this._dummy}update(e){const t=Zn(e,this._geom),i=this._ctx.view.canvas.getBoundingClientRect(),n=this._ctx.view.worldToScreen(t);this._indicator.style.left=`${n.x+i.left}px`,this._indicator.style.top=`${n.y+i.top}px`,this._onMove(t)}end(){super.end(),this._indicator.remove()}}class jo extends N{constructor(){super(),this.mode=j.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=kt(i),s=qe(e.view.container);await e.view.withMode(se.SELECTION,()=>t.withCursor(be.Crosshair,async()=>{let r=null,o=null;const c=new Eh(e,n,(F,z)=>{r=F,o=z}),l=new D(p.t("jig.measureArc.startPoint"));l.jig=c;try{if((await t.getPoint(l)).status!==v.OK){s.remove();return}}catch{s.remove();return}if(!r||!o){s.remove();return}const h=r,d=o,g=vr(n),m=Dt(n),y=()=>{const F=e.view.canvas.getBoundingClientRect(),z=e.view.worldToScreen(d);g.style.left=`${z.x+F.left}px`,g.style.top=`${z.y+F.top}px`};y();const w=()=>Wi(s,e.view,h,d,d,n),C=()=>{y(),w()};e.view.events.viewChanged.addEventListener(C);const b=F=>{Wi(s,e.view,h,d,F,n);const z=Oo(d,F,h);m.textContent=i.formatter.formatLength(z,{showUnits:!0,showApproximate:!0}),m.style.display="";const U=Fo(d,F,h),V=e.view.canvas.getBoundingClientRect(),K=e.view.worldToScreen(U);m.style.left=`${K.x+V.left}px`,m.style.top=`${K.y+V.top}px`,y()},x=new D(p.t("jig.measureArc.endPoint"));x.jig=new kh(e,h,n,b);let A;try{const F=await t.getPoint(x);if(F.status!==v.OK){s.remove(),g.remove(),m.remove(),e.view.events.viewChanged.removeEventListener(C);return}A=F.value}catch{s.remove(),g.remove(),m.remove(),e.view.events.viewChanged.removeEventListener(C);return}m.remove(),g.remove(),e.view.events.viewChanged.removeEventListener(C),s.remove();const _=Zn(A,h),L=Oo(d,_,h),T=Fo(d,_,h),O=qe(e.view.container);Wi(O,e.view,h,d,_,n);const k=()=>Wi(O,e.view,h,d,_,n);e.view.events.viewChanged.addEventListener(k);const E=e.view.htmlTransientManager,M=`arc-${Date.now()}`;E.add(`${M}-dot1`,Be(n),d,"measurement"),E.add(`${M}-dot2`,Be(n),_,"measurement"),E.add(`${M}-badge`,Bt(n,i.formatter.formatLength(L,{showUnits:!0,showApproximate:!0})),T,"measurement"),pt(()=>{O.remove(),e.view.events.viewChanged.removeEventListener(k),E.remove(`${M}-dot1`),E.remove(`${M}-dot2`),E.remove(`${M}-badge`)})}))}}function No(a,e){const t=e.x-a.x,i=e.y-a.y;return Math.sqrt(t*t+i*i)}class Ro extends ${constructor(e,t,i,n){super(e),this._p1=i,this._view=e,this._db=t,this._line=new u.AcDbLine(i,i),this._line.color=n,this._line.lineWeight=u.AcGiLineWeight.LineWeight070,this._badge=Dt(n)}get entity(){return this._line}update(e){this._line.endPoint=e;const t=No(this._p1,e);if(t<1e-4){this._badge.style.display="none";return}this._badge.textContent=this._db.formatter.formatLength(t,{showUnits:!0,showApproximate:!0}),this._badge.style.display="block";const i={x:(this._p1.x+e.x)/2,y:(this._p1.y+e.y)/2},n=this._view.canvas.getBoundingClientRect(),s=this._view.worldToScreen(i);this._badge.style.left=`${s.x+n.left}px`,this._badge.style.top=`${s.y+n.top}px`}end(){super.end(),this._badge.remove()}}class zo extends N{constructor(){super(),this.mode=j.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=kt(i);await e.view.withMode(se.SELECTION,()=>t.withCursor(be.Crosshair,async()=>{const s=new D(p.t("jig.measureDistance.firstPoint")),r=await t.getPoint(s);if(r.status!==v.OK)return;const o=r.value,c=new D(p.t("jig.measureDistance.secondPoint"));c.useBasePoint=!0,c.jig=new Ro(e.view,i,o,n);const l=await t.getPoint(c);if(l.status!==v.OK)return;const h=l.value,d=No(o,h),g=new u.AcDbLine(o,h);g.color=n,g.lineWeight=u.AcGiLineWeight.LineWeight070,e.view.addTransientEntity(g);const m=e.view.htmlTransientManager,y=`dist-${Date.now()}`,w={x:(o.x+h.x)/2,y:(o.y+h.y)/2};m.add(`${y}-dot1`,Be(n),o,"measurement"),m.add(`${y}-dot2`,Be(n),h,"measurement"),m.add(`${y}-badge`,Bt(n,i.formatter.formatLength(d,{showUnits:!0,showApproximate:!0})),w,"measurement"),pt(()=>{e.view.removeTransientEntity(g.objectId),m.remove(`${y}-dot1`),m.remove(`${y}-dot2`),m.remove(`${y}-badge`)})}))}}class Jn extends ${constructor(e,t,i,n=1,s=!1){super(e),this._view=e,this._basePoint=new u.AcGePoint3d(i),this._copyCount=Math.max(0,n),this._fitMode=s,this._previewItems=[];for(let r=1;r<=this._copyCount;r++)t.map(o=>o.clone()).filter(o=>!!o).forEach(o=>{this._previewItems.push({entity:o,factor:r,lastDisplacement:new u.AcGePoint3d(0,0,0)})})}get entity(){var e;return((e=this._previewItems[0])==null?void 0:e.entity)??null}update(e){if(this._previewItems.length===0)return;const t=new u.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z);this._previewItems.forEach(i=>{const n=this.scaleDisplacement(t,i.factor),s=new u.AcGePoint3d(n.x-i.lastDisplacement.x,n.y-i.lastDisplacement.y,n.z-i.lastDisplacement.z);s.x===0&&s.y===0&&s.z===0||(i.entity.transformBy(new u.AcGeMatrix3d().makeTranslation(s.x,s.y,s.z)),i.lastDisplacement=n)})}render(){this._previewItems.length!==0&&this._view.addTransientEntity(this._previewItems.map(e=>e.entity))}end(){this._previewItems.forEach(e=>this._view.removeTransientEntity(e.entity.objectId))}scaleDisplacement(e,t){const i=this._fitMode&&this._copyCount>0?t/this._copyCount:t;return new u.AcGePoint3d(e.x*i,e.y*i,e.z*i)}}const Yt=class Yt extends N{constructor(){super(),this.mode=j.Review}addKeyword(e,t){e.keywords.add(p.t(`jig.copy.keywords.${t}.display`),p.t(`jig.copy.keywords.${t}.global`),p.t(`jig.copy.keywords.${t}.local`))}computeDisplacement(e,t){return new u.AcGePoint3d(t.x-e.x,t.y-e.y,t.z-e.z)}scaleDisplacement(e,t,i,n){const s=n&&i>0?t/i:t;return new u.AcGePoint3d(e.x*s,e.y*s,e.z*s)}buildCopies(e,t,i=1,n=!1){const s=[];for(let r=1;r<=i;r++){const o=e.map(h=>h.clone()).filter(h=>!!h),c=this.scaleDisplacement(t,r,i,n),l=new u.AcGeMatrix3d().makeTranslation(c.x,c.y,c.z);o.forEach(h=>h.transformBy(l)),s.push(...o)}return s}async promptCopyMode(e){const t=new Y(`${p.t("jig.copy.modePrompt")} <${e}>`);t.allowNone=!0,this.addKeyword(t,"single"),this.addKeyword(t,"multiple");const i=await S.instance.editor.getKeywords(t);if(i.status===v.None)return e;if(i.status!==v.OK)return;const n=i.stringResult??"";return n==="Single"||n==="Multiple"?n:e}async promptArrayPlacement(e,t,i){const n=new on(p.t("jig.copy.arrayItemCount"),2);n.lowerLimit=2,n.allowNegative=!1,n.allowZero=!1;const s=await S.instance.editor.getInteger(n);if(s.status!==v.OK)return;const r=s.value??2,o=Math.max(1,r-1);for(;;){const c=new D(p.t("jig.copy.arraySecondPointOrFit"));this.addKeyword(c,"fit"),c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=i,c.jig=new Jn(e.view,t,i,o);const l=await S.instance.editor.getPoint(c);if(l.status===v.OK)return{copyCount:o,endPoint:new u.AcGePoint3d(l.value),fitMode:!1};if(l.status===v.Keyword&&l.stringResult==="Fit"){const h=new D(p.t("jig.copy.arrayFitSecondPoint"));h.useBasePoint=!0,h.useDashedLine=!0,h.basePoint=i,h.jig=new Jn(e.view,t,i,o,!0);const d=await S.instance.editor.getPoint(h);if(d.status===v.OK)return{copyCount:o,endPoint:new u.AcGePoint3d(d.value),fitMode:!0}}return}}async executeCopyLoop(e,t,i,n,s=!1){const r=e.doc.database.tables.blockTable;for(;;){const o=new D(p.t(s?"jig.copy.displacementOrArray":"jig.copy.secondPointOrArray"));this.addKeyword(o,"array"),o.useBasePoint=!0,o.useDashedLine=!0,o.basePoint=i,o.allowNone=n==="Multiple",o.jig=new Jn(e.view,t,i);const c=await S.instance.editor.getPoint(o);if(c.status===v.OK){const l=this.buildCopies(t,this.computeDisplacement(i,c.value));if(l.length>0&&r.modelSpace.appendEntity(l),n==="Single")return;continue}if(c.status===v.Keyword&&c.stringResult==="Array"){const l=await this.promptArrayPlacement(e,t,i);if(!l)continue;const h=this.buildCopies(t,this.computeDisplacement(i,l.endPoint),l.copyCount,l.fitMode);if(h.length>0&&r.modelSpace.appendEntity(h),n==="Single")return;continue}return}}async execute(e){var d;const t=e.view.selectionSet,i=new we(e.doc.database),n=e.doc.database.tables.blockTable,s=t.count>0?t.ids:((d=(await S.instance.editor.getSelection(new je(p.sysCmdPrompt("copy")))).value)==null?void 0:d.ids)??[];if(s.length===0)return;const r=e.doc.openMode==j.Review?i.filterAnnotationEntities(s):s;if(r.length===0){t.clear();return}const o=r.map(g=>n.getEntityById(g)).filter(g=>!!g);if(o.length===0){t.clear();return}let c=Yt._defaultMode,l,h=!1;for(;!l;){const g=new D(p.t("jig.copy.basePointOrOptions"));g.allowNone=!0,this.addKeyword(g,"displacement"),this.addKeyword(g,"mode"),c!=="Multiple"&&this.addKeyword(g,"multiple");const m=await S.instance.editor.getPoint(g);if(m.status===v.OK){l=new u.AcGePoint3d(m.value);break}if(m.status===v.None){l=new u.AcGePoint3d(0,0,0),h=!0;break}if(m.status!==v.Keyword){t.clear();return}const y=m.stringResult??"";if(y==="Displacement"){l=new u.AcGePoint3d(0,0,0),h=!0;break}if(y==="Multiple"){c="Multiple";continue}if(y!=="Mode"){t.clear();return}const w=await this.promptCopyMode(c);if(!w){t.clear();return}c=w,Yt._defaultMode=w}await this.executeCopyLoop(e,o,l,c,h),t.clear()}};Yt._defaultMode="Multiple";let Hi=Yt;class Vo extends N{constructor(){super(),this.mode=j.Review}async execute(e){const t=e.view.selectionSet,i=new we(e.doc.database);if(t.count>0){const n=e.doc.openMode==j.Review?i.filterAnnotationEntities(t.ids):t.ids;e.doc.database.tables.blockTable.removeEntity(n),t.clear()}else{const n=p.sysCmdPrompt("erase"),s=new je(n),r=await S.instance.editor.getSelection(s);if(r.status===v.OK&&r.value&&r.value.count>0){let o=r.value.ids;e.doc.openMode==j.Review&&(o=i.filterAnnotationEntities(o)),e.doc.database.tables.blockTable.removeEntity(o),t.clear()}}}}class Go extends ${constructor(e,t,i){super(e),this._view=e,this._basePoint=new u.AcGePoint3d(i),this._lastDisplacement=new u.AcGePoint3d(0,0,0),this._previewEntities=t.map(n=>this.cloneEntity(n)).filter(n=>!!n)}get entity(){return this._previewEntities[0]??null}update(e){if(this._previewEntities.length===0)return;const t=new u.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z),i=new u.AcGePoint3d(t.x-this._lastDisplacement.x,t.y-this._lastDisplacement.y,t.z-this._lastDisplacement.z);if(!(i.x!==0||i.y!==0||i.z!==0))return;const s=new u.AcGeMatrix3d().makeTranslation(i.x,i.y,i.z);this._previewEntities.forEach(r=>r.transformBy(s)),this._lastDisplacement=t}render(){this._previewEntities.length!==0&&this._view.addTransientEntity(this._previewEntities)}end(){this._previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}cloneEntity(e){return e.clone()}}class $o extends N{constructor(){super(),this.mode=j.Review}async execute(e){var C;const t=e.view.selectionSet,i=new we(e.doc.database),n=e.doc.database.tables.blockTable,s=t.count>0?t.ids:((C=(await S.instance.editor.getSelection(new je(p.sysCmdPrompt("move")))).value)==null?void 0:C.ids)??[];if(s.length===0)return;const r=e.doc.openMode==j.Review?i.filterAnnotationEntities(s):s;if(r.length===0){t.clear();return}const o=r.map(b=>n.getEntityById(b)).filter(b=>!!b);if(o.length===0){t.clear();return}let c,l;const h=b=>{b.keywords.add(p.t("jig.move.keywords.displacement.display"),p.t("jig.move.keywords.displacement.global"),p.t("jig.move.keywords.displacement.local"))};class d{constructor(x){this.machine=x}buildPrompt(){const x=new D(p.t("jig.move.basePointOrDisplacement"));return h(x),x}async handleResult(x){return x.status===v.OK?(c=new u.AcGePoint3d(x.value),this.machine.setState(new g(this.machine)),"continue"):x.status===v.Keyword&&x.stringResult==="Displacement"?(this.machine.setState(new m),"continue"):"finish"}}class g{constructor(x){this.machine=x}buildPrompt(){const x=new D(p.t("jig.move.secondPointOrDisplacement"));return h(x),c&&(x.useBasePoint=!0,x.useDashedLine=!0,x.basePoint=c,x.jig=new Go(e.view,o,c)),x}async handleResult(x){if(x.status===v.OK&&c){const A=new u.AcGePoint3d(x.value);return l=new u.AcGePoint3d(A.x-c.x,A.y-c.y,A.z-c.z),"finish"}return x.status===v.Keyword&&x.stringResult==="Displacement"?(this.machine.setState(new m),"continue"):"finish"}}class m{buildPrompt(){const x=new D(p.t("jig.move.displacement"));return x.useBasePoint=!0,x.useDashedLine=!0,x.basePoint=new u.AcGePoint3d(0,0,0),x.jig=new Go(e.view,o,x.basePoint),x}async handleResult(x){return x.status===v.OK&&(l=new u.AcGePoint3d(x.value)),"finish"}}const y=new Te;if(y.setState(new d(y)),await y.run(b=>S.instance.editor.getPoint(b)),!l){t.clear();return}const w=new u.AcGeMatrix3d().makeTranslation(l.x,l.y,l.z);r.forEach(b=>{const x=n.getEntityById(b);x&&(x.transformBy(w),x.triggerModifiedEvent())}),t.clear()}}function Bh(a){return a instanceof u.AcDbCurve}function Dh(a,e){e.layer=a.layer,e.color=a.color.clone(),e.lineType=a.lineType,e.lineWeight=a.lineWeight,e.linetypeScale=a.linetypeScale,e.transparency=a.transparency,e.visibility=a.visibility}function Ko(a,e,t){try{const i=a.getOffsetSideAtPoint(t),n=a.getOffsetCurves(e*i);return n.forEach(s=>Dh(a,s)),n}catch{return[]}}class Mh extends ${constructor(e,t,i){super(e),this._previewCurves=[],this._renderedIds=[],this._view=e,this._curve=t,this._distance=i}get entity(){return this._previewCurves[0]??null}update(e){this.clearRendered(),this._previewCurves=Ko(this._curve,this._distance,e)}render(){this._previewCurves.length!==0&&(this._view.addTransientEntity(this._previewCurves),this._renderedIds=this._previewCurves.map(e=>e.objectId))}end(){this.clearRendered()}clearRendered(){this._renderedIds.forEach(e=>this._view.removeTransientEntity(e)),this._renderedIds=[]}}class Nt extends N{constructor(){super(),this.mode=j.Review}async execute(e){const t=e.doc.database.tables.blockTable,i=new we(e.doc.database);let n,s;class r{constructor(d){this.machine=d}buildPrompt(){const d=Nt._lastDistance,g=d!=null?`${p.t("jig.offset.distance")} <${d}>`:p.t("jig.offset.distance"),m=new he(g);return m.useBasePoint=!1,m.useDashedLine=!0,m.allowZero=!1,m.allowNegative=!1,d!=null&&(m.defaultValue=d,m.useDefaultValue=!0,m.allowNone=!0),m}handleResult(d){return!(d instanceof ie)||d.status!==v.OK||d.value==null?"finish":!Number.isFinite(d.value)||u.AcGeTol.isNonPositive(d.value)?(S.instance.editor.showMessage(p.t("jig.offset.invalidDistance"),"warning"),"finish"):(n=d.value,Nt._lastDistance=d.value,this.machine.setState(new o(this.machine)),"continue")}}class o{constructor(d){this.machine=d}buildPrompt(){const d=new Le(p.t("jig.offset.selectObject"));return d.allowNone=!0,d.allowObjectOnLockedLayer=!0,d.setRejectMessage(p.t("jig.offset.invalidSelection")),d}handleResult(d){if(!(d instanceof si)||d.status===v.None||d.status!==v.OK||!d.objectId)return"finish";const g=e.doc.openMode==j.Review?i.filterAnnotationEntities([d.objectId]):[d.objectId],m=t.getEntityById(g[0]);return Bh(m)?(s=m,this.machine.setState(new c(this.machine)),"continue"):(S.instance.editor.showMessage(p.t("jig.offset.invalidSelection"),"warning"),"continue")}}class c{constructor(d){this.machine=d}buildPrompt(){const d=new D(p.t("jig.offset.sidePoint"));if(d.allowNone=!0,d.disableOSnap=!0,s&&n!=null){const g=new Mh(e.view,s,n);g.update({...e.view.curPos,z:0}),g.render(),d.jig=g}return d}handleResult(d){if(!(d instanceof oi)||d.status!==v.OK||!d.value||!s||n==null)return"finish";const g=Ko(s,n,new u.AcGePoint3d(d.value));return g.length===0?S.instance.editor.showMessage(p.t("jig.offset.offsetFailed"),"warning"):t.modelSpace.appendEntity(g),s=void 0,this.machine.setState(new o(this.machine)),"continue"}}const l=new Te;l.setState(new r(l)),await l.run(h=>h instanceof he?S.instance.editor.getDistance(h):h instanceof Le?S.instance.editor.getEntity(h):S.instance.editor.getPoint(h))}}class Yi extends ${constructor(e,t){super(e),this._view=e,this._previewEntities=t.map(i=>i.clone()).filter(i=>!!i)}get entity(){return this._previewEntities[0]??null}update(e){}render(){this._previewEntities.length!==0&&this._view.addTransientEntity(this._previewEntities)}end(){this._previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}}class Uo extends ${constructor(e,t,i,n=0){super(e),this._lastAngleRad=0,this._view=e,this._basePoint=new u.AcGePoint3d(i),this._referenceAngleDeg=n,this._previewEntities=t.map(s=>s.clone()).filter(s=>!!s)}get entity(){return this._previewEntities[0]??null}update(e){if(this._previewEntities.length===0)return;const t=(e-this._referenceAngleDeg)*Math.PI/180,i=t-this._lastAngleRad;if(u.AcGeTol.equalToZero(i))return;const n=Rt.createRotationMatrix(this._basePoint,i);this._previewEntities.forEach(s=>s.transformBy(n)),this._lastAngleRad=t}render(){this._previewEntities.length!==0&&this._view.addTransientEntity(this._previewEntities)}end(){this._previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}}class Rt extends N{constructor(){super(),this.mode=j.Review}static createRotationMatrix(e,t){return new u.AcGeMatrix3d().makeTranslation(e.x,e.y,e.z).multiply(new u.AcGeMatrix3d().makeRotationZ(t)).multiply(new u.AcGeMatrix3d().makeTranslation(-e.x,-e.y,-e.z))}addKeyword(e,t){e.keywords.add(p.t(`jig.rotate.keywords.${t}.display`),p.t(`jig.rotate.keywords.${t}.global`),p.t(`jig.rotate.keywords.${t}.local`))}warnInvalidInput(e){J.emit("message",{message:p.t(`jig.rotate.invalid.${e}`),type:"warning"})}computeAngleDeg(e,t){const i=t.x-e.x,n=t.y-e.y;if(u.AcGeTol.isPositive(Math.hypot(i,n)))return Math.atan2(n,i)*180/Math.PI}async promptReferenceAngle(e,t,i){for(;;){const n=new xe(p.t("jig.rotate.referenceAngleOrPoints"));this.addKeyword(n,"points"),n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=i,n.allowNegative=!0,n.allowZero=!0,n.useDefaultValue=!0,n.defaultValue=0,n.jig=new Yi(e.view,t);const s=await S.instance.editor.getAngle(n);if(s.status===v.OK)return s.value??0;if(s.status===v.Keyword&&s.stringResult==="Points"){const r=new D(p.t("jig.rotate.firstReferencePoint"));r.jig=new Yi(e.view,t);const o=await S.instance.editor.getPoint(r);if(o.status!==v.OK)return;const c=new D(p.t("jig.rotate.secondReferencePoint"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(o.value),c.jig=new Yi(e.view,t);const l=await S.instance.editor.getPoint(c);if(l.status!==v.OK)return;const h=this.computeAngleDeg(o.value,l.value);if(h==null){this.warnInvalidInput("referencePoints");continue}return h}return}}async promptRotationAngle(e,t,i){let n=!1;for(;;){const s=new xe(p.t("jig.rotate.rotationAngleOrOptions"));this.addKeyword(s,"copy"),this.addKeyword(s,"reference"),s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=i,s.allowNegative=!0,s.allowZero=!0,s.jig=new Uo(e.view,t,i);const r=await S.instance.editor.getAngle(s);if(r.status===v.OK)return{copyMode:n,angleRad:(r.value??0)*Math.PI/180};if(r.status!==v.Keyword)return;const o=r.stringResult??"";if(o==="Copy"){n=!0;continue}if(o!=="Reference")return;const c=await this.promptReferenceAngle(e,t,i);if(c==null)return;const l=new xe(p.t("jig.rotate.newAngle"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=i,l.allowNegative=!0,l.allowZero=!0,l.jig=new Uo(e.view,t,i,c);const h=await S.instance.editor.getAngle(l);return h.status!==v.OK?void 0:{copyMode:n,angleRad:((h.value??0)-c)*Math.PI/180}}}async execute(e){var m;const t=e.view.selectionSet,i=new we(e.doc.database),n=e.doc.database.tables.blockTable,s=t.count>0?t.ids:((m=(await S.instance.editor.getSelection(new je(p.sysCmdPrompt("rotate")))).value)==null?void 0:m.ids)??[];if(s.length===0)return;const r=e.doc.openMode==j.Review?i.filterAnnotationEntities(s):s;if(r.length===0){t.clear();return}const o=r.map(y=>n.getEntityById(y)).filter(y=>!!y);if(o.length===0){t.clear();return}const c=new D(p.t("jig.rotate.basePoint"));c.jig=new Yi(e.view,o);const l=await S.instance.editor.getPoint(c);if(l.status!==v.OK){t.clear();return}const h=new u.AcGePoint3d(l.value),d=await this.promptRotationAngle(e,o,h);if(!d){t.clear();return}const g=Rt.createRotationMatrix(h,d.angleRad);if(d.copyMode){const y=o.map(w=>w.clone()).filter(w=>!!w);y.forEach(w=>w.transformBy(g)),y.length>0&&n.modelSpace.appendEntity(y)}else o.forEach(y=>{y.transformBy(g),y.triggerModifiedEvent()});t.clear()}}class gt extends N{constructor(){super(),this.mode=j.Review,this._isShowEntityDrawStyleToolbar=!0}get isShowEntityDrawStyleToolbar(){return this._isShowEntityDrawStyleToolbar}set isShowEntityDrawStyleToolbar(e){this._isShowEntityDrawStyleToolbar=e}onCommandWillStart(e){const t=e.doc.database,i=new we(t);this._previousLayer=t.clayer,this._previousCecolor=t.cecolor.toString(),this._previousCelweight=t.celweight,this._revisionLayer=i.getAnnotationLayer(),t.clayer=this._revisionLayer}onCommandEnded(e){const t=e.doc.database;this._previousLayer&&(t.clayer=this._previousLayer),this._previousCecolor&&(t.cecolor=u.AcCmColor.fromString(this._previousCecolor)??new u.AcCmColor),this._previousCelweight&&(t.celweight=this._previousCelweight),this._previousLayer=void 0,this._revisionLayer=void 0}}const Oh=8;function Fh(a,e,t){const i=a.worldToScreen(t),n=new u.AcGePoint2d(i.x+e,i.y),s=a.screenToWorld(n);return Math.abs(s.x-t.x)}function Wo(a,e,t,i){a.reset(!1);const n=Math.min(e.x,t.x),s=Math.max(e.x,t.x),r=Math.min(e.y,t.y),o=Math.max(e.y,t.y),c=s-n,l=o-r,h=new u.AcGePoint2d((n+s)/2,(r+o)/2),g=Fh(i,Oh,h),m=Math.max(4,Math.ceil(c/g)*2),y=Math.max(4,Math.ceil(l/g)*2),w=[],C=[];let b=0;const x=A=>A?.4:-.4;for(let A=0;A<=m;A++){const _=A/m,L=n+c*_,T=r;if(w.push(new u.AcGePoint2d(L,T)),A<m){const O=b%2===0;C.push(x(O)),b++}else C.push(void 0)}for(let A=1;A<=y;A++){const _=A/y,L=s,T=r+l*_;if(w.push(new u.AcGePoint2d(L,T)),A<y){const O=b%2===0;C.push(x(O)),b++}else C.push(void 0)}for(let A=1;A<=m;A++){const _=1-A/m,L=n+c*_,T=o;if(w.push(new u.AcGePoint2d(L,T)),A<m){const O=b%2===0;C.push(x(O)),b++}else C.push(void 0)}for(let A=1;A<y;A++){const _=1-A/y,L=n,T=r+l*_;if(w.push(new u.AcGePoint2d(L,T)),A<y-1){const O=b%2===0;C.push(x(O)),b++}else C.push(void 0)}for(let A=0;A<w.length;A++){const _=C[A];a.addVertexAt(A,w[A],_)}a.closed=!0}class Ho extends ${constructor(e,t){super(e),this._cloud=new u.AcDbPolyline,this._firstPoint=new u.AcGePoint2d(t),this._view=e}get entity(){return this._cloud}update(e){Wo(this._cloud,this._firstPoint,e,this._view)}}class Yo extends gt{constructor(){super(),this.mode=j.Review}async execute(e){const t=new D(p.t("jig.line.firstPoint")),i=await S.instance.editor.getPoint(t);if(i.status!==v.OK)return;const n=i.value,s=new D(p.t("jig.line.nextPoint"));s.jig=new Ho(e.view,n),s.useDashedLine=!1,s.useBasePoint=!0;const r=await S.instance.editor.getPoint(s);if(r.status!==v.OK)return;const o=r.value,c=e.doc.database,l=new u.AcDbPolyline;Wo(l,n,o,e.view),c.tables.blockTable.modelSpace.appendEntity(l)}}class Xo extends gt{constructor(){super(),this.mode=j.Review}async execute(e){const t=new D(p.t("jig.circle.center")),i=await S.instance.editor.getPoint(t);if(i.status!==v.OK)return;const n=i.value,s=new he(p.t("jig.circle.radius"));s.allowZero=!1,s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(n),s.jig=new ji(e.view,n);const r=await S.instance.editor.getDistance(s);if(r.status!==v.OK)return;const o=r.value;e.doc.database.tables.blockTable.modelSpace.appendEntity(new u.AcDbCircle(n,o))}}function qo(a,e,t){a.reset(!1),a.addVertexAt(0,new u.AcGePoint2d(e)),a.addVertexAt(1,new u.AcGePoint2d(t.x,e.y)),a.addVertexAt(2,new u.AcGePoint2d(t)),a.addVertexAt(3,new u.AcGePoint2d(e.x,t.y)),a.closed=!0}class jh extends ${constructor(e,t){super(e),this._rect=new u.AcDbPolyline,this._firstPoint=new u.AcGePoint2d(t)}get entity(){return this._rect}update(e){qo(this._rect,this._firstPoint,e)}}class Zo extends gt{constructor(){super(),this.mode=j.Review}async execute(e){const t=new D(p.t("jig.rect.firstPoint")),i=await S.instance.editor.getPoint(t);if(i.status!==v.OK)return;const n=i.value,s=new D(p.t("jig.rect.nextPoint"));s.jig=new jh(e.view,n),s.useDashedLine=!1,s.useBasePoint=!0;const r=await S.instance.editor.getPoint(s);if(r.status!==v.OK)return;const o=r.value,c=e.doc.database,l=new u.AcDbPolyline;qo(l,n,o),c.tables.blockTable.modelSpace.appendEntity(l)}}class Jo extends gt{constructor(){super(),this.mode=j.Review,this.isShowEntityDrawStyleToolbar=!1}async execute(e){const t=e.doc.database,n=new we(t).getAnnotationLayer();if(n){const s=t.tables.layerTable.getAt(n);s&&(s.isOff=!s.isOff)}}}const Nh=.1;function Qo(a,e){const t=e.x-a.x,i=e.y-a.y;return Math.sqrt(t*t+i*i)}class ea extends ${constructor(e,t){super(e),this._lastPoint=null,this._polyline=new u.AcDbPolyline,this._points=[new u.AcGePoint2d(t)],this._lastPoint=new u.AcGePoint2d(t),this._polyline.addVertexAt(0,this._points[0])}get entity(){return this._polyline}get points(){return this._points}update(e){if(this._lastPoint===null)return;const t=new u.AcGePoint2d(e);Qo(this._lastPoint,t)>=Nh&&(this._points.push(t),this._lastPoint=t,this._polyline.addVertexAt(this._points.length,t))}}class ta extends gt{constructor(){super(),this.mode=j.Review}async execute(e){const t=new D(p.t("jig.sketch.firstPoint")),i=await S.instance.editor.getPoint(t);if(i.status!==v.OK)return;const n=i.value,s=new ea(e.view,n),r=new D(p.t("jig.sketch.nextPoint"));r.jig=s,r.useDashedLine=!1,r.useBasePoint=!0;const o=await S.instance.editor.getPoint(r);if(o.status!==v.OK)return;const c=o.value,l=s.points,h=l[l.length-1],d=new u.AcGePoint2d(c);Qo(h,d)>.01&&l.push(d);const g=e.doc.database,m=new u.AcDbPolyline;for(let y=0;y<l.length;y++)m.addVertexAt(y,l[y]);g.tables.blockTable.modelSpace.appendEntity(m)}}class ia extends N{async execute(e){this.printSelectionSet(e),this.printStats(e),this.printPerformanceData()}printSelectionSet(e){const t=e.doc.database.tables.blockTable.modelSpace;e.view.selectionSet.ids.forEach(i=>{const n=t.getIdAt(i);n&&u.log.info(n)})}printStats(e){const t=e.view.stats,i=t.layouts;u.log.info("Geometry information in current drawing:");for(let n=0;n<i.length;++n){console.group(`Layout: ${n}`);const s=i[n],r=[0,0,0,0,0,0,0],o=[0,0,0,0,0,0,0];let c=0;const l=s.layers.map(h=>(r[0]=h.line.indexed.geometrySize/1024,r[1]=h.line.nonIndexed.geometrySize/1024,r[2]=h.mesh.indexed.geometrySize/1024,r[3]=h.mesh.nonIndexed.geometrySize/1024,r[4]=h.point.indexed.geometrySize/1024,r[5]=h.point.nonIndexed.geometrySize/1024,r[6]=h.unbatched.geometrySize/1024,o[0]+=r[0],o[1]+=r[1],o[2]+=r[2],o[3]+=r[3],o[4]+=r[4],o[5]+=r[5],o[6]+=r[6],c+=h.unbatched.count,{name:h.name,"idx line (KB)":r[0].toFixed(1),"line (KB)":r[1].toFixed(1),"idx mesh (KB)":r[2].toFixed(1),"mesh (KB)":r[3].toFixed(1),"idx point (KB)":r[4].toFixed(1),"point (KB)":r[5].toFixed(1),"unbatched (KB)":r[6].toFixed(1),"unbatched count":h.unbatched.count,"unbatched line":h.unbatched.byType.line,"unbatched mesh":h.unbatched.byType.mesh,"unbatched point":h.unbatched.byType.point,"unbatched other":h.unbatched.byType.other,"total geo (KB)":(h.summary.totalGeometrySize/1024).toFixed(1),"total mapping (KB)":(h.summary.totalMappingSize/1024).toFixed(1)}));l.push({name:"total","idx line (KB)":o[0].toFixed(1),"line (KB)":o[1].toFixed(1),"idx mesh (KB)":o[2].toFixed(1),"mesh (KB)":o[3].toFixed(1),"idx point (KB)":o[4].toFixed(1),"point (KB)":o[5].toFixed(1),"unbatched (KB)":o[6].toFixed(1),"unbatched count":c,"unbatched line":s.summary.totalSize.unbatchedByType.line,"unbatched mesh":s.summary.totalSize.unbatchedByType.mesh,"unbatched point":s.summary.totalSize.unbatchedByType.point,"unbatched other":s.summary.totalSize.unbatchedByType.other,"total geo (KB)":(s.summary.totalSize.geometry/1024).toFixed(1),"total mapping (KB)":(s.summary.totalSize.mapping/1024).toFixed(1)}),console.table(l),console.table([{layoutCount:t.summary.layoutCount,entityCount:t.summary.entityCount,"scene line (KB)":(t.summary.totalSize.line/1024).toFixed(1),"scene mesh (KB)":(t.summary.totalSize.mesh/1024).toFixed(1),"scene point (KB)":(t.summary.totalSize.point/1024).toFixed(1),"scene unbatched (KB)":(t.summary.totalSize.unbatched/1024).toFixed(1),"scene unbatched count":t.summary.totalSize.unbatchedCount,"scene unbatched line":t.summary.totalSize.unbatchedByType.line,"scene unbatched mesh":t.summary.totalSize.unbatchedByType.mesh,"scene unbatched point":t.summary.totalSize.unbatchedByType.point,"scene unbatched other":t.summary.totalSize.unbatchedByType.other,"scene total geo (KB)":(t.summary.totalSize.geometry/1024).toFixed(1),"scene total mapping (KB)":(t.summary.totalSize.mapping/1024).toFixed(1)}]),console.groupEnd()}}printPerformanceData(){u.AcCmPerformanceCollector.getInstance().printAll()}}class na extends N{async execute(e){J.emit("open-file",{})}}class sa extends N{async execute(e){const t=S.instance.baseUrl;S.instance.openUrl(t+"templates/acadiso.dxf")}}class ra extends N{async execute(){S.instance.regen()}}class oa extends N{async execute(e){e.view.mode=se.SELECTION,e.view.setCursor(be.Crosshair)}}class aa extends N{constructor(){super(),this.mode=j.Review}async execute(e){const t=u.AcDbSysVarManager.instance(),i=t.getVar(this.globalName,e.doc.database),n=p.t("jig.sysvar.prompt").trim(),s=n.match(/([::])\s*$/),r=(s==null?void 0:s[1])??":",o=s?n.slice(0,s.index).trimEnd():n,c=i==null?"":` <${String(i)}>`,l=`${o}${c}${r}`,h=new ce(l),d=await S.instance.editor.getString(h);if(d.status!==v.OK||!d.stringResult)return;const g=d.stringResult;t.getDescriptor(this.globalName)&&t.setVar(this.globalName,g,e.doc.database)}}class ca extends N{async execute(e){const t=u.AcDbSystemVariables.WHITEBKCOLOR,i=u.AcDbSysVarManager.instance();if(i.getDescriptor(t)){const s=e.doc.database,r=i.getVar(t,s);i.setVar(t,!r,s)}}}class Je extends N{captureCurrentViewBox(e){const t=e.view.screenToWorld({x:0,y:0}),i=e.view.screenToWorld({x:e.view.width,y:e.view.height});return new u.AcGeBox2d().expandByPoint(t).expandByPoint(i)}rememberViewBeforeZoom(e){Je.previousViewBox=this.captureCurrentViewBox(e)}zoomToExtents(e){this.rememberViewBeforeZoom(e),e.view.zoomToFitDrawing()}zoomToWindow(e,t,i){const n=new u.AcGeBox2d().expandByPoint(t).expandByPoint(i);this.rememberViewBeforeZoom(e),e.view.zoomTo(n,1)}async promptAndZoomWindowFromFirstCorner(e,t){const i=new D(p.t("jig.zoom.secondCorner"));i.useBasePoint=!0,i.basePoint=new u.AcGePoint3d(t),i.useDashedLine=!0;const n=await S.instance.editor.getPoint(i);n.status!==v.OK||!n.value||this.zoomToWindow(e,t,n.value)}async promptAndZoomWindowByBox(e){const t=new ti(p.t("jig.zoom.firstCorner"),p.t("jig.zoom.secondCorner")),i=await S.instance.editor.getBox(t);i.status!==v.OK||!i.value||(this.rememberViewBeforeZoom(e),e.view.zoomTo(i.value,1))}async runCenter(e){const t=new D(p.t("jig.zoom.centerPoint")),i=await S.instance.editor.getPoint(t);if(i.status!==v.OK||!i.value)return;const n=new ce(p.t("jig.zoom.heightOrScale")),s=await S.instance.editor.getString(n);if(s.status!==v.OK||!s.stringResult)return;const r=this.parseScaleFactor(s.stringResult);if(r!=null){this.applyRelativeScale(e,r,i.value);return}const o=Number(s.stringResult);if(!Number.isFinite(o)||o<=0)return;const c=e.view.width/Math.max(e.view.height,1),l=o/2,h=o*c/2,d=new u.AcGeBox2d().expandByPoint({x:i.value.x-h,y:i.value.y-l}).expandByPoint({x:i.value.x+h,y:i.value.y+l});this.rememberViewBeforeZoom(e),e.view.zoomTo(d,1)}parseScaleFactor(e){const t=e.trim().toLowerCase();if(!t)return;if(t.endsWith("xp")){const n=Number(t.slice(0,-2));return Number.isFinite(n)&&n>0?n:void 0}if(t.endsWith("x")){const n=Number(t.slice(0,-1));return Number.isFinite(n)&&n>0?n:void 0}const i=Number(t);return Number.isFinite(i)&&i>0?i:void 0}applyRelativeScale(e,t,i){const n=this.captureCurrentViewBox(e),s=Math.max(n.max.x-n.min.x,u.FLOAT_TOL),r=Math.max(n.max.y-n.min.y,u.FLOAT_TOL),o=s/(2*t),c=r/(2*t),l=i??{x:(n.min.x+n.max.x)/2,y:(n.min.y+n.max.y)/2},h=new u.AcGeBox2d().expandByPoint({x:l.x-o,y:l.y-c}).expandByPoint({x:l.x+o,y:l.y+c});this.rememberViewBeforeZoom(e),e.view.zoomTo(h,1)}runPrevious(e){if(!Je.previousViewBox)return;const t=this.captureCurrentViewBox(e);e.view.zoomTo(Je.previousViewBox,1),Je.previousViewBox=t}async execute(e){const t=new D(p.t("jig.zoom.mainPrompt"));t.allowNone=!0,t.keywords.add(p.t("jig.zoom.keywords.all.display"),p.t("jig.zoom.keywords.all.global"),p.t("jig.zoom.keywords.all.local")),t.keywords.add(p.t("jig.zoom.keywords.center.display"),p.t("jig.zoom.keywords.center.global"),p.t("jig.zoom.keywords.center.local")),t.keywords.add(p.t("jig.zoom.keywords.extents.display"),p.t("jig.zoom.keywords.extents.global"),p.t("jig.zoom.keywords.extents.local")),t.keywords.add(p.t("jig.zoom.keywords.previous.display"),p.t("jig.zoom.keywords.previous.global"),p.t("jig.zoom.keywords.previous.local")),t.keywords.add(p.t("jig.zoom.keywords.scale.display"),p.t("jig.zoom.keywords.scale.global"),p.t("jig.zoom.keywords.scale.local")),t.keywords.add(p.t("jig.zoom.keywords.window.display"),p.t("jig.zoom.keywords.window.global"),p.t("jig.zoom.keywords.window.local"));const i=await S.instance.editor.getPoint(t);if(i.status===v.None){this.zoomToExtents(e);return}if(i.status===v.OK&&i.value){await this.promptAndZoomWindowFromFirstCorner(e,i.value);return}if(i.status!==v.Keyword)return;const n=i.stringResult??"";if(n==="All"||n==="Extents"){this.zoomToExtents(e);return}if(n==="Window"){await this.promptAndZoomWindowByBox(e);return}if(n==="Center"){await this.runCenter(e);return}if(n==="Scale"){const s=new ce(p.t("jig.zoom.scaleFactor")),r=await S.instance.editor.getString(s);if(r.status!==v.OK||!r.stringResult)return;const o=this.parseScaleFactor(r.stringResult);if(o==null)return;this.applyRelativeScale(e,o);return}n==="Previous"&&this.runPrevious(e)}}class la extends N{async execute(e){e.view.mode=se.PAN,e.view.setCursor(be.Grab)}}class ha{constructor(e,t){this._plugins=new Map,this._context=e,this._commandManager=t}async loadPlugin(e){const t=e.name;if(!t)throw new Error("[AcApPluginManager] Plugin name is required");if(this._plugins.has(t))throw new Error(`[AcApPluginManager] Plugin '${t}' is already loaded`);try{await e.onLoad(this._context,this._commandManager)}catch(i){throw new Error(`[AcApPluginManager] Failed to load plugin '${t}': ${i}`)}this._plugins.set(t,e)}async unloadPlugin(e){const t=this._plugins.get(e);if(!t)return!1;try{await t.onUnload(this._context,this._commandManager)}catch(i){u.log.error(`[AcApPluginManager] Error unloading plugin '${e}':`,i)}return this._plugins.delete(e),!0}isPluginLoaded(e){return this._plugins.has(e)}getPlugin(e){return this._plugins.get(e)}getLoadedPlugins(){return Array.from(this._plugins.keys())}async unloadAllPlugins(){const e=Array.from(this._plugins.keys());for(const t of e)await this.unloadPlugin(t)}async loadPluginsFromConfig(e,t){const i=(t==null?void 0:t.continueOnError)??!1,n=[],s=[];for(const r of e)try{const o=typeof r=="function"?r():r;await this.loadPlugin(o),n.push(o.name)}catch(o){const c=typeof r=="function"?"Unknown":r.name||"Unknown",l=o instanceof Error?o:new Error(String(o));if(s.push({name:c,error:l}),!i)throw l}return{loaded:n,failed:s}}async loadPluginsFromFolder(e,t){const i=(t==null?void 0:t.continueOnError)??!1,n=(t==null?void 0:t.pluginList)||[],s=[],r=[];if(n.length===0)return u.log.warn("[AcApPluginManager] No plugin list provided. Cannot load plugins from folder without a list of files."),{loaded:s,failed:r};const o=e.replace(/\/$/,""),c=o.startsWith("./")?o:`./${o}`;for(const l of n)try{const d=await import(`${c}/${l.replace(/^\//,"")}`);let g=d.default,m;if(!g){const w=l.replace(/\.(js|ts)$/,"");m=w.split(/[-_]/).map(C=>C.charAt(0).toUpperCase()+C.slice(1).toLowerCase()).join(""),g=d[m]||d.Plugin||d[w]}if(!g){const w=m||"Plugin";throw new Error(`No plugin export found in ${l}. Expected default export, or named export 'Plugin' or '${w}'.`)}let y;if(typeof g=="function"?g.prototype&&g.prototype.onLoad?y=new g:y=g():y=g,!y||typeof y.onLoad!="function")throw new Error(`Invalid plugin in ${l}. Plugin must implement AcApPlugin interface.`);await this.loadPlugin(y),s.push(y.name)}catch(h){const d=h instanceof Error?h:new Error(String(h));if(r.push({name:l,error:d}),!i)throw d}return{loaded:s,failed:r}}}var Xi=(a=>(a[a.LEFT_BOTTOM=0]="LEFT_BOTTOM",a[a.LEFT_TOP=1]="LEFT_TOP",a[a.RIGHT_TOP=2]="RIGHT_TOP",a[a.RIGHT_BOTTOM=4]="RIGHT_BOTTOM",a))(Xi||{});class Rh extends f.Object3D{constructor(e,t,i=150,n=2){super(),this.camera=e,this.renderer=t,this.gizmoCamera=new f.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 f.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 f.Box2(new f.Vector2(t-s,0),new f.Vector2(t,s));switch(n){case 0:r.set(new f.Vector2(0,i-s),new f.Vector2(s,i));break;case 1:r.set(new f.Vector2(0,0),new f.Vector2(s,s));break;case 4:r.set(new f.Vector2(t-s,i-s),new f.Vector2(t,i));break}return r}}function zh(a,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",c=document.createElement("canvas");c.width=n,c.height=s;const l=c.getContext("2d");if(l){l.font=`bold ${i}px ${t}`,l.fillStyle=`rgba(${r})`,l.fillRect(0,0,n,s);const g=l.measureText(a).width;l.fillStyle=`rgba(${o})`,l.fillText(a,n/2-g/2,s/2+i/2-2)}const h=new f.Texture(c);return h.minFilter=f.LinearFilter,h.needsUpdate=!0,h}function Qn(a){const e=zh(a,{fontSize:100,font:"Arial Narrow, sans-serif",color:[255,255,255,1],bgColor:[0,0,0,0]}),t=new f.SpriteMaterial({map:e,transparent:!0});return new f.Sprite(t)}Xi.RIGHT_TOP;const Vh={pos:Xi.LEFT_BOTTOM,size:100,hasZAxis:!0};class Gh extends Rh{constructor(e,t,i){const n={...Vh,...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 f.BufferGeometry;o.setAttribute("position",new f.Float32BufferAttribute(s,3)),o.setAttribute("color",new f.Float32BufferAttribute(r,3));const c=new f.LineBasicMaterial({vertexColors:!0,toneMapped:!1});this.axes=new f.LineSegments(o,c),this.axes.position.set(-1,-1,-1),this.add(this.axes),this.xText=Qn("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=Qn("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=Qn("Z"),this.zText.position.set(-1,-1,1.5),this.add(this.zText))}setLineColors(e,t){const i=new f.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 $h extends mr{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=se.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==se.SELECTION?this._cameraControls.mouseButtons={MIDDLE:f.MOUSE.PAN}:e==se.PAN&&(this._cameraControls.mouseButtons={LEFT:f.MOUSE.PAN}),this._cameraControls.update(),this._mode=e}get viewportCount(){return this._viewportViews.size}get viewportViews(){return this._viewportViews.values()}get internalCamera(){return this._camera.internalCamera}get viewportsBoundingBox(){if(this._viewportViews.size===0)return;const e=new u.AcGeBox2d;return this._viewportViews.forEach(t=>{const i=t.viewport.box;e.expandByPoint(i.min),e.expandByPoint(i.max)}),e.isEmpty()?void 0:e}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 Gh(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:Xi.LEFT_BOTTOM})}drawViewports(e){if(this._viewportViews.size>0){const t=this._renderer.autoClear;this._renderer.autoClear=!1;const i=new f.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 Kh{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 Uh(a,e){return[...a].sort((t,i)=>Wh(t,i,e))}function Wh(a,e,t){const i=ua(a)-ua(e);if(Math.abs(i)>Number.EPSILON)return i;const n=da(t,a)-da(t,e);return Math.abs(n)>Number.EPSILON?n:0}function ua(a){return Math.max(a.maxX-a.minX,0)*Math.max(a.maxY-a.minY,0)}function da(a,e){const t=a.x<e.minX?e.minX-a.x:a.x>e.maxX?a.x-e.maxX:0,i=a.y<e.minY?e.minY-a.y:a.y>e.maxY?a.y-e.maxY:0;return t*t+i*i}class Hh{constructor(){this.items=new Map}insert(e){this.items.set(e.id,e)}load(e){for(const t of e)this.items.set(t.id,t)}remove(e){this.items.delete(e.id)}removeById(e){this.items.delete(e)}clear(){this.items.clear()}search(e){const t=[];for(const i of this.items.values())pa(i,e)&&t.push(i);return t}collides(e){for(const t of this.items.values())if(pa(t,e))return!0;return!1}all(){return Array.from(this.items.values())}}function pa(a,e){return!(a.maxX<e.minX||a.minX>e.maxX||a.maxY<e.minY||a.minY>e.maxY)}function ga(a,e,t=0,i=a.length-1,n=Yh){for(;i>t;){if(i-t>600){const c=i-t+1,l=e-t+1,h=Math.log(c),d=.5*Math.exp(2*h/3),g=.5*Math.sqrt(h*d*(c-d)/c)*(l-c/2<0?-1:1),m=Math.max(t,Math.floor(e-l*d/c+g)),y=Math.min(i,Math.floor(e+(c-l)*d/c+g));ga(a,e,m,y,n)}const s=a[e];let r=t,o=i;for(zt(a,t,e),n(a[i],s)>0&&zt(a,t,i);r<o;){for(zt(a,r,o),r++,o--;n(a[r],s)<0;)r++;for(;n(a[o],s)>0;)o--}n(a[t],s)===0?zt(a,t,o):(o++,zt(a,o,i)),o<=e&&(t=o+1),e<=o&&(i=o-1)}}function zt(a,e,t){const i=a[e];a[e]=a[t],a[t]=i}function Yh(a,e){return a<e?-1:a>e?1:0}class Xh{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(!Zi(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],c=t.leaf?n(o):o;Zi(e,c)&&(t.leaf?i.push(o):ts(e,c)?this._all(o,i):s.push(o))}t=s.pop()}return i}collides(e){let t=this.data;if(!Zi(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(Zi(e,r)){if(t.leaf||ts(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=yt([]),this}remove(e,t){if(!e)return this;let i=this.data;const n=this.toBBox(e),s=[],r=[];let o,c,l;for(;i||s.length;){if(i||(i=s.pop(),c=s[s.length-1],o=r.pop(),l=!0),i.leaf){const h=qh(e,i.children,t);if(h!==-1)return i.children.splice(h,1),s.push(i),this._condense(s),this}!l&&!i.leaf&&ts(i,n)?(s.push(i),r.push(o),o=0,c=i,i=i.children[0]):c?(o++,i=c.children[o],l=!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=yt(e.slice(t,i+1)),mt(o,this.toBBox),o;n||(n=Math.ceil(Math.log(s)/Math.log(r)),r=Math.ceil(s/Math.pow(r,n-1))),o=yt([]),o.leaf=!1,o.height=n;const c=Math.ceil(s/r),l=c*Math.ceil(Math.sqrt(r));ma(e,t,i,l,this.compareMinX);for(let h=t;h<=i;h+=l){const d=Math.min(h+l-1,i);ma(e,h,d,c,this.compareMinY);for(let g=h;g<=d;g+=c){const m=Math.min(g+c-1,d);o.children.push(this._build(e,g,m,n-1))}}return mt(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 c=0;c<t.children.length;c++){const l=t.children[c],h=es(l),d=Qh(e,l)-h;d<r?(r=d,s=h<s?h:s,o=l):d===r&&h<s&&(s=h,o=l)}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),Gt(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=yt(i.children.splice(r,i.children.length-r));o.height=i.height,o.leaf=i.leaf,mt(i,this.toBBox),mt(o,this.toBBox),t?e[t-1].children.push(o):this._splitRoot(i,o)}_splitRoot(e,t){this.data=yt([e,t]),this.data.height=e.height+1,this.data.leaf=!1,mt(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 c=Vt(e,0,o,this.toBBox),l=Vt(e,o,i,this.toBBox),h=eu(c,l),d=es(c)+es(l);h<s?(s=h,n=o,r=d<r?d:r):h===s&&d<r&&(r=d,n=o)}return n||i-t}_chooseSplitAxis(e,t,i){const n=e.leaf?this.compareMinX:Zh,s=e.leaf?this.compareMinY:Jh,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=Vt(e,0,t,s),o=Vt(e,i-t,i,s);let c=qi(r)+qi(o);for(let l=t;l<i-t;l++){const h=e.children[l];Gt(r,e.leaf?s(h):h),c+=qi(r)}for(let l=i-t-1;l>=t;l--){const h=e.children[l];Gt(o,e.leaf?s(h):h),c+=qi(o)}return c}_adjustParentBBoxes(e,t,i){for(let n=i;n>=0;n--)Gt(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():mt(e[t],this.toBBox)}}function qh(a,e,t){if(!t)return e.indexOf(a);for(let i=0;i<e.length;i++)if(t(a,e[i]))return i;return-1}function mt(a,e){Vt(a,0,a.children.length,e,a)}function Vt(a,e,t,i,n){n||(n=yt(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=a.children[s];Gt(n,a.leaf?i(r):r)}return n}function Gt(a,e){return a.minX=Math.min(a.minX,e.minX),a.minY=Math.min(a.minY,e.minY),a.maxX=Math.max(a.maxX,e.maxX),a.maxY=Math.max(a.maxY,e.maxY),a}function Zh(a,e){return a.minX-e.minX}function Jh(a,e){return a.minY-e.minY}function es(a){return(a.maxX-a.minX)*(a.maxY-a.minY)}function qi(a){return a.maxX-a.minX+(a.maxY-a.minY)}function Qh(a,e){return(Math.max(e.maxX,a.maxX)-Math.min(e.minX,a.minX))*(Math.max(e.maxY,a.maxY)-Math.min(e.minY,a.minY))}function eu(a,e){const t=Math.max(a.minX,e.minX),i=Math.max(a.minY,e.minY),n=Math.min(a.maxX,e.maxX),s=Math.min(a.maxY,e.maxY);return Math.max(0,n-t)*Math.max(0,s-i)}function ts(a,e){return a.minX<=e.minX&&a.minY<=e.minY&&e.maxX<=a.maxX&&e.maxY<=a.maxY}function Zi(a,e){return e.minX<=a.maxX&&e.minY<=a.maxY&&e.maxX>=a.minX&&e.maxY>=a.minY}function yt(a){return{children:a,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function ma(a,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;ga(a,r,e,t,n),s.push(e,r,r,t)}}class ya{constructor(e){this.tree=new Xh(e),this.idMap=new Map}insert(e){this.idMap.has(e.id)||(this.tree.insert(e),this.idMap.set(e.id,e))}load(e){this.tree.load(e)}remove(e,t){this.tree.remove(e,t),this.idMap.delete(e.id)}removeById(e){this.tree.remove({minX:0,minY:0,maxX:0,maxY:0,id:e},(t,i)=>t.id===i.id),this.idMap.delete(e)}clear(){this.tree.clear(),this.idMap.clear()}search(e){return this.tree.search(e)}collides(e){return this.tree.collides(e)}all(){return this.tree.all()}}const tn=class tn{constructor(e){this.childIndexes=new Map,this.rootIndex=e??new ya}setChildIndex(e,t){this.childIndexes.set(e,t)}removeChildIndex(e){this.childIndexes.delete(e)}insert(e){this.rootIndex.insert(e)}load(e){this.rootIndex.load(e)}remove(e,t){this.rootIndex.remove(e,t),this.childIndexes.delete(e.id)}removeById(e){this.rootIndex.removeById(e),this.childIndexes.delete(e)}clear(){this.rootIndex.clear(),this.childIndexes.forEach(e=>e.clear()),this.childIndexes.clear()}search(e){const t=this.rootIndex.search(e),i=[];for(const n of t){const s=this.childIndexes.get(n.id);if(!s){i.push(n);continue}const r=s.search(e);i.push({...n,children:r})}return i}collides(e){return this.rootIndex.collides(e)?this.rootIndex.search(e).some(i=>{const n=this.childIndexes.get(i.id);return n?n.collides(e):!0}):!1}all(){const e=[];for(const t of this.rootIndex.all()){const i=this.childIndexes.get(t.id);i?e.push(...i.all()):e.push(t)}return e}hasChildIndex(e){return this.childIndexes.has(e)}ensureChildIndex(e,t){if(this.hasChildIndex(e))return this.childIndexes.get(e);const i=this.createIndexBySize(t.length);if(i)return t.forEach(n=>i.insert(n)),this.setChildIndex(e,i),i}createChildIndex(e){return this.ensureChildIndex(e.objectId,e.boxes)}createIndexBySize(e){if(e>tn.THRESHOLD)return new ya;if(e>0)return new Hh}};tn.THRESHOLD=100;let is=tn;class tu{constructor(e){this._group=new wl,this._name=e.name,this._box=new f.Box3,this._group.visible=!(e.isFrozen||e.isOff)}get name(){return this._name}set name(e){this._name=e}get box(){return this._box}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}update(e){this._name=e.name,this._group.visible=!(e.isFrozen||e.isOff)}updateMaterial(e,t){this._group.updateMaterial(e,t)}rerenderPoints(e){this._group.rerenderPoints(e)}hasEntity(e){return this._group.hasEntity(e)}addEntity(e,t=!0){this._group.addEntity(e);const i=e.box;t&&this._box.union(i)}isIntersectWith(e,t){return this._group.isIntersectWith(e,t)}removeEntity(e){return this._group.removeEntity(e)}updateEntity(e){if(!e.objectId)return!1;const t=this._group.removeEntity(e.objectId);return t&&this._group.addEntity(e),t}clear(){this._group.clear(),this._box.makeEmpty(),this._group.removeFromParent()}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 iu{constructor(){this._group=new f.Group,this._spatialIndex=new is,this._box=new f.Box3,this._layers=new Map,this._isLoaded=!1}get internalObject(){return this._group}get layers(){return this._layers}get box(){return this._box}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}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,o=0,c=0;const l={line:0,mesh:0,point:0,other:0};return this._layers.forEach(h=>{const d=h.stats;e.push(d),n+=d.line.indexed.geometrySize+d.line.nonIndexed.geometrySize,s+=d.mesh.indexed.geometrySize+d.mesh.nonIndexed.geometrySize,r+=d.point.indexed.geometrySize+d.point.nonIndexed.geometrySize,o+=d.unbatched.geometrySize,c+=d.unbatched.count,l.line+=d.unbatched.byType.line,l.mesh+=d.unbatched.byType.mesh,l.point+=d.unbatched.byType.point,l.other+=d.unbatched.byType.other,t+=d.summary.totalGeometrySize,i+=d.summary.totalMappingSize}),{layers:e,summary:{entityCount:this.entityCount,totalSize:{line:n,mesh:s,point:r,unbatched:o,geometry:t,mapping:i,unbatchedCount:c,unbatchedByType:l}}}}clear(){return this._layers.forEach(e=>{e.clear()}),this._layers.clear(),this._box.makeEmpty(),this._spatialIndex.clear(),this}rerenderPoints(e){this._layers.forEach(t=>{t.rerenderPoints(e)})}isIntersectWith(e,t){const i=this.getLayersByObjectId(e);for(let n=0;n<i.length;++n){const s=i[n];if(s&&s.isIntersectWith(e,t))return!0}return!1}hasVisibleEntity(e){return this.getLayersByObjectId(e).some(t=>t.visible)}addEntity(e,t=!0){if(!e.objectId)throw new Error("Object id is required to add one entity!");if(!e.layerName)throw new Error("Layer name is required to add one entity!");const i=this._layers.get(e.layerName);if(!i)throw new Error(`layer '${e.layerName}' doesn't exist!`);i.addEntity(e);const n=e.box;t&&this._box.union(n),this._spatialIndex.insert({minX:n.min.x,minY:n.min.y,maxX:n.max.x,maxY:n.max.y,id:e.objectId});const s=this.getSpatialIndexChildBoxes(e);return s?this._spatialIndex.ensureChildIndex(e.objectId,s):e instanceof He&&this._spatialIndex.createChildIndex(e),this}removeEntity(e){let t=!1;for(const[i,n]of this._layers)n.removeEntity(e)&&(t=!0);return this._spatialIndex.removeById(e),t}updateEntity(e){for(const[t,i]of this._layers)if(i.updateEntity(e))return!0;return!1}getLayer(e){return this._layers.get(e)}addLayer(e){const t=e.name;let i=this._layers.get(t);return i===void 0&&(i=new tu(e),this._layers.set(t,i),this._group.add(i.internalObject)),i}updateLayer(e){const t=this._layers.get(e.name);return t&&t.update(e),t}hover(e){e.forEach(t=>{this.getLayersByObjectId(t).forEach(n=>n.hover([t]))})}unhover(e){e.forEach(t=>{this.getLayersByObjectId(t).forEach(n=>n.unhover([t]))})}select(e){e.forEach(t=>{this.getLayersByObjectId(t).forEach(n=>n.select([t]))})}unselect(e){e.forEach(t=>{this.getLayersByObjectId(t).forEach(n=>n.unselect([t]))})}search(e){return this._spatialIndex.search({minX:e.min.x,minY:e.min.y,maxX:e.max.x,maxY:e.max.y})}getLayersByObjectId(e){const t=[];for(const[i,n]of this._layers)n.hasEntity(e)&&t.push(n);return t}getSpatialIndexChildBoxes(e){const t=e.userData.spatialIndexChildBoxes;if(!(!t||t.length===0))return t}}class nu{constructor(){this._scene=new f.Scene,this._transientManager=new ar(this._scene),this._htmlTransientManager=new or(this._scene),this._layers=new Map,this._layouts=new Map,this._activeLayoutBtrId="",this._modelSpaceBtrId=""}get htmlTransientManager(){return this._htmlTransientManager}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=[];let t=0,i=0,n=0,s=0,r=0,o=0,c=0,l=0;const h={line:0,mesh:0,point:0,other:0};return this._layouts.forEach(d=>e.push(d.stats)),e.forEach(d=>{t+=d.summary.entityCount,i+=d.summary.totalSize.line,n+=d.summary.totalSize.mesh,s+=d.summary.totalSize.point,r+=d.summary.totalSize.unbatched,o+=d.summary.totalSize.geometry,c+=d.summary.totalSize.mapping,l+=d.summary.totalSize.unbatchedCount,h.line+=d.summary.totalSize.unbatchedByType.line,h.mesh+=d.summary.totalSize.unbatchedByType.mesh,h.point+=d.summary.totalSize.unbatchedByType.point,h.other+=d.summary.totalSize.unbatchedByType.other}),{layouts:e,summary:{layoutCount:e.length,entityCount:t,totalSize:{line:i,mesh:n,point:s,unbatched:r,geometry:o,mapping:c,unbatchedCount:l,unbatchedByType:h}}}}addEmptyLayout(e){const t=this._layouts.get(e);if(t)return t;const i=new iu;return this._layouts.set(e,i),this._scene.add(i.internalObject),i.visible=e==this._activeLayoutBtrId,this._layers.forEach(n=>{i.addLayer(n)}),i}clear(){return this._layouts.forEach(e=>{this._scene.remove(e.internalObject),e.clear()}),this._layouts.clear(),this._layers.clear(),this._transientManager.clear(),this._htmlTransientManager.clear(),this._scene.clear(),this._transientManager=new ar(this._scene),this._htmlTransientManager=new or(this._scene),this}hover(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.hover(e)),!0)}unhover(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.unhover(e)),!0)}select(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.select(e)),!0)}unselect(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.unselect(e)),!0)}search(e){const t=this.activeLayout;return t?t==null?void 0:t.search(e):[]}addLayer(e){const t=[];return this._layers.set(e.name,e),this._layouts.forEach(i=>{const n=i.addLayer(e);n&&t.push(n)}),t}updateLayer(e){const t=[];return this._layers.set(e.name,e),this._layouts.forEach(i=>{const n=i.updateLayer(e);n&&t.push(n)}),t}addTransientEntity(e){this._transientManager.update(e)}removeTransientEntity(e){this._transientManager.remove(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 u.log.warn("[AcTrSecene] The owner id of one entity cannot be empty!");return this}removeEntity(e){for(const[t,i]of this._layouts)if(i.removeEntity(e))return!0;return!1}updateEntity(e){for(const[t,i]of this._layouts)if(i.updateEntity(e))return!0;return!1}}const ns={background:0};class fa extends js{constructor(e=ns){const t={...ns,...e},i=t.container??document.createElement("div");t.container=i;const n=new f.WebGLRenderer({antialias:!0,alpha:!0});i.appendChild(n.domElement),super(n.domElement,i),this._rafId=null,this._loadingLayouts=new Set,this._initializedLayouts=new Set,this.animate=()=>{var d;this._rafId=requestAnimationFrame(this.animate),this.events.renderFrame.dispatch({render:this._renderer,camera:this.internalCamera}),this._isDirty&&(this._layoutViewManager.render(this._scene),this.internalCamera&&this._css2dRenderer.render(this._scene.internalScene,this.internalCamera),(d=this._stats)==null||d.update(),this._isDirty=!1)},e.calculateSizeCallback&&this.setCalculateSizeCallback(e.calculateSizeCallback),n.setPixelRatio(Math.min(window.devicePixelRatio,2)),n.setSize(this.width,this.height),this._renderer=new Kc(n);const s=ye.instance.fontMapping;this._renderer.setFontMapping(s),this._renderer.events.fontNotFound.addEventListener(d=>{J.emit("font-not-found",{fontName:d.fontName,count:d.count??0})}),this._scene=this.createScene(),this.backgroundColor=t.background||0,this._stats=this.createStats(ye.instance.isShowStats),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(d=>{const g=d.name.toLowerCase();if(g===u.AcDbSystemVariables.WHITEBKCOLOR.toLowerCase()){const m=d.newVal;this.backgroundColor=m?16777215:0}else if(g===u.AcDbSystemVariables.COLORTHEME.toLowerCase()){const m=d.newVal,y=typeof m=="number"?m===1:typeof m=="boolean"?m:String(m).toLowerCase()==="light"||String(m)==="1";this.backgroundColor=y?16777215:0}}),ye.instance.events.modified.addEventListener(d=>{d.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,d.value)});let r=null,o=null,c=null;const l=()=>this.mode===se.SELECTION&&!this.editor.isActive&&!Re.getActiveInputBox(),h=()=>{c==null||c.remove(),c=null};this.canvas.addEventListener("mousedown",d=>{d.button===0&&l()&&(o=this.viewportToCanvas({x:d.clientX,y:d.clientY}),r=this.screenToWorld(o),c=document.createElement("div"),c.className="ml-jig-preview-rect",this.container.appendChild(c))}),this.canvas.addEventListener("mousemove",d=>{if(!r||!c||!o)return;const g=this.viewportToCanvas({x:d.clientX,y:d.clientY}),m=this.screenToWorld(g),y=this.worldToScreen(r),w=this.worldToScreen(m),C=Math.min(y.x,w.x),b=Math.min(y.y,w.y),x=Math.abs(y.x-w.x),A=Math.abs(y.y-w.y),_=this.getSelectionMode(o,g),L=this.getPointerSelectionAction(d),T=this.getSelectionPreviewStyle(_,L);Object.assign(c.style,{left:`${C}px`,top:`${b}px`,width:`${x}px`,height:`${A}px`,borderStyle:T.borderStyle,background:T.background}),c.style.setProperty("--line-color",T.lineColor)}),this.canvas.addEventListener("mouseup",d=>{if(!r||!o)return;const g=this.viewportToCanvas({x:d.clientX,y:d.clientY}),m=this.screenToWorld(g);h();const y=this.getPointerSelectionAction(d);if(this.isSelectionClick(o,g)){const w=this.pick(m);w.length>0?this.applySelection([w[0].id],y):y==="replace"&&this.selectionSet.clear()}else{const w=new u.AcGeBox2d().expandByPoint(r).expandByPoint(m),C=this.getSelectionMode(o,g);this.selectByBoxWithMode(w,C,y)}r=null,o=null}),this.canvas.addEventListener("dblclick",d=>{d.button===0&&l()&&S.instance.curDocument.openMode===j.Write&&this.openPickedMTextEditor(d)}),document.addEventListener("keydown",d=>{const g=d.target,m=g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||(g==null?void 0:g.isContentEditable)===!0,y=d.isComposing||d.keyCode===229;if(!(m||y))switch(d.code){case"Escape":this.selectionSet.clear();break;case"Delete":case"Backspace":this.editor.isActive||S.instance.sendStringToExecute("erase");break}}),u.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(d=>{const g=d.layout.blockTableRecordId,m=!this._initializedLayouts.has(g);this._initializedLayouts.add(g),Promise.resolve().then(()=>Ch).then(({clearAllMeasurements:y})=>y(this)),this.activeLayoutBtrId=g,this.createLayoutViewIfNeeded(g),this.loadLayoutEntitiesIfNeeded(g),this._isDirty=!0,m&&this.applyInitialZoom(g,d.layout)}),this._css2dRenderer=new os.CSS2DRenderer,this._css2dRenderer.setSize(this.width,this.height),this._css2dRenderer.domElement.style.position="absolute",this._css2dRenderer.domElement.style.top="0px",this._css2dRenderer.domElement.style.left="0px",this._css2dRenderer.domElement.style.pointerEvents="none",this._css2dRenderer.domElement.style.zIndex="99998",i.appendChild(this._css2dRenderer.domElement),this._missedImages=new Map,this._layoutViewManager=new Kh,this.initialize(),this.onWindowResize(),this._isDirty=!0,this.startAnimationLoop(),this._numOfEntitiesToProcess=0}getPointerSelectionAction(e){return Fs(e)}initialize(){this.setCursor(be.Crosshair)}get mode(){const e=this.activeLayoutView;return e?e.mode:se.SELECTION}set mode(e){this.activeLayoutView.mode=e}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._renderer.changeForeground(e==0?16777215:0),this._renderer.currentBackgroundColor=e,this.editor.setCursorColor(e==0?"white":"black"),Rs(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}get cadScene(){return this._scene}get internalScene(){return this._scene.internalScene}get htmlTransientManager(){return this._scene.htmlTransientManager}get internalCamera(){var e;return(e=this.activeLayoutView)==null?void 0:e.internalCamera}set ltscale(e){this._renderer.ltscale=e}set celtscale(e){this._renderer.celtscale=e}screenToWorld(e){const t=this.activeLayoutView;return t?t.screenToWorld(e):new u.AcGePoint2d(e)}worldToScreen(e){const t=this.activeLayoutView;return t?t.worldToScreen(e):new u.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)}zoomToFitDrawing(e=0){new mn(()=>this._numOfEntitiesToProcess<=0,()=>{if(this._scene.box){const i=ki.threeBox3dToGeBox2d(this._scene.box);this.zoomTo(i),this._isDirty=!0}},300,e).start()}zoomToFitLayer(e){const t=this._scene.activeLayout;if(t){const i=t.getLayer(e);if(i&&!i.box.isEmpty()){const n=ki.threeBox3dToGeBox2d(i.box);return this.zoomTo(n),this._isDirty=!0,!0}}return!1}flyTo(e,t){this.activeLayoutView.flyTo(e,t),this._isDirty=!0}async openPickedMTextEditor(e){const t=this.viewportToCanvas({x:e.clientX,y:e.clientY}),i=this.screenToWorld(t),n=this.pick(i,void 0,!0);if(!n.length)return;const s=S.instance.curDocument.database.tables.blockTable.getEntityById(n[0].id);s instanceof u.AcDbMText&&(e.preventDefault(),await this.editMTextEntity(s))}async editMTextEntity(e){e.lineSpacingFactor!==Re.defaultLineSpacingFactor&&(e.lineSpacingFactor=Re.defaultLineSpacingFactor,e.triggerModifiedEvent()),this._isDirty=!0;const t=new Re;let i=!1;try{const n=await t.open({view:this,location:e.location,width:this.resolveMTextEditorWidth(e),textHeight:this.resolveMTextEditorTextHeight(e),initialText:e.contents,initialAttachmentPoint:e.attachmentPoint,toolbarFontFamilies:this.getMTextToolbarFontFamilies()});if(!n)return;e.location=n.location,e.contents=n.contents,e.width=n.width,e.height=n.height,e.lineSpacingFactor=n.lineSpacingFactor,e.attachmentPoint=n.attachmentPoint,e.triggerModifiedEvent(),i=!0}finally{i||(this.updateEntity(e),this._isDirty=!0)}}resolveMTextEditorWidth(e){const t=Number(e.width);return Number.isFinite(t)&&t>0?t:1e-4}resolveMTextEditorTextHeight(e){const t=Number(e.height);return Number.isFinite(t)&&t>0?t:this.pixelsToWorldY(24)}pixelsToWorldY(e){const t=this.screenToWorld({x:0,y:0}),i=this.screenToWorld({x:0,y:e});return Math.max(Math.abs(i.y-t.y),1e-4)}getMTextToolbarFontFamilies(){return Array.from(new Set(S.instance.avaiableFonts.flatMap(e=>e.name).map(e=>e.trim()).filter(e=>e.length>0)))}pick(e,t,i){e==null&&(e=this.curPos);const n=[],s=this._scene.activeLayout;if(!s)return n;const r=this.activeLayoutView,o=t??this.selectionBoxSize,c=r.pointToBox(e,o),l=Math.max(c.size.width/2,c.size.height/2),h=r.layoutBtrId!==this._scene.modelSpaceBtrId,d=(c.size.width+c.size.height)/2,g=[],m=new Set;if(h)for(const b of r.viewportViews)b.containsPaperPoint(e)&&!b.isNearPaperBorder(e,d)&&(g.push(b),m.add(b.viewport.id));const y=this._scene.search(c),w=r.resetRaycaster(e,l);y.forEach(b=>{m.has(b.id)||s.isIntersectWith(b.id,w)&&n.push(b)}),g.length>0&&this.pickThroughViewports(e,c,g,n);const C=Uh(n,e);return i?C.slice(0,1):C}pickThroughViewports(e,t,i,n){const s=this._scene.modelSpaceLayout;if(!s)return;const r=(t.size.width+t.size.height)/4;for(const o of i){const c=o.paperPointToModel(e),l=r*o.paperToModelScale;if(l<=0)continue;const h=new u.AcGeBox2d().setFromPoints([new u.AcGePoint2d(c.x-l,c.y-l),new u.AcGePoint2d(c.x+l,c.y+l)]),d=o.resetRaycaster(c,l);s.search(h).forEach(m=>{s.isIntersectWith(m.id,d)&&n.push(m)})}}search(e){return this._scene.search(e)}select(e){const t=[];this.pick(e).forEach(n=>t.push(n.id)),t.length>0&&this.selectionSet.add(t)}selectByBox(e){this.selectByBoxWithMode(e,"crossing","add")}addLayer(e){const t=this._scene.addLayer({name:e.name,isFrozen:e.isFrozen,isOff:e.isOff,color:e.color}),i={layer:e.name,color:e.color.clone(),rgbColor:e.color.RGB,lineType:e.lineStyle,lineWeight:e.lineWeight,transparency:e.transparency},n=this._renderer.updateLayerMaterial(e.name,i);t.forEach(s=>{for(const r in n){const o=n[r];s.updateMaterial(Number(r),o)}}),this._isDirty=!0}updateLayer(e,t){const i=this._scene.updateLayer({name:e.name,isFrozen:e.isFrozen,isOff:e.isOff,color:e.color}),n={};t.color&&(n.color=t.color.clone(),n.rgbColor=t.color.RGB),t.lineStyle&&(n.lineType=e.lineStyle),t.lineWeight!==void 0&&(n.lineWeight=t.lineWeight),t.transparency!==void 0&&(n.transparency=t.transparency),n.layer=e.name;const s=this._renderer.updateLayerMaterial(e.name,n);i.forEach(r=>{for(const o in s){const c=s[o];r.updateMaterial(Number(o),c)}}),this._isDirty=!0}addTransientEntity(e){const t=Array.isArray(e)?e:[e];for(let i=0;i<t.length;++i){const n=t[i],s=this.drawEntity(n,!0);s&&(s.objectId=n.objectId,this._scene.addTransientEntity(s),this._isDirty=!0)}}removeTransientEntity(e){this._scene.removeTransientEntity(e),this._isDirty=!0}addEntity(e){const t=Array.isArray(e)?e:[e];this._numOfEntitiesToProcess+=t.length,setTimeout(async()=>{await this.batchConvert(t)}),this._isDirty=!0}removeEntity(e){(Array.isArray(e)?e:[e]).forEach(i=>this._scene.removeEntity(i.objectId)),this._isDirty=!0}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.worldDraw(this._renderer);s&&(s.objectId=n.objectId,s.ownerId=n.ownerId,s.layerName=n.layer,s.visible=n.visibility,this._scene.updateEntity(s))}this._isDirty=!0,setTimeout(()=>{this._isDirty=!0},100)}addLayout(e){this._scene.addEmptyLayout(e.blockTableRecordId),this.createLayoutViewIfNeeded(e.blockTableRecordId),this._isDirty=!0}markLayoutAsInitialized(e){this._initializedLayouts.add(e)}applyInitialZoom(e,t){new mn(()=>this._numOfEntitiesToProcess<=0,()=>{const n=t.limits,s=this._layoutViewManager.getAt(e),r=s==null?void 0:s.viewportsBoundingBox,o=!n||n.isEmpty()?!1:r?n.min.x<=r.min.x&&n.min.y<=r.min.y&&n.max.x>=r.max.x&&n.max.y>=r.max.y:!0;if(n&&!n.isEmpty()&&o)this.zoomTo(n);else if(r)this.zoomTo(r);else if(t.extents&&!t.extents.isEmpty()){const c=t.extents;this.zoomTo(new u.AcGeBox2d({x:c.min.x,y:c.min.y},{x:c.max.x,y:c.max.y}))}else this._scene.box&&this.zoomTo(ki.threeBox3dToGeBox2d(this._scene.box));this._isDirty=!0},300,0).start()}clear(){this._scene.clear(),this._isDirty=!0,this._missedImages.clear(),this._renderer.dispose()}highlight(e){this._isDirty=this._scene.select(e)}unhighlight(e){this._isDirty=this._scene.unselect(e)}stopAnimationLoop(){this._rafId!=null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}onHover(e){this._isDirty=this._scene.hover([e])}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){return new nu}createStats(e){const t=new Pa;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._css2dRenderer.setSize(this.width,this.height),this._layoutViewManager.resize(this.width,this.height),this._isDirty=!0}startAnimationLoop(){this._rafId==null&&(this._rafId=requestAnimationFrame(this.animate))}createLayoutViewIfNeeded(e){let t=this._layoutViewManager.getAt(e);return t==null&&(t=new $h(this._renderer,e,this.width,this.height),t.events.viewChanged.addEventListener(()=>{this._isDirty=!0,this.events.viewChanged.dispatch(),this.clearHover()}),this._layoutViewManager.add(t)),t}loadLayoutEntitiesIfNeeded(e){try{const i=S.instance.curDocument.database.tables.blockTable.getIdAt(e);if(!i)return;const n=this._scene.layouts.get(e);if(n&&n.isLoaded||this._loadingLayouts.has(e))return;const s=this._layoutViewManager.getAt(e);if(n&&n.entityCount>0&&s&&s.viewportCount===0&&this.ensureViewportViews(i,s),n&&n.entityCount>0){n.isLoaded=!0;return}n||this._scene.addEmptyLayout(e);const r=[],o=i.newIterator();for(const c of o)r.push(c);if(r.length===0){const c=this._scene.layouts.get(e);c&&(c.isLoaded=!0);return}this._loadingLayouts.add(e),this._numOfEntitiesToProcess+=r.length,setTimeout(async()=>{try{await this.batchConvert(r);const c=this._scene.layouts.get(e);c&&(c.isLoaded=!0)}finally{this._loadingLayouts.delete(e)}})}catch(t){u.log.error("[AcTrView2d] Error loading layout entities:",t)}}toggleStatsVisibility(e,t){t?e.dom.style.display="block":e.dom.style.display="none"}drawEntity(e,t){return e.worldDraw(this._renderer,t)}ensureViewportViews(e,t){const i=e.newIterator();for(const n of i){if(!(n instanceof u.AcDbViewport)||Ge.isDefaultPaperSpaceViewport(n))continue;const s=new Ge(t,n.toGiViewport(),this._renderer);t.addViewport(s)}}async batchConvert(e){for(let t=0;t<e.length;++t){const i=e[t];try{if(i instanceof u.AcDbViewport&&Ge.isDefaultPaperSpaceViewport(i))continue;const n=this.drawEntity(i,!0);if(!n)continue;if(n.objectId=i.objectId,n.ownerId=i.ownerId,n.layerName=i.layer,n.visible=i.visibility,n instanceof He&&n.isOnTheSameLayer&&this.remapInheritedLayerObjects(n.children,"0",n.layerName),n instanceof He&&!n.isOnTheSameLayer)this.handleGroup(n);else{const s=!(i instanceof u.AcDbRay||i instanceof u.AcDbXline);await n.draw(),this._scene.addEntity(n,s),n.dispose(),this._isDirty=!0}if(i instanceof u.AcDbViewport){if(!Ge.isDefaultPaperSpaceViewport(i)){const s=this._layoutViewManager.getAt(i.ownerId);if(s){const r=new Ge(s,i.toGiViewport(),this._renderer);s.addViewport(r)}}}else if(i instanceof u.AcDbRasterImage){const s=i.imageFileName;s&&this._missedImages.set(i.objectId,s)}}catch(n){u.log.error(`[AcTrView2d] Failed to convert entity ${i.objectId} (${i.type}):`,n)}finally{this.decreaseNumOfEntitiesToProcess()}}}handleGroup(e){const t=e.children,i=new Map;t.forEach(l=>{var d;const h=l.userData.layerName;i.has(h)||i.set(h,[]),(d=i.get(h))==null||d.push(l)}),e.children=[];for(const l of t)l.parent=null;const n=e.styleManager,s=e.objectId,r=e.layerName,o=e.box,c=e.boxes.map(l=>({...l}));i.forEach((l,h)=>{const d=h==="0"?r:h;this.remapInheritedLayerObjects(l,h,d);const g=new re(n);g.applyMatrix4(e.matrix),g.objectId=s,g.ownerId=e.ownerId,g.layerName=d,g.box=o;const m=g.userData;m.spatialIndexChildBoxes=c;for(let y=0;y<l.length;y++)g.add(l[y]);this._scene.addEntity(g,!0),g.dispose()}),e.dispose(),this._isDirty=!0}remapInheritedLayerObjects(e,t,i){if(t===i)return;const n=this._renderer,s=this.getEffectiveLayerTraits(i);for(const r of e)r.traverse(o=>{if(o.userData.layerName===t&&(o.userData.layerName=i),!("material"in o))return;const c=o.material;if(Array.isArray(c)){const h=c;o.material=h.map(d=>n.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(d,t),i,s));return}const l=n.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(c,t),i,s);o.material=l,o.userData.styleMaterialId=l.id})}promoteLayerZeroByLayerColor(e,t){const i=Ie(e),n=tr(i)&&i.isByLayerColor!==!0;return t==="0"&&n&&bn(e,{isByLayerColor:!0}),e}getEffectiveLayerTraits(e){const t=S.instance.curDocument.database.tables.layerTable.getAt(e);if(t)return{layer:t.name,color:t.color.clone(),rgbColor:t.color.RGB,lineType:t.lineStyle,lineWeight:t.lineWeight,transparency:t.transparency}}decreaseNumOfEntitiesToProcess(){this._numOfEntitiesToProcess--,this._numOfEntitiesToProcess<0&&(this._numOfEntitiesToProcess=0,u.log.warn("Something wrong! The number of entities to process should not be less than 0."))}}class su{constructor(){this._loader=new Mc}get baseUrl(){return this._loader.baseUrl}set baseUrl(e){this._loader.baseUrl=e}get avaiableFonts(){return this._loader.avaiableFonts}async getAvaiableFonts(){return await this._loader.getAvailableFonts()}async load(e){const t=await this._loader.load(e),i=[],n=[];t.forEach(s=>{s.status==="NotFound"?i.push(s.fontName):s.status==="FailedToLoad"&&n.push({fontName:s.fontName,url:s.url})}),i.length>0&&J.emit("fonts-not-found",{fonts:i}),n.length>0&&J.emit("fonts-not-loaded",{fonts:n})}}const Oe=class Oe{constructor(e={}){this.options={size:e.size??"48px",borderWidth:e.borderWidth??"5px",color:e.color??"var(--ml-ui-accent, #0b84ff)",host:e.host??document.body,overlay:e.overlay??!0,overlayColor:e.overlayColor??"var(--ml-ui-overlay, rgba(0,0,0,0.5))",message:e.message??""},Oe.stylesInjected||this.injectStyles(),this.createDom()}show(){return this.root.style.display="flex",this}hide(){return this.root.style.display="none",this}setMessage(e=""){return this.messageEl.textContent=e,this.messageEl.style.display=e?"block":"none",this}destroy(){var e;(e=this.root)!=null&&e.parentNode&&this.root.parentNode.removeChild(this.root)}createDom(){const e=this.options.host;getComputedStyle(e).position==="static"&&(e.style.position="relative");const i=document.createElement("div");i.className="ml-ccl-overlay",i.style.display="flex",i.style.background=this.options.overlay?this.options.overlayColor:"transparent";const n=document.createElement("div");n.className="ml-ccl-spinner",n.style.width=this.options.size,n.style.height=this.options.size,n.style.borderWidth=this.options.borderWidth,n.style.borderTopColor=this.options.color;const s=document.createElement("div");s.className="ml-ccl-message",s.textContent=this.options.message,s.style.display=this.options.message?"block":"none";const r=document.createElement("div");r.className="ml-ccl-wrapper",r.appendChild(n),r.appendChild(s),i.appendChild(r),e.appendChild(i),this.root=i,this.spinner=n,this.messageEl=s}injectStyles(){if(document.getElementById(Oe.styleId)){Oe.stylesInjected=!0;return}const e=`
|
|
343
|
+
}`;return new y.ShaderMaterial({uniforms:r,vertexShader:a,fragmentShader:c,clipping:!0})}}class Uc extends ot{buildKey(e,t){const i=this.hasByLayerKeyTraits(e),n=this.resolveLineWidth(e.lineWeight),s=this.getMaterialMode(e,t),r=this.buildDrawOrderSuffix(e);return s==="shader"?i?`layer_${s}_${e.layer}_${e.lineType.name}_${e.rgbColor}_${e.lineTypeScale}_${n}${r}`:`entity_${s}_${e.lineType.name}_${e.rgbColor}_${e.lineTypeScale}_${n}${r}`:i?`layer_${s}_${e.layer}_${e.rgbColor}_${n}${r}`:`entity_${s}_${e.rgbColor}_${n}${r}`}isShaderMaterial(e,t){return!!(!t.basicMaterialOnly&&e.lineType.pattern&&e.lineType.pattern.length>0)}getMaterialMode(e,t){return this.isShaderMaterial(e,t)?"shader":t.basicMaterialOnly?"basic":"fat"}createMaterialImpl(e,t={}){let i;const n=this.getLineTypeScales(),s=n.ltscale*n.celtscale*e.lineTypeScale;if(this.isShaderMaterial(e,t))i=Kc.createLineShaderMaterial(e.lineType.pattern,e.rgbColor,s,this.options.viewportScaleUniform,ot.CameraZoomUniform);else if(t.basicMaterialOnly||e.lineWeight<0)i=new y.LineBasicMaterial({color:e.rgbColor});else{const r=new xt.LineMaterial({color:e.rgbColor,linewidth:this.resolveLineWidth(e.lineWeight)});r.resolution.copy(this.options.resolution),i=r}return i}hasByLayerKeyTraits(e){return super.hasByLayerKeyTraits(e)||e.lineWeight===u.AcGiLineWeight.ByLayer}resolveLineWidth(e){return e<0?1:Math.max(1,e/40)}updateResolution(){const e=this.options.resolution;Object.values(this.cache).forEach(t=>{t instanceof xt.LineMaterial&&t.resolution.copy(e)})}getLineTypeScales(){return{ltscale:this.options.ltscale||1,celtscale:this.options.celtscale||1}}}class $c extends ot{buildKey(e,t){const i=t.size??1,n=this.buildDrawOrderSuffix(e);return this.hasByLayerKeyTraits(e)?`layer_${e.layer}_${e.rgbColor}_${i}${n}`:`entity_${e.rgbColor}_${i}${n}`}hasByLayerKeyTraits(e){return e.color.isByLayer}createMaterialImpl(e,t={}){return new y.PointsMaterial({color:e.rgbColor,size:t.size})}}class Wc{constructor(){this.options={ltscale:1,celtscale:1,viewportScaleUniform:1,maxFragmentUniforms:1024,resolution:new y.Vector2(1,1),showLineWeight:!1,currentBackgroundColor:qe},this.unsupportedTextStyles={},this.pointMgr=new $c(this.options),this.lineMgr=new Uc(this.options),this.fillMgr=new Gc(this.options)}getPointsMaterial(e,t=2){return this.pointMgr.getMaterial(e,{size:t})}getLineMaterial(e,t){const i=!!(e.lineType.pattern&&e.lineType.pattern.length>0),n=!this.options.showLineWeight&&!i;return this.lineMgr.getMaterial(e,{basicMaterialOnly:t||n})}get showLineWeight(){return this.options.showLineWeight}set showLineWeight(e){this.options.showLineWeight=e}get currentBackgroundColor(){return this.options.currentBackgroundColor}set currentBackgroundColor(e){this.options.currentBackgroundColor=e,this.changeBackground(e),this.repaintForegroundMaterials(xn(e))}getFillMaterial(e,t=$s,i){return this.fillMgr.getMaterial(e,{rebaseOffset:t,gradientBounds:i})}getMTextFillMaterial(e,t=$s){return this.fillMgr.getMaterial(e,{rebaseOffset:t})}getBackSideVariant(e){return this.fillMgr.getBackSideVariant(e)}updateLayerMaterial(e,t){return{...this.lineMgr.updateLayerMaterial(e,t),...this.pointMgr.updateLayerMaterial(e,t),...this.fillMgr.updateLayerMaterial(e,t)}}getLayerBoundMaterial(e,t,i){return this.lineMgr.getLayerBoundMaterial(e,t,i)||this.pointMgr.getLayerBoundMaterial(e,t,i)||this.fillMgr.getLayerBoundMaterial(e,t,i)||e}repaintForegroundMaterials(e){this.lineMgr.changeForeground(e),this.pointMgr.changeForeground(e),this.fillMgr.changeForeground(e)}changeBackground(e){this.lineMgr.changeBackground(e),this.pointMgr.changeBackground(e),this.fillMgr.changeBackground(e)}dispose(){this.lineMgr.dispose(),this.pointMgr.dispose(),this.fillMgr.dispose()}updateLineResolution(e,t){this.options.resolution.set(e,t),this.lineMgr.updateResolution()}}const $s=new y.Vector2(0,0);class Hc{constructor(e){this.events={fontNotFound:new u.AcCmEventManager},this._renderer=e,this._styleManager=new Wc;const t=e.getSize(new y.Vector2);this._styleManager.updateLineResolution(t.x,t.y),Xe.getInstance().overrideStyleManager(this._styleManager),B.FontManager.instance.events.fontNotFound.addEventListener(i=>{this.events.fontNotFound.dispatch(i)}),this._subEntityTraits=dn.createDefaultTraits()}get subEntityTraits(){return this._subEntityTraits}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),this._styleManager.updateLineResolution(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){return this.updateCameraZoomUniform(t.zoom),this._renderer.render(e,t.internalCamera),!1}changeBackground(e){this._styleManager.changeBackground(e)}get currentBackgroundColor(){return this._styleManager.currentBackgroundColor}set currentBackgroundColor(e){this._styleManager.currentBackgroundColor=e}setClearColor(e,t){this._renderer.setClearColor(e,t)}getClearColor(){const e=new y.Color;return this._renderer.getClearColor(e),e.getHex()}set clearAlpha(e){this._renderer.setClearAlpha(e)}get clearAlpha(){return this._renderer.getClearAlpha()}get internalRenderer(){return this._renderer}setFontMapping(e){B.FontManager.instance.setFontMapping(e)}set ltscale(e){this._styleManager.options.ltscale=e}set celtscale(e){this._styleManager.options.celtscale=e}get missedFonts(){return B.FontManager.instance.missedFonts}get showLineWeight(){return this._styleManager.showLineWeight}set showLineWeight(e){this._styleManager.showLineWeight=e}updateLayerMaterial(e,t){return this._styleManager.updateLayerMaterial(e,t)}getLayerBoundMaterial(e,t,i){return this._styleManager.getLayerBoundMaterial(e,t,i)}createObject(){return new Os(this._styleManager)}createEntity(){return new Y(this._styleManager)}group(e){return new Ye(e,this._styleManager)}point(e,t){return new Dc(e,this._subEntityTraits,t,this._styleManager)}circularArc(e){return this.linePoints(e.getPoints(100))}ellipticalArc(e){return this.linePoints(e.getPoints(100))}lines(e){return this.linePoints(e)}lineSegments(e,t,i){return new Ic(e,t,i,this._subEntityTraits,this._styleManager)}area(e){return new Oc(e,this._subEntityTraits,this._styleManager)}mtext(e,t,i){return new kc(e,this._subEntityTraits,t,this._styleManager,i)}image(e,t){return new _c(e,t,this._styleManager)}dispose(){this._styleManager.dispose(),B.FontManager.instance.missedFonts={}}linePoints(e){return new Lc(e,this._subEntityTraits,this._styleManager)}updateCameraZoomUniform(e){ot.CameraZoomUniform.value=e}}class Yc{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()}screenToWorld(e,t,i){const n=new y.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 u.AcGePoint2d(s.x,s.y)}worldToScreen(e,t,i){const n=new y.Vector3(e.x,e.y,0).project(this._camera);return new u.AcGePoint2d((n.x+1)/2*t,(-n.y+1)/2*i)}wcs2Ndc(e,t,i){const n=this.worldToScreen(e,t,i);return this.cwcs2Ndc(n,t,i)}cwcs2Ndc(e,t,i){return new u.AcGePoint2d(e.x/t*2-1,-(e.y/i)*2+1)}}class Ws{constructor(e,t,i){this._frustum=400,this.events={viewChanged:new u.AcCmEventManager},this._renderer=e,this._width=t,this._height=i;const n=this.createCamera();this._camera=new Yc(n),this._cameraControls=this.createCameraControls(),this._cameraControls.addEventListener("change",()=>{this.events.viewChanged.dispatch({view:this})}),this._raycaster=new y.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.screenToWorld({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()}screenToWorld(e){return this._camera.screenToWorld(e,this._width,this._height)}worldToScreen(e){return this._camera.worldToScreen(e,this._width,this._height)}pointToBox(e,t){const i=this.worldToScreen(e),n=this.screenToWorld({x:i.x+t,y:i.y+t}),s=this.screenToWorld({x:i.x-t,y:i.y-t});return new u.AcGeBox2d().setFromPoints([n,s])}resetRaycaster(e,t){const i=this._camera.wcs2Ndc(e,this._width,this._height);return this._raycaster.setFromCamera(new y.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 u.AcGeVector2d;e.getSize(i);const n=new u.AcGeVector2d;e.getCenter(n);const s=i.x*t,r=i.y*t,a=this._width/s,c=this._height/r,l=Math.min(a,c);this.flyTo(n,l),this.updateCameraFrustum()}flyTo(e,t){const i=new y.Vector3(e.x,e.y,0);this._camera.position.set(e.x,e.y,this._camera.position.z),this._camera.lookAt(i),this._camera.setRotationFromEuler(new y.Euler(0,0,0)),this._cameraControls.target=i,t!=null&&(this._camera.zoom=t),this._camera.updateProjectionMatrix()}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 y.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 Ua.OrbitControls(this._camera.internalCamera,this._renderer.domElement);return e.enableDamping=!1,e.autoRotate=!1,e.enableRotate=!1,e.zoomSpeed=5,e.zoomToCursor=!0,e.mouseButtons={MIDDLE:y.MOUSE.PAN},e.touches={ONE:y.TOUCH.PAN,TWO:y.TOUCH.DOLLY_PAN},e.update(),e}}class Fe extends Ws{static calculateViewportWindowBox(e,t){const i=t.box,n=new u.AcGeBox2d;return n.expandByPoint(e.worldToScreen(i.min)),n.expandByPoint(e.worldToScreen(i.max)),n}static isDefaultPaperSpaceViewport(e){if(e.number===1)return!0;const t=1e-6;return Math.abs(e.centerPoint.x-e.viewCenter.x)<t&&Math.abs(e.centerPoint.y-e.viewCenter.y)<t}constructor(e,t,i){const n=Fe.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,1)}containsPaperPoint(e){const t=this._viewport.box;return e.x>=t.min.x&&e.x<=t.max.x&&e.y>=t.min.y&&e.y<=t.max.y}isNearPaperBorder(e,t){if(!this.containsPaperPoint(e))return!1;const i=this._viewport.box,n=Math.abs(e.x-i.min.x),s=Math.abs(e.x-i.max.x),r=Math.abs(e.y-i.min.y),a=Math.abs(e.y-i.max.y);return Math.min(n,s,r,a)<=t}paperPointToModel(e){const t=this._viewport.box,i=this._viewport.viewBox,n=t.max.x-t.min.x,s=t.max.y-t.min.y;if(n<=0||s<=0)return new u.AcGePoint2d((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2);const r=(e.x-t.min.x)/n,a=(e.y-t.min.y)/s;return new u.AcGePoint2d(i.min.x+r*(i.max.x-i.min.x),i.min.y+a*(i.max.y-i.min.y))}get paperToModelScale(){const e=this._viewport.box,t=this._viewport.viewBox,i=e.max.x-e.min.x;return i<=0?1:(t.max.x-t.min.x)/i}render(e){const t=Fe.calculateViewportWindowBox(this._parentView,this._viewport);if(!t.isEmpty()){const i=t.size.width,n=t.size.height;(i!==this._width||n!==this._height)&&(this._width=i,this._height=n,this._frustum=n/2,this.zoomTo(this._viewport.viewBox,1));const s=this._parentView.height-t.min.y-n;this._renderer.setViewport(t.min.x,s,i,n),this._renderer.internalRenderer.setScissor(t.min.x,s,i,n),this._renderer.internalRenderer.setScissorTest(!0),this._renderer.render(e,this._camera),this._renderer.internalRenderer.setScissorTest(!1)}}}function Xc(o){return vn(o)}function qc(o){if(typeof o=="number")return o===1;if(typeof o=="boolean")return o;const e=String(o).toLowerCase();return e==="light"||e==="1"||e==="true"}function Hs(o){return o.currentSpaceId===o.tables.blockTable.modelSpace.objectId}function Sn(o){return o?u.AcDbSystemVariables.MODELBKCOLOR:u.AcDbSystemVariables.PAPERBKCOLOR}function Ys(o,e){const t=o==null?void 0:o.RGB;return t??(e?qe:zs)}function gi(o,e){const t=Sn(e),i=u.AcDbSysVarManager.instance().getVar(t,o);return Ys(i,e)}function Xs(o){const e=o.RGB??qe,t=new u.AcCmColor(u.AcCmColorMethod.ByColor);return Lt(e)?t.setRGB(0,0,0):t.setRGB(255,255,255),t}function pi(o){return Lt(o)?"black":"white"}var be=(o=>(o[o.NoSpecialCursor=-1]="NoSpecialCursor",o[o.Crosshair=0]="Crosshair",o[o.RectCursor=1]="RectCursor",o[o.RubberBand=2]="RubberBand",o[o.NotRotated=3]="NotRotated",o[o.TargetBox=4]="TargetBox",o[o.RotatedCrosshair=5]="RotatedCrosshair",o[o.CrosshairNoRotate=6]="CrosshairNoRotate",o[o.Invisible=7]="Invisible",o[o.EntitySelect=8]="EntitySelect",o[o.Parallelogram=9]="Parallelogram",o[o.EntitySelectNoPersp=10]="EntitySelectNoPersp",o[o.PkfirstOrGrips=11]="PkfirstOrGrips",o[o.CrosshairDashed=12]="CrosshairDashed",o[o.Grab=13]="Grab",o))(be||{});class qs{constructor(e){this._backgroundColor=qe,this._totalLength=20,this._view=e,this._cursorMap=new Map,this.setCursorColor(pi(this._backgroundColor)),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(t=>{if(t.name===u.AcDbSystemVariables.PICKBOX.toLowerCase()){let i=t.newVal;i=i>=0?i:0,this._cursorMap.set(0,this.createRectCrossIcon(i,this._totalLength-i,pi(this._backgroundColor))),this.setCursor(this._currentCursor)}}),this.setCursor(0)}get currentCursor(){return this._currentCursor}setCursor(e){const t=this._view.canvas;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)}this._currentCursor=e}syncBackgroundColor(e){this._backgroundColor=e,this.setCursorColor(pi(e))}setCursorColor(e){const i=this.createRectCrossIcon(10,this._totalLength-10,e);this._cursorMap.set(0,i),this._currentCursor===0&&(this._view.canvas.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=`
|
|
344
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="${s}" height="${s}" viewBox="0 0 ${s} ${s}">
|
|
345
|
+
<rect x="${t}" y="${t}" width="${e}" height="${e}" fill="none" stroke="${i}" />
|
|
346
|
+
<line x1="${n+t}" y1="0" x2="${n+t}" y2="${t}" stroke="${i}" />
|
|
347
|
+
<line x1="${e+t}" y1="${n+t}" x2="${e+2*t}" y2="${n+t}" stroke="${i}" />
|
|
348
|
+
<line x1="${n+t}" y1="${e+t}" x2="${n+t}" y2="${e+2*t}" stroke="${i}" />
|
|
349
|
+
<line x1="0" y1="${n+t}" x2="${t}" y2="${n+t}" stroke="${i}" />
|
|
350
|
+
</svg>
|
|
351
|
+
`;return this.encodeSvgToCursor(r,n+t,n+t)}}function Zs(o){const e=o??u.acdbHostApplicationServices().workingDatabase,t=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.ORTHOMODE,e);return Number(t)!==0}function Js(o,e){const t=o.x-e.x,i=o.y-e.y;return Math.abs(t)>=Math.abs(i)?{x:o.x,y:e.y}:{x:e.x,y:o.y}}const at=2,Qs=4;function Tt(o){return o??u.acdbHostApplicationServices().workingDatabase}function er(o,e,t){const i=u.AcDbSysVarManager.instance().getVar(o,e),n=Number(i);return Number.isFinite(n)?n:t}function Zc(o,e){const t=u.AcDbSysVarManager.instance().getVar(o,e);return t==null?"":String(t)}function mi(o){const e=Tt(o);return er(u.AcDbSystemVariables.POLARMODE,e,0)}function tr(o){const e=Tt(o);return er(u.AcDbSystemVariables.POLARANG,e,90)}function ir(o){const e=Tt(o);return Zc(u.AcDbSystemVariables.POLARADDANG,e)}function nr(o){return(mi(o)&at)!==0}function Jc(o,e,t){let i=o-e;return t===1&&(i=-i),u.AcGeMathUtil.normalizeAngle(i)}function Qc(o,e,t){let i=o;return t===1&&(i=-i),u.AcGeMathUtil.normalizeAngle(i+e)}function el(o){if(!o.trim())return[];const e=[];for(const t of o.split(";")){const i=t.trim();if(!i)continue;const n=Number(i);if(Number.isFinite(n)&&(e.push((n%360+360)%360),e.length>=10))break}return e}function tl(o,e){const t=mi(o),i=(t&at)!==0,n=(t&Qs)!==0,s=new Set;if(e.includeOrtho)for(const r of[0,90,180,270])s.add(r);if(i){const r=tr(o);if(r>0){const a=Math.max(1,Math.round(360/r));for(let c=0;c<a;c++)s.add((c*r%360+360)%360)}if(n)for(const a of el(ir(o)))s.add(a)}return[...s].map(u.AcGeMathUtil.degToRad)}function sr(o,e){const t=Math.abs(u.AcGeMathUtil.normalizeAngle(o-e));return Math.min(t,Math.PI*2-t)}function il(o,e){let t=e[0],i=sr(o,t);for(let n=1;n<e.length;n++){const s=e[n],r=sr(o,s);r<i&&(i=r,t=s)}return t}function rr(o,e,t){const i=Tt(t),n=Zs(i),s=nr(i);if(!n&&!s)return o;if(n&&!s)return Js(o,e);const r=o.x-e.x,a=o.y-e.y,c=Math.hypot(r,a);if(c<1e-10)return o;const l=Math.atan2(a,r),h=Jc(l,i.angbase,i.angdir),d=tl(i,{includeOrtho:n});if(d.length===0)return o;const p=il(h,d),m=Qc(p,i.angbase,i.angdir);return{x:e.x+c*Math.cos(m),y:e.y+c*Math.sin(m)}}function nl(o){const e=Tt(o),t=mi(e),i=t&at?t&~at:t|at;return u.AcDbSysVarManager.instance().setVar(u.AcDbSystemVariables.POLARMODE,i,e),i}class fi{constructor(e=[]){this.events={selectionAdded:new u.AcCmEventManager,selectionRemoved:new u.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})}}}class An{constructor(e,t,i,n=!0,s=!1,r=!0){this._displayName=e,this._globalName=t??e,this._localName=i??this._globalName,this._enabled=n,this._isReadOnly=s,this._visible=r}get displayName(){return this._displayName}set displayName(e){this._isReadOnly||(this._displayName=e)}get enabled(){return this._enabled}set enabled(e){this._isReadOnly||(this._enabled=e)}get globalName(){return this._globalName}set globalName(e){this._isReadOnly||(this._globalName=e)}get isReadOnly(){return this._isReadOnly}get localName(){return this._localName}set localName(e){this._isReadOnly||(this._localName=e)}get visible(){return this._visible}set visible(e){this._isReadOnly||(this._visible=e)}get alias(){return this._globalName.replace(/[^A-Z]/g,"")}}class or{constructor(e){if(this._keywords=[],!e)return;const t=e.trim().split(/\s+/),i=[],n=[];let s=!1;for(const a of t){if(a==="_"){s=!0;continue}(s?n:i).push(a)}const r=Math.max(i.length,n.length);for(let a=0;a<r;a++){const c=i[a],l=n[a],h=v=>{if(!v)return;const C=v.indexOf(",");return C>=0?v.substring(0,C):v},d=h(l),p=h(c),m=d!==void 0,f=p!==void 0,w=m?d:"",x=f?p:void 0,b=new An(w||x||"",w,x,!0,!1,!0);this._keywords.push(b)}}add(e,t,i,n=!0,s=!0){let r,a,c;t===void 0?(r=e,a=e,c=e):i===void 0?(r=t,a=e,c=t):(r=e,a=t,c=i);const l=new An(r,a,c,n,!1,s);return this._keywords.push(l),l}clear(){this._keywords=[],this._defaultKeyword=void 0}toArray(){return this._keywords.slice()}get default(){return this._defaultKeyword}set default(e){if(e&&!this._keywords.includes(e))throw new Error("Default keyword must be one of the collection's keywords");this._defaultKeyword=e}getDisplayString(e=!1){return this._keywords.filter(i=>i.visible&&i.enabled).map(i=>(!e&&this._defaultKeyword===i,i.displayName)).join("/")}getPromptFormat(){const e=this._keywords.filter(s=>s.visible).map(s=>s.displayName),t=this._defaultKeyword&&this._defaultKeyword.visible?this._defaultKeyword.displayName:void 0,i=`[${e.join("/")}]`,n=t?` <${t}>`:"";return{visibleKeywords:e,defaultKeyword:t,formattedTail:`${i}${n}:`}}[Symbol.iterator](){let e=0;const t=this._keywords;return{next(){return e<t.length?{done:!1,value:t[e++]}:{done:!0,value:void 0}}}}findByDisplayName(e){return this._keywords.find(t=>t.displayName.toLowerCase()===e.toLowerCase())}findByGlobalName(e){return this._keywords.find(t=>t.globalName.toLowerCase()===e.toLowerCase())}findByName(e){if(!e)return;let t=e.trim();if(!t)return;const i=t.startsWith("_");i&&(t=t.substring(1));const n=t.toLowerCase();return this._keywords.find(s=>s.enabled?s.globalName.toLowerCase()===n?!0:i?!1:!!(s.localName&&s.localName.toLowerCase()===n||s.alias&&s.alias.toLowerCase()===n||s.displayName.toLowerCase()===n):!1)}get count(){return this._keywords.length}}class _e{constructor(e,t){this._message="",this._appendKeywordsToMessage=!0,this._isReadOnly=!1,this._keywords=new or,t!==void 0?this.setMessageAndKeywords(e,t):this._message=e}get jig(){return this._jig}set jig(e){this._isReadOnly||(this._jig=e)}get message(){return this._message}set message(e){this._isReadOnly||(this._message=e)}get appendKeywordsToMessage(){return this._appendKeywordsToMessage}set appendKeywordsToMessage(e){this._isReadOnly||(this._appendKeywordsToMessage=e)}get isReadOnly(){return this._isReadOnly}get keywords(){return this._keywords}getKeywordPromptFormat(){return this._keywords.getPromptFormat()}setMessageAndKeywords(e,t){if(this._isReadOnly)return this;const i=e.match(/^(.*?)\s*\[(.*?)\](.*)?$/);if(i){const[,n,s]=i;if(this._message=n.trim(),s!==void 0){const r=s.split("/").map(a=>a.trim()).filter(a=>a.length>0);this._keywords.clear();for(const a of r){let l=t.split(/\s+/).find(h=>h.toLowerCase()===a.toLowerCase());l||(l=a),this._keywords.add(a,l)}}}return this}}class ve extends _e{constructor(e,t){super(e,t),this._useBasePoint=!0,this._useDashedLine=!0,this._useAngleBase=!1,this._defaultValue=0,this._useDefaultValue=!1,this._allowZero=!0,this._allowNegative=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get baseAngle(){return this._baseAngle??0}set baseAngle(e){this.isReadOnly||(this._baseAngle=e)}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get useAngleBase(){return this._useAngleBase}set useAngleBase(e){this.isReadOnly||(this._useAngleBase=e)}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}get allowZero(){return this._allowZero}set allowZero(e){this.isReadOnly||(this._allowZero=e)}get allowNegative(){return this._allowNegative}set allowNegative(e){this.isReadOnly||(this._allowNegative=e)}}class yi extends _e{constructor(e,t){super(e),this._useBasePoint=!1,this._useDashedLine=!1,this._disableOSnap=!1,this._secondCornerMessage=t}get firstCornerMessage(){return this.message}set firstCornerMessage(e){this.isReadOnly||(this.message=e)}get secondCornerMessage(){return this._secondCornerMessage}set secondCornerMessage(e){this.isReadOnly||(this._secondCornerMessage=e)}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get disableOSnap(){return this._disableOSnap}set disableOSnap(e){this.isReadOnly||(this._disableOSnap=e)}}class ce{constructor(e,t){this.status=e,this.stringResult=t}}class wi extends ce{constructor(e,t,i){super(e,i),this.value=t}}class bi extends _e{constructor(e,t){super(e,t),this._defaultValue=0,this._useDefaultValue=!1,this._allowNone=!1,this._allowArbitraryInput=!1,this._allowNegative=!1,this._allowZero=!0}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowArbitraryInput(){return this._allowArbitraryInput}set allowArbitraryInput(e){this.isReadOnly||(this._allowArbitraryInput=e)}get allowNegative(){return this._allowNegative}set allowNegative(e){this.isReadOnly||(this._allowNegative=e)}get allowZero(){return this._allowZero}set allowZero(e){this.isReadOnly||(this._allowZero=e)}}class ue extends bi{constructor(e){super(e),this._useBasePoint=!1,this._useDashedLine=!0,this._only2d=!0,this.allowNegative=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get only2d(){return this._only2d}set only2d(e){this.isReadOnly||(this._only2d=e)}}class q extends bi{}class Cn extends ce{constructor(e,t){super(e,void 0),this.value=t}}class se extends Cn{constructor(e,t){super(e,t)}}class Le extends _e{constructor(e,t){super(e,t),this._allowNone=!1,this._allowObjectOnLockedLayer=!1,this._rejectMessage="Invalid object selected.",this._allowedClasses=new Set}normalizeClassName(e){const t=e.trim();return t.startsWith("AcDb")?t.slice(4):t}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowObjectOnLockedLayer(){return this._allowObjectOnLockedLayer}set allowObjectOnLockedLayer(e){this.isReadOnly||(this._allowObjectOnLockedLayer=e)}get rejectMessage(){return this._rejectMessage}setRejectMessage(e){return this.isReadOnly||(this._rejectMessage=e),this}addAllowedClass(e){if(!this.isReadOnly){const t=this.normalizeClassName(e);t&&this._allowedClasses.add(t)}return this}removeAllowedClass(e){if(!this.isReadOnly){const t=this.normalizeClassName(e);t&&this._allowedClasses.delete(t)}return this}clearAllowedClasses(){return this.isReadOnly||this._allowedClasses.clear(),this}isClassAllowed(e){const t=this.normalizeClassName(e);return this._allowedClasses.size===0||this._allowedClasses.has(t)}}class vi extends ce{constructor(e,t,i){super(e),this.objectId=t,this.pickedPoint=i}}class Pn extends bi{constructor(e,t,i){super(e),typeof t=="number"&&(this._lowerLimit=Math.floor(t)),typeof i=="number"&&(this._upperLimit=Math.ceil(i))}get lowerLimit(){return this._lowerLimit}set lowerLimit(e){this.isReadOnly||(this._lowerLimit=typeof e=="number"?Math.floor(e):void 0)}get upperLimit(){return this._upperLimit}set upperLimit(e){this.isReadOnly||(this._upperLimit=typeof e=="number"?Math.floor(e):void 0)}}class xi extends Cn{constructor(e,t){super(e,t)}}class X extends _e{constructor(e,t){super(e,t),this._allowNone=!1,this._allowArbitraryInput=!1}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get allowArbitraryInput(){return this._allowArbitraryInput}set allowArbitraryInput(e){this.isReadOnly||(this._allowArbitraryInput=e)}}class D extends _e{constructor(e,t){super(e,t),this._useBasePoint=!1,this._useDashedLine=!1,this._allowNone=!1,this._disableOSnap=!1}get basePoint(){return this._basePoint}set basePoint(e){this.isReadOnly||(e==null?this._basePoint=e:this._basePoint=this._basePoint?this._basePoint.copy(e):new u.AcGePoint3d(e))}get useBasePoint(){return this._useBasePoint}set useBasePoint(e){this.isReadOnly||(this._useBasePoint=e)}get useDashedLine(){return this._useDashedLine}set useDashedLine(e){this.isReadOnly||(this._useDashedLine=e)}get allowNone(){return this._allowNone}set allowNone(e){this.isReadOnly||(this._allowNone=e)}get disableOSnap(){return this._disableOSnap}set disableOSnap(e){this.isReadOnly||(this._disableOSnap=e)}}class Si extends ce{constructor(e,t){super(e,void 0),this.value=t}}class Re extends _e{constructor(e,t){super(e,t),this._singleOnly=!1}get singleOnly(){return this._singleOnly}set singleOnly(e){this._singleOnly=e}}class It extends ce{constructor(e,t,i){super(e,i),this.value=t}}class le extends _e{constructor(e,t){super(e,t),this._allowSpaces=!0,this._allowEmpty=!1,this._defaultValue="",this._useDefaultValue=!1}get allowSpaces(){return this._allowSpaces}set allowSpaces(e){this.isReadOnly||(this._allowSpaces=e)}get allowEmpty(){return this._allowEmpty}set allowEmpty(e){this.isReadOnly||(this._allowEmpty=e)}get maxLength(){return this._maxLength}set maxLength(e){this.isReadOnly||(this._maxLength=e)}get defaultValue(){return this._defaultValue}set defaultValue(e){this.isReadOnly||(this._defaultValue=e)}get useDefaultValue(){return this._useDefaultValue}set useDefaultValue(e){this.isReadOnly||(this._useDefaultValue=e)}}var S=(o=>(o[o.Cancel=-5002]="Cancel",o[o.Error=-5001]="Error",o[o.Keyword=-5005]="Keyword",o[o.Modeless=5027]="Modeless",o[o.None=5e3]="None",o[o.OK=5100]="OK",o[o.Other=5028]="Other",o))(S||{});const ke=class ke{static get messages(){return this._messages}static getLocaleMessage(e){return this._messages[e]}static mergeLocaleMessage(e,t){ar(this._messages[e],t)}static registerMessage(e,t){this.mergeLocaleMessage(e,t)}static setCurrentLocale(e){const t=this._currentLocale;this._currentLocale=e,this.events.localeChanged.dispatch({old:t,new:this._currentLocale})}static get currentLocale(){return this._currentLocale}static t(e,t){const i=this._currentLocale,n=this._messages[i],s=e.split(".");let r=n;for(const a of s){if(!r||typeof r!="object")return(t==null?void 0:t.fallback)??e;r=r[a]}return typeof r=="string"?r:(t==null?void 0:t.fallback)??e}static cmdDescription(e,t){const i=`command.${e}.${t.toLowerCase()}.description`;return this.t(i)}static cmdPrompt(e,t){const i=`command.${e}.${t.toLowerCase()}.prompt`;return this.t(i)}static sysCmdDescription(e){return this.cmdDescription(he.SYSTEMT_COMMAND_GROUP_NAME,e)}static sysCmdPrompt(e){return this.cmdPrompt(he.SYSTEMT_COMMAND_GROUP_NAME,e)}};ke._messages={en:{},zh:{}},ke._currentLocale="en",ke.events={localeChanged:new u.AcCmEventManager},ke.userCmdDescription=e=>ke.cmdDescription(he.DEFAUT_COMMAND_GROUP_NAME,e),ke.userCmdPrompt=e=>ke.cmdPrompt(he.DEFAUT_COMMAND_GROUP_NAME,e);let g=ke;function ar(o,e){for(const t of Object.keys(e)){const i=e[t],n=o[t];cr(n)&&cr(i)?ar(n,i):o[t]=i}}function cr(o){return typeof o=="object"&&o!==null}const sl={ACAD:{"-hatch":{description:"Creates hatch fills through command-line options without the ribbon UI"},"-layer":{description:"Manages layers through command-line options"},angbase:{description:"Sets the base angle 0 direction with respect to the current UCS"},angdir:{description:"Sets whether positive angles are measured clockwise or counterclockwise"},arc:{description:"Creates an arc"},aunits:{description:"Sets the display format for angles"},auprec:{description:"Sets the display precision for angles, used together with AUNITS"},cdxf:{description:"Exports current drawing to DXF"},cpdf:{description:"Exports current drawing to PDF"},cecolor:{description:"Sets the current default color for newly created objects"},celtscale:{description:"Controls the linetype scale factor for newly created objects"},celtype:{description:"Sets the linetype for newly created objects"},celweight:{description:"Sets the default lineweight for newly created objects"},cetranparency:{description:"Sets the transparency for newly created objects"},circle:{description:"Creates one circle by center and radius"},clayer:{description:"Sets the current layer for new objects and editing operations"},cmleaderstyle:{description:"Sets the name of the current multileader style"},cmlscale:{description:"Controls the overall width of a multiline"},cmlstyle:{description:"Sets the name of the current multiline style"},colortheme:{description:"Controls the color theme of the user interface (dark or light)"},copy:{description:"Copies selected entities by cloning them to new positions",prompt:"Select entities"},csvg:{description:"Converts current drawing to SVG"},chtml:{description:"Exports current drawing to a standalone offline HTML file"},dimlinear:{description:"Creates linear dimensions"},dynmode:{description:"Controls Dynamic Input settings at the cursor"},dynprompt:{description:"Controls display of prompts in Dynamic Input tooltips"},ellipse:{description:"Creates an ellipse or elliptical arc by axis endpoints or center"},erase:{description:"Deletes selected entities from the drawing",prompt:"Select entities"},hatch:{description:"Fills an enclosed area or selected objects with a hatch pattern"},ipdf:{description:"Imports vector geometry from a PDF file"},hpang:{description:"Sets the default angle, in radians, for newly created hatch patterns"},hpassoc:{description:"Controls whether newly created hatches are associative"},hpbackgroundcolor:{description:"Sets the default background color for newly created hatch patterns"},hpcolor:{description:"Sets the default color for newly created hatches"},hpdouble:{description:"Controls whether user-defined hatch patterns are doubled"},hpislanddetection:{description:"Controls how islands within newly created hatch boundaries are treated"},hplayer:{description:"Sets the default layer for newly created hatches and fills"},hpname:{description:"Sets the default pattern name for newly created hatches in this session"},hpscale:{description:"Sets the default scale factor for newly created hatch patterns"},hpseparate:{description:"Controls whether one or separate hatch objects are created for multiple boundaries"},hptransparency:{description:"Sets the default transparency for newly created hatches and fills"},insunits:{description:"Specifies drawing units for automatic scaling of inserted blocks, images, or xrefs"},laycur:{description:"Changes the layer property of selected objects to the current layer",prompt:"Select objects to be changed to the current layer"},laydel:{description:"Deletes a layer and all objects on that layer"},layerclose:{description:"Closes the Layer Properties Manager"},layerp:{description:"Undoes the last change or set of changes made to layer settings"},layfrz:{description:"Freezes the layer of selected objects",prompt:"Select object on layer to freeze"},layiso:{description:"Isolates the layers of selected objects",prompt:"Select objects on layers to isolate"},laylck:{description:"Locks the layer of selected objects",prompt:"Select object on layer to lock"},layoff:{description:"Turns off the layer of selected objects",prompt:"Select object on layer to turn off"},layon:{description:"Turns on all layers in the drawing"},laythw:{description:"Thaws all frozen layers in the drawing"},layulk:{description:"Unlocks the layer of selected objects",prompt:"Select object on layer to unlock"},layuniso:{description:"Restores layers hidden or locked by LAYISO"},line:{description:"Draws straight line segments between points"},log:{description:"Logs debug information in console"},lunits:{description:"Sets the display format for coordinates and distances"},luprec:{description:"Sets the display precision for linear units, used together with LUNITS"},lwdisplay:{description:"Controls whether lineweights are displayed in the drawing"},measurearea:{description:"Calculates the area and perimeter of selected objects or points"},measureangle:{description:"Measures the angle between two lines or three points"},measurearc:{description:"Measures the length of an arc segment"},measuredistance:{description:"Measures the distance and delta values between two points"},measurement:{description:"Sets whether the drawing uses English (imperial) or metric units"},measurementcolor:{description:"Sets the color used for measurement overlays"},mline:{description:"Creates multiple parallel lines as one multiline object"},move:{description:"Moves selected entities by a displacement vector",prompt:"Select entities"},offset:{description:"Creates parallel curves, polylines, or circles at a specified distance"},mtext:{description:"Creates one mtext entity"},open:{description:"Opens an existing drawing file"},osmode:{description:"Sets running Object Snap modes using a bitcode value"},pan:{description:"Shifts the view without changing the viewing direction or magnification"},pickbox:{description:"Sets the size (in pixels) of the selection box used to pick objects"},pline:{description:"Creates a polyline by specifying multiple points"},pngout:{description:"Exports to PNG"},point:{description:"Creates points"},polygon:{description:"Creates a regular polygon by center/radius or by one polygon edge"},qnew:{description:"Starts a new drawing"},ray:{description:"Creates a ray that starts at a point and extends to infinity"},rectang:{description:"Creates a rectangle by specifying two opposite corners"},regen:{description:"Redraws the current drawing"},revcloud:{description:"Creates a revision cloud (cloud line) in rectangular shape"},rotate:{description:"Rotates selected entities around a base point",prompt:"Select entities"},select:{description:"Selects entities"},shortcutmenu:{description:"Controls the availability of shortcut menus in the drawing area"},sketch:{description:"Creates a sketch line using polyline that tracks mouse movement"},spline:{description:"Creates a smooth spline curve by specifying control points"},textstyle:{description:"Sets the name of the current text style"},unitmode:{description:"Controls fractional display of coordinates when LUNITS is Architectural or Fractional"},switchbg:{description:"Toggles the drawing area background between white and black"},xline:{description:"Creates a construction line that extends infinitely in both directions"},zoom:{description:"Zooms to display the maximum extents of all entities"}},USER:{}},rl={arc:{startPointOrCenter:"Specify start point of arc or",secondPointOrOptions:"Specify second point of arc or",secondPoint:"Specify second point of arc:",startPoint:"Specify start point of arc:",centerPoint:"Specify center point of arc:",endPoint:"Specify end point of arc:",endPointOrOptions:"Specify end point of arc or",centerPointOrOptions:"Specify center point of arc",includedAngle:"Specify included angle:",chordLength:"Specify chord length:",tangentDirection:"Specify tangent direction for start point of arc:",radius:"Specify radius of arc:",keywords:{center:{display:"Center(C)",local:"Center",global:"Center"},end:{display:"End(E)",local:"End",global:"End"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},chordLength:{display:"chord Length(L)",local:"Chord Length",global:"ChordLength"},direction:{display:"Direction(D)",local:"Direction",global:"Direction"},radius:{display:"Radius(R)",local:"Radius",global:"Radius"}},invalid:{threePoint:"Invalid 3-point arc: points are collinear or cannot define an arc.",center:"Invalid center input: start and end points must lie on the same circle.",angle:"Invalid angle input: included angle must be greater than 0 and less than 360 degrees.",chordLength:"Invalid chord length: value is out of range for the current radius.",direction:"Invalid direction: cannot construct an arc from this tangent direction.",radius:"Invalid radius: the specified radius cannot connect start and end points."}},circle:{center:"Specify the center of circle:",centerOrOptions:"Specify center point of circle or",radius:"Specify the radius of circle:",radiusOrDiameter:"Specify radius of circle or",diameter:"Specify diameter of circle:",twoPointFirst:"Specify first endpoint of circle diameter:",twoPointSecond:"Specify second endpoint of circle diameter:",threePointFirst:"Specify first point on circle:",threePointSecond:"Specify second point on circle:",threePointThird:"Specify third point on circle:",keywords:{threeP:{display:"3P(3P)",local:"3P",global:"3P"},twoP:{display:"2P(2P)",local:"2P",global:"2P"},diameter:{display:"Diameter(D)",local:"Diameter",global:"Diameter"}}},copy:{basePointOrOptions:"Specify base point or",displacementOrArray:"Specify displacement or",secondPointOrArray:"Specify second point or",modePrompt:"Enter copy mode option",arrayItemCount:"Enter the number of items in the array including the original:",arraySecondPointOrFit:"Specify second point or",arrayFitSecondPoint:"Specify second point:",keywords:{displacement:{display:"Displacement(D)",local:"Displacement",global:"Displacement"},mode:{display:"Mode(O)",local:"Mode",global:"Mode"},multiple:{display:"Multiple(M)",local:"Multiple",global:"Multiple"},single:{display:"Single(S)",local:"Single",global:"Single"},array:{display:"Array(A)",local:"Array",global:"Array"},fit:{display:"Fit(F)",local:"Fit",global:"Fit"}}},dimlinear:{xLine1Point:"Specify the first extension line origin:",xLine2Point:"Specify the second extension line origin:",dimLinePoint:"Specify dimension line location:"},ellipse:{axisEndpointOrOptions:"Specify axis endpoint of ellipse or",arcAxisEndpointOrCenter:"Specify axis endpoint of elliptical arc or",center:"Specify center of ellipse:",firstAxisEndpoint:"Specify endpoint of axis:",secondAxisEndpoint:"Specify other endpoint of axis:",otherAxisOrRotation:"Specify distance to other axis or",rotationAngle:"Specify rotation angle around major axis:",arcStartAngle:"Specify start angle of elliptical arc:",arcEndAngle:"Specify end angle of elliptical arc:",keywords:{arc:{display:"Arc(A)",local:"Arc",global:"Arc"},center:{display:"Center(C)",local:"Center",global:"Center"},rotation:{display:"Rotation(R)",local:"Rotation",global:"Rotation"}},invalid:{axis:"Invalid axis input: axis length must be greater than 0.",otherAxis:"Invalid other-axis input: distance must be greater than 0.",rotation:"Invalid rotation input: resulting minor axis must be greater than 0."}},hatch:{prompt:"Select boundary object or",pickPoint:"Specify internal point (or press Enter to finish):",select:"Select objects to hatch:",patternName:"Enter hatch pattern name:",scale:"Specify hatch pattern scale:",angle:"Specify hatch pattern angle:",style:"Enter hatch style",associative:"Specify associativity",invalidBoundary:"Selected objects do not form a closed boundary.",keywords:{pick:{display:"Pick points(P)",local:"Pick points",global:"PickPoints"},select:{display:"Select objects(S)",local:"Select objects",global:"SelectObjects"},cancel:{display:"Cancel(C)",local:"Cancel",global:"Cancel"},pattern:{display:"Pattern(P)",local:"Pattern",global:"Pattern"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},style:{display:"Style(T)",local:"Style",global:"HatchStyle"},associative:{display:"Associative(AS)",local:"Associative",global:"AssociativeMode"},normal:{display:"Normal(N)",local:"Normal",global:"Normal"},outer:{display:"Outer(O)",local:"Outer",global:"Outer"},ignore:{display:"Ignore(I)",local:"Ignore",global:"Ignore"},yes:{display:"Yes(Y)",local:"Yes",global:"Yes"},no:{display:"No(N)",local:"No",global:"No"}}},layer:{main:"Enter option",listSummary:"Layer list was printed to browser console",emptyInput:"No layer name was entered.",newPrompt:"Enter name for new layer(s):",makePrompt:"Enter name of layer to make current:",setPrompt:"Enter name of layer to set current:",onPrompt:"Enter layer name(s) to turn on:",offPrompt:"Enter layer name(s) to turn off:",freezePrompt:"Enter layer name(s) to freeze:",thawPrompt:"Enter layer name(s) to thaw:",lockPrompt:"Enter layer name(s) to lock:",unlockPrompt:"Enter layer name(s) to unlock:",colorLayerPrompt:"Enter layer name(s) to change color:",colorValuePrompt:"Enter color (ACI 1-255, RGB like 255,0,0, or CSS color name):",invalidColor:"Invalid color input.",descriptionLayerPrompt:"Enter layer name to edit description:",descriptionValuePrompt:"Enter new layer description:",created:"Created layer count",alreadyExists:"Layer already exists",notFound:"Layer not found",cannotChangeCurrent:"Cannot turn off or freeze the current layer.",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"Make(M)",local:"Make",global:"Make"},set:{display:"Set(S)",local:"Set",global:"Set"},new:{display:"New(N)",local:"New",global:"New"},on:{display:"On(ON)",local:"On",global:"On"},off:{display:"Off(OF)",local:"Off",global:"Off"},color:{display:"Color(C)",local:"Color",global:"Color"},freeze:{display:"Freeze(F)",local:"Freeze",global:"Freeze"},thaw:{display:"Thaw(T)",local:"Thaw",global:"Thaw"},lock:{display:"Lock(L)",local:"Lock",global:"Lock"},unlock:{display:"Unlock(U)",local:"Unlock",global:"Unlock"},description:{display:"Description(D)",local:"Description",global:"Description"}}},layon:{alreadyOn:"All layers are already on.",turnedOn:"Turned on layers"},laycur:{prompt:"Select objects to be changed to the current layer",currentLayerNotFound:"Current layer not found.",noObjects:"No valid objects were selected.",alreadyCurrent:"Selected objects are already on the current layer.",changed:"Changed objects to current layer"},layfrz:{prompt:"Select object on layer to freeze or",invalidSelection:"Invalid object selected.",settingsPrompt:"Enter LAYFRZ setting to change",viewportPrompt:"Specify viewport freeze behavior",blockSelectionPrompt:"Specify nested block selection behavior",vpfreezeFallback:"Current viewer does not support per-viewport layer freeze; using Freeze behavior instead.",nestedSelectionLimited:"Nested block selection settings are stored, but current picking still resolves the top-level entity layer.",layerNotFound:"Layer not found",cannotFreezeCurrent:"Cannot freeze the current layer.",alreadyFrozen:"Layer is already frozen",frozen:"Frozen layer",restored:"Restored layer",nothingToUndo:"There is no LAYFRZ action to undo.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},viewports:{display:"Viewports(V)",local:"Viewports",global:"Viewports"},blockSelection:{display:"Block selection(B)",local:"Block selection",global:"BlockSelection"},freeze:{display:"Freeze(F)",local:"Freeze",global:"Freeze"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"},block:{display:"Block(B)",local:"Block",global:"Block"},entity:{display:"Entity(E)",local:"Entity",global:"Entity"},none:{display:"None(N)",local:"None",global:"None"}}},layiso:{prompt:"Select objects on the layer(s) to be isolated or",settingsPrompt:"Enter setting for layers not isolated",offModePrompt:"Enter off behavior for layers not isolated",noLayers:"No valid layers were selected.",layerNotFound:"Layer not found",isolated:"Isolated layer(s)",affectedLayers:"affected layers",vpfreezeFallback:"Current viewer does not support per-viewport layer freeze; using Off behavior instead.",lockFadeFallback:"Current viewer does not support layer fade display; non-isolated layers will be locked without fade.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},off:{display:"Off(O)",local:"Off",global:"Off"},lockAndFade:{display:"Lock and fade(L)",local:"Lock and fade",global:"LockAndFade"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"}}},layuniso:{noPrevious:"No previous LAYISO layer state to restore.",layerNotFound:"Layer not found",nothingRestored:"No LAYISO layer changes were restored.",restored:"Restored layers"},laythw:{alreadyThawed:"All layers are already thawed.",thawed:"Thawed layers"},laylck:{prompt:"Select an object on the layer to be locked",invalidSelection:"Invalid object selected.",layerNotFound:"Layer not found",alreadyLocked:"Layer is already locked",locked:"Locked layer"},layulk:{prompt:"Select an object on the layer to be unlocked",invalidSelection:"Invalid object selected.",layerNotFound:"Layer not found",alreadyUnlocked:"Layer is already unlocked",unlocked:"Unlocked layer"},layoff:{prompt:"Select object on layer to turn off or",invalidSelection:"Invalid object selected.",settingsPrompt:"Enter LAYOFF setting to change",viewportPrompt:"Specify viewport behavior",blockSelectionPrompt:"Specify nested block selection behavior",vpfreezeFallback:"Current viewer does not support per-viewport layer off; using Off behavior instead.",nestedSelectionLimited:"Nested block selection settings are stored, but current picking still resolves the top-level entity layer.",layerNotFound:"Layer not found",cannotTurnOffCurrent:"Cannot turn off the current layer.",alreadyOff:"Layer is already off",turnedOff:"Turned off layer",restored:"Restored layer",nothingToUndo:"There is no LAYOFF action to undo.",keywords:{settings:{display:"Settings(S)",local:"Settings",global:"Settings"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},viewports:{display:"Viewports(V)",local:"Viewports",global:"Viewports"},blockSelection:{display:"Block selection(B)",local:"Block selection",global:"BlockSelection"},off:{display:"Off(O)",local:"Off",global:"Off"},vpfreeze:{display:"Vpfreeze(V)",local:"Vpfreeze",global:"Vpfreeze"},block:{display:"Block(B)",local:"Block",global:"Block"},entity:{display:"Entity(E)",local:"Entity",global:"Entity"},none:{display:"None(N)",local:"None",global:"None"}}},layerp:{restored:"Restored previous layer state.",noPreviousState:"There is no previous layer state to restore."},line:{firstPoint:"Specify the first point:",firstPointOrContinue:"Specify first point or",nextPoint:"Specify the next point:",nextPointWithOptions:"Specify next point or",keywords:{continue:{display:"Continue(C)",local:"Continue",global:"Continue"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"}}},xline:{firstPointOrOptions:"Specify a point or",secondPoint:"Specify second point:",throughPoint:"Specify through point:",angle:"Enter angle of xline:",invalidDirection:"Invalid direction for XLINE.",keywords:{hor:{display:"Hor(H)",local:"Hor",global:"Hor"},ver:{display:"Ver(V)",local:"Ver",global:"Ver"},ang:{display:"Ang(A)",local:"Ang",global:"Ang"}}},ray:{startPoint:"Specify start point:",throughPoint:"Specify through point:"},mline:{startPointWithOptions:"Specify start point or",nextPointWithOptions:"Specify next point or",justificationPrompt:"Enter justification type",scalePrompt:"Specify mline scale:",stylePrompt:"Enter mline style name or [?] for list:",styleNotFound:"Mline style not found",styleListHeader:"Loaded mline styles:",styleListEmpty:"No mline style is loaded in current drawing.",keywords:{justification:{display:"Justification(J)",local:"Justification",global:"Justification"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},style:{display:"Style(ST)",local:"Style",global:"Style"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},top:{display:"Top(T)",local:"Top",global:"Top"},zero:{display:"Zero(Z)",local:"Zero",global:"Zero"},bottom:{display:"Bottom(B)",local:"Bottom",global:"Bottom"}}},measureAngle:{vertex:"Specify vertex point:",arm1:"Specify point on first arm:",arm2:"Specify point on second arm:"},measureArc:{startPoint:"Specify arc start point:",throughPoint:"Specify a point on the arc:",endPoint:"Specify arc end point:"},measureArea:{firstPoint:"Specify first point:",nextPoint:"Specify next point (or press Enter to finish):"},measureDistance:{firstPoint:"Specify first point:",secondPoint:"Specify second point:"},move:{basePointOrDisplacement:"Specify base point or",secondPointOrDisplacement:"Specify second point or",displacement:"Specify displacement:",keywords:{displacement:{display:"Displacement(D)",local:"Displacement",global:"Displacement"}}},offset:{distance:"Specify offset distance:",selectObject:"Select object to offset or press Enter to finish:",sidePoint:"Specify point on side to offset:",invalidDistance:"Offset distance must be greater than 0.",invalidSelection:"Selected object cannot be offset.",offsetFailed:"Unable to create an offset curve for the specified side."},mtext:{point:"Specify mtext insertion point:"},pngout:{boundsFirstCorner:"Specify first corner of bounds",boundsSecondCorner:"Specify opposite corner",longSidePrompt:"Enter long side size in pixels"},point:{point:"Specify a point"},polygon:{numberOfSides:"Enter number of sides:",centerOrEdge:"Specify center of polygon or",radiusOrType:"Enter options",edgeStart:"Specify first endpoint of edge:",edgeEnd:"Specify second endpoint of edge:",keywords:{edge:{display:"Edge(E)",local:"Edge",global:"Edge"},inscribed:{display:"Inscribed in circle(I)",local:"Inscribed in circle",global:"Inscribed"},circumscribed:{display:"Circumscribed about circle(C)",local:"Circumscribed about circle",global:"Circumscribed"}},invalid:{sides:"Invalid number of sides. Enter an integer between 3 and 1024.",radius:"Invalid radius. Radius must be greater than 0.",edge:"Invalid edge. The edge length must be greater than 0."}},polyline:{firstPoint:"Specify the first point:",nextPoint:"Specify the next point (or press Enter to finish):",nextPointWithOptions:"Specify next point or",nextPointWithArcOptions:"Specify next point or",keywords:{arc:{display:"Arc(A)",local:"Arc",global:"Arc"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},line:{display:"Line(L)",local:"Line",global:"Line"},angle:{display:"Angle(A)",local:"Angle",global:"Angle"},center:{display:"Center(C)",local:"Center",global:"Center"},secondPoint:{display:"Second point(P)",local:"Second point",global:"SecondPoint"},radius:{display:"Radius(R)",local:"Radius",global:"Radius"}},arcAngle:"Specify arc angle:",arcCenter:"Specify center point:",arcSecondPoint:"Specify second point on arc:",arcEndPoint:"Specify arc end point:",arcRadius:"Specify arc radius:"},rect:{firstPoint:"Specify first corner point:",nextPoint:"Specify other corner point:",firstPointWithOptions:"Specify first corner point or",otherCornerWithOptions:"Specify other corner point or",chamferFirst:"Specify first chamfer distance:",chamferSecond:"Specify second chamfer distance:",filletRadius:"Specify fillet radius:",segmentWidth:"Specify rectangle line width:",elevationValue:"Specify elevation:",thicknessValue:"Specify thickness:",rotationAngle:"Specify rectangle rotation angle:",dimensionLength:"Specify rectangle length:",dimensionWidth:"Specify rectangle width:",areaValue:"Specify rectangle area:",areaLengthOrWidth:"Specify rectangle length",areaSpecifyWidth:"Specify rectangle width:",invalidPositive:"Invalid input. Please enter a value greater than 0.",invalidRect:"Unable to create rectangle. Please specify valid corners or dimensions.",thicknessNotSupported:"Rectangle thickness is currently not written to entity data. The thickness setting is ignored.",keywords:{chamfer:{display:"Chamfer(C)",local:"Chamfer",global:"Chamfer"},elevation:{display:"Elevation(E)",local:"Elevation",global:"Elevation"},fillet:{display:"Fillet(F)",local:"Fillet",global:"Fillet"},thickness:{display:"Thickness(T)",local:"Thickness",global:"Thickness"},width:{display:"Width(W)",local:"Width",global:"Width"},area:{display:"Area(A)",local:"Area",global:"Area"},dimensions:{display:"Dimensions(D)",local:"Dimensions",global:"Dimensions"},rotation:{display:"Rotation(R)",local:"Rotation",global:"Rotation"},length:{display:"Length(L)",local:"Length",global:"Length"},rectWidth:{display:"Width(W)",local:"Width",global:"Width"}}},rotate:{basePoint:"Specify base point:",rotationAngleOrOptions:"Specify rotation angle or",referenceAngleOrPoints:"Specify reference angle or",firstReferencePoint:"Specify first point of reference angle:",secondReferencePoint:"Specify second point:",newAngle:"Specify new angle:",keywords:{copy:{display:"Copy(C)",local:"Copy",global:"Copy"},reference:{display:"Reference(R)",local:"Reference",global:"Reference"},points:{display:"Points(P)",local:"Points",global:"Points"}},invalid:{referencePoints:"Invalid reference points: points must be different."}},sketch:{firstPoint:"Specify the first point:",nextPoint:"Specify the end point:"},spline:{firstPoint:"Specify the first point:",nextPoint:"Specify the next point (or press Enter to finish):",firstPointWithOptions:"Specify first point or",nextPointWithFitOptions:"Specify next point or",nextPointWithCvOptions:"Specify next control vertex or",methodPrompt:"Enter spline creation method",knotsPrompt:"Enter knot parameterization",degreePrompt:"Specify spline degree:",keywords:{method:{display:"Method(M)",local:"Method",global:"Method"},fit:{display:"Fit(F)",local:"Fit",global:"Fit"},cv:{display:"CV(C)",local:"CV",global:"CV"},knots:{display:"Knots(K)",local:"Knots",global:"Knots"},degree:{display:"Degree(D)",local:"Degree",global:"Degree"},undo:{display:"Undo(U)",local:"Undo",global:"Undo"},close:{display:"Close(C)",local:"Close",global:"Close"},chord:{display:"Chord(C)",local:"Chord",global:"Chord"},sqrtChord:{display:"Sqrt chord(S)",local:"Sqrt chord",global:"SqrtChord"},uniform:{display:"Uniform(U)",local:"Uniform",global:"Uniform"}}},sysvar:{prompt:"Please input new value:"},zoom:{mainPrompt:"Specify corner of window or",firstCorner:"Specify first corner:",secondCorner:"Specify opposite corner:",centerPoint:"Specify center point:",heightOrScale:"Enter height or scale factor (nX or nXP):",scaleFactor:"Enter scale factor (nX or nXP):",keywords:{all:{display:"All(A)",local:"All",global:"All"},center:{display:"Center(C)",local:"Center",global:"Center"},extents:{display:"Extents(E)",local:"Extents",global:"Extents"},previous:{display:"Previous(P)",local:"Previous",global:"Previous"},scale:{display:"Scale(S)",local:"Scale",global:"Scale"},window:{display:"Window(W)",local:"Window",global:"Window"}}}},ol={commandLine:{noLast:"(no last command)",unknownCommand:"Unknown command",executed:"Executed command",showHistory:"Show command history",placeholder:"Type command",showMessages:"Show message history",canceled:"*Canceled*",noHistory:"(no history)",close:"Close command line"},inputManager:{firstCorner:"Specify the first corner or",secondCorner:"Specify the second corner or"},message:{fetchingDrawingFile:"Fetching file ..."},progress:{start:"Start parsing file ...",parse:"Parsing file ...",font:"Downloading fonts needed by this drawing ...",ltype:"Parsing line types ...",style:"Parsing text syltes ...",dimstyle:"Parsing dimension styles ...",layer:"Parsing layers ...",vport:"Parsing viewports ...",blockrecord:"Parsing block record ...",header:"Parsing header ...",block:"Parsing blocks ...",entity:"Parsing entities ...",object:"Parsing named dictionaries ...",end:"Finished!"}},al={ACAD:{"-hatch":{description:"通过命令行选项创建填充,不显示 Ribbon 界面"},"-layer":{description:"通过命令行选项管理图层"},angbase:{description:"设置当前 UCS 中 0 度的基准角方向"},angdir:{description:"设置正角度的方向为顺时针或逆时针"},arc:{description:"创建圆弧"},aunits:{description:"设置角度显示格式"},auprec:{description:"设置角度显示精度(小数位数),与 AUNITS 配合使用"},cdxf:{description:"导出当前图纸为DXF格式"},cpdf:{description:"导出当前图纸为PDF格式"},cecolor:{description:"设置新创建对象的当前默认颜色"},celtscale:{description:"控制新创建对象的线型比例系数"},celtype:{description:"设置新创建对象的线型"},celweight:{description:"设置新创建对象的默认线宽"},cetranparency:{description:"设置新创建对象的透明度"},circle:{description:"使用圆心和半径创建圆"},clayer:{description:"设置新建对象和编辑操作所使用的当前图层"},cmleaderstyle:{description:"设置当前多重引线样式名称"},cmlscale:{description:"控制多线的整体宽度"},cmlstyle:{description:"设置当前多线样式名称"},colortheme:{description:"控制用户界面的颜色主题(深色或浅色)"},copy:{description:"通过克隆将所选图元复制到新位置",prompt:"选择对象"},csvg:{description:"转换当前图纸为SVG格式"},chtml:{description:"将当前图纸导出为可离线打开的 HTML 文件"},dimlinear:{description:"创建线性尺寸标注"},dynmode:{description:"控制光标处的动态输入设置"},dynprompt:{description:"控制动态输入工具提示中提示的显示"},ellipse:{description:"通过轴端点或中心点创建椭圆或椭圆弧"},erase:{description:"从图纸中删除所选对象",prompt:"选择对象"},hatch:{description:"用填充图案填充封闭区域或所选对象"},ipdf:{description:"从 PDF 文件导入矢量几何"},hpang:{description:"设置新创建填充图案的默认角度(弧度)"},hpassoc:{description:"控制新创建的填充是否具有关联性"},hpbackgroundcolor:{description:"设置新创建填充图案的默认背景颜色"},hpcolor:{description:"设置新创建填充的默认颜色"},hpdouble:{description:"控制用户定义的填充图案是否加倍"},hpislanddetection:{description:"控制新创建填充边界内孤岛的处理方式"},hplayer:{description:"设置新创建填充和填充区域的默认图层"},hpname:{description:"设置当前会话中新创建填充的默认图案名称"},hpscale:{description:"设置新创建填充图案的默认比例系数"},hpseparate:{description:"控制为多个边界创建单个还是独立的填充对象"},hptransparency:{description:"设置新创建填充和填充区域的默认透明度"},insunits:{description:"指定插入块、图像或外部参照时用于自动缩放的图形单位"},laycur:{description:"将所选对象的图层属性更改为当前图层",prompt:"选择要更改到当前图层的对象"},laydel:{description:"删除图层及该图层上的所有对象"},layerclose:{description:"关闭图层属性管理器"},layerp:{description:"撤销对图层设置的最后一次更改或一组更改"},layfrz:{description:"冻结所选对象所在的图层",prompt:"选择要冻结其图层的对象"},layiso:{description:"隔离所选对象所在的图层",prompt:"选择要隔离其图层的对象"},laylck:{description:"锁定所选对象所在的图层",prompt:"选择要锁定其图层的对象"},layoff:{description:"关闭所选对象所在的图层",prompt:"选择要关闭其图层的对象"},layon:{description:"打开图纸中的所有图层"},laythw:{description:"解冻图纸中的所有冻结图层"},layulk:{description:"解锁所选对象所在的图层",prompt:"选择要解锁其图层的对象"},layuniso:{description:"恢复由 LAYISO 隐藏或锁定的图层"},line:{description:"在指定点之间绘制直线段"},log:{description:"在控制台输出调试信息"},lunits:{description:"设置坐标和距离的显示格式"},luprec:{description:"设置线性单位的显示精度(小数位数),与 LUNITS 配合使用"},lwdisplay:{description:"用于控制是否在图纸中显示线宽效果"},measurearea:{description:"计算所选对象或点定义区域的面积和周长"},measureangle:{description:"测量两条线或三个点之间的夹角"},measurearc:{description:"测量圆弧段的弧长"},measuredistance:{description:"测量两点之间的距离及坐标增量"},measurement:{description:"设置图形使用英制或公制单位"},measurementcolor:{description:"设置测量标注覆盖图形使用的颜色"},mline:{description:"创建由多条平行线组成的多线对象"},move:{description:"通过位移向量移动所选图元",prompt:"选择对象"},offset:{description:"按指定距离创建平行曲线、多段线或圆"},mtext:{description:"创建多行文本"},open:{description:"打开图纸"},osmode:{description:"使用位码设置运行中的对象捕捉模式"},pan:{description:"平移视图"},pickbox:{description:"控制用于选择对象的拾取框大小(像素)"},pline:{description:"通过指定多个点创建多段线"},pngout:{description:"导出为 PNG 图片"},point:{description:"连续创建点"},polygon:{description:"通过中心和半径或指定一条边创建正多边形"},qnew:{description:"创建新图纸"},ray:{description:"创建从起点向单一方向无限延伸的射线"},rectang:{description:"通过指定两个对角点创建矩形"},regen:{description:"重绘图纸"},revcloud:{description:"创建矩形修订云线"},rotate:{description:"绕基点旋转所选图元",prompt:"选择对象"},select:{description:"选择图元"},shortcutmenu:{description:"控制图形区域中快捷菜单的可用性"},sketch:{description:"使用多段线创建手绘线,跟踪鼠标移动"},spline:{description:"通过指定控制点创建平滑的样条曲线"},textstyle:{description:"设置当前文字样式的名称"},unitmode:{description:"当 LUNITS 为建筑或分数格式时,控制坐标的分数显示格式"},switchbg:{description:"切换绘图区域背景颜色,在白色和黑色背景之间切换"},xline:{description:"创建在两个方向上无限延伸的构造线"},zoom:{description:"缩放以显示所有对象"}},USER:{}},cl={arc:{startPointOrCenter:"指定圆弧的起点或",secondPointOrOptions:"指定圆弧上的第二点或",secondPoint:"指定圆弧上的第二点:",startPoint:"指定圆弧的起点:",centerPoint:"指定圆弧的圆心:",endPoint:"指定圆弧的端点:",endPointOrOptions:"指定圆弧的端点或",centerPointOrOptions:"指定圆弧的圆心或",includedAngle:"指定圆弧的夹角:",chordLength:"指定圆弧的弦长:",tangentDirection:"指定圆弧起点的切线方向:",radius:"指定圆弧的半径:",keywords:{center:{display:"圆心(C)",local:"圆心",global:"Center"},end:{display:"端点(E)",local:"端点",global:"End"},angle:{display:"角度(A)",local:"角度",global:"Angle"},chordLength:{display:"弦长(L)",local:"弦长",global:"ChordLength"},direction:{display:"方向(D)",local:"方向",global:"Direction"},radius:{display:"半径(R)",local:"半径",global:"Radius"}},invalid:{threePoint:"三点圆弧无效:三点共线或无法确定圆弧。",center:"圆心输入无效:起点与终点必须在同一圆上。",angle:"角度输入无效:夹角必须大于 0 且小于 360 度。",chordLength:"弦长输入无效:该值超出当前半径可用范围。",direction:"方向输入无效:无法根据该切线方向构造圆弧。",radius:"半径输入无效:指定半径无法连接起点与终点。"}},circle:{center:"指定圆的圆心:",centerOrOptions:"指定圆的圆心或",radius:"指定圆的半径:",radiusOrDiameter:"指定圆的半径或",diameter:"指定圆的直径:",twoPointFirst:"指定圆直径的第一个端点:",twoPointSecond:"指定圆直径的第二个端点:",threePointFirst:"指定圆上的第一个点:",threePointSecond:"指定圆上的第二个点:",threePointThird:"指定圆上的第三个点:",keywords:{threeP:{display:"三点(3P)",local:"三点",global:"3P"},twoP:{display:"两点(2P)",local:"两点",global:"2P"},diameter:{display:"直径(D)",local:"直径",global:"Diameter"}}},copy:{basePointOrOptions:"指定基点或",displacementOrArray:"指定位移或",secondPointOrArray:"指定第二个点或",modePrompt:"输入复制模式选项",arrayItemCount:"输入阵列中的项目数(包括原对象):",arraySecondPointOrFit:"指定第二个点或",arrayFitSecondPoint:"指定第二个点:",keywords:{displacement:{display:"位移(D)",local:"位移",global:"Displacement"},mode:{display:"模式(O)",local:"模式",global:"Mode"},multiple:{display:"多个(M)",local:"多个",global:"Multiple"},single:{display:"单个(S)",local:"单个",global:"Single"},array:{display:"阵列(A)",local:"阵列",global:"Array"},fit:{display:"布满(F)",local:"布满",global:"Fit"}}},dimlinear:{xLine1Point:"指定第一条尺寸界限原点:",xLine2Point:"指定第二条尺寸界限原点:",dimLinePoint:"指定尺寸线位置:"},ellipse:{axisEndpointOrOptions:"指定椭圆的轴端点或",arcAxisEndpointOrCenter:"指定椭圆弧的轴端点或",center:"指定椭圆中心点:",firstAxisEndpoint:"指定轴的端点:",secondAxisEndpoint:"指定轴的另一个端点:",otherAxisOrRotation:"指定到另一轴的距离或",rotationAngle:"指定绕长轴的旋转角度:",arcStartAngle:"指定椭圆弧起始角:",arcEndAngle:"指定椭圆弧终止角:",keywords:{arc:{display:"圆弧(A)",local:"圆弧",global:"Arc"},center:{display:"中心点(C)",local:"中心点",global:"Center"},rotation:{display:"旋转(R)",local:"旋转",global:"Rotation"}},invalid:{axis:"轴输入无效:轴长必须大于 0。",otherAxis:"另一轴输入无效:距离必须大于 0。",rotation:"旋转输入无效:计算得到的短轴必须大于 0。"}},hatch:{prompt:"选择边界对象或",pickPoint:"指定内部点(或按 Enter 结束):",select:"选择要填充的对象:",patternName:"输入填充图案名称:",scale:"指定填充图案比例:",angle:"指定填充图案角度:",style:"输入填充样式",associative:"指定关联性",invalidBoundary:"所选对象无法构成闭合边界。",keywords:{pick:{display:"拾取点(P)",local:"拾取点",global:"PickPoints"},select:{display:"选择对象(S)",local:"选择对象",global:"SelectObjects"},cancel:{display:"放弃(C)",local:"放弃",global:"Cancel"},pattern:{display:"图案(P)",local:"图案",global:"Pattern"},scale:{display:"比例(S)",local:"比例",global:"Scale"},angle:{display:"角度(A)",local:"角度",global:"Angle"},style:{display:"样式(T)",local:"样式",global:"HatchStyle"},associative:{display:"关联(AS)",local:"关联",global:"AssociativeMode"},normal:{display:"普通(N)",local:"普通",global:"Normal"},outer:{display:"外部(O)",local:"外部",global:"Outer"},ignore:{display:"忽略(I)",local:"忽略",global:"Ignore"},yes:{display:"是(Y)",local:"是",global:"Yes"},no:{display:"否(N)",local:"否",global:"No"}}},layer:{main:"输入选项",listSummary:"图层列表已输出到浏览器控制台",emptyInput:"未输入图层名。",newPrompt:"输入新建图层名称(可用逗号分隔多个):",makePrompt:"输入要创建并设为当前的图层名:",setPrompt:"输入要设为当前的图层名:",onPrompt:"输入要打开的图层名:",offPrompt:"输入要关闭的图层名:",freezePrompt:"输入要冻结的图层名:",thawPrompt:"输入要解冻的图层名:",lockPrompt:"输入要锁定的图层名:",unlockPrompt:"输入要解锁的图层名:",colorLayerPrompt:"输入要修改颜色的图层名:",colorValuePrompt:"输入颜色(ACI 1-255、RGB 如 255,0,0 或颜色名):",invalidColor:"颜色输入无效。",descriptionLayerPrompt:"输入要修改说明的图层名:",descriptionValuePrompt:"输入新的图层说明:",created:"已创建图层数量",alreadyExists:"图层已存在",notFound:"未找到图层",cannotChangeCurrent:"不能关闭或冻结当前图层。",keywords:{list:{display:"?(?)",local:"?",global:"?"},make:{display:"创建并置为当前(M)",local:"创建并置为当前",global:"Make"},set:{display:"置为当前(S)",local:"置为当前",global:"Set"},new:{display:"新建(N)",local:"新建",global:"New"},on:{display:"打开(ON)",local:"打开",global:"On"},off:{display:"关闭(OF)",local:"关闭",global:"Off"},color:{display:"颜色(C)",local:"颜色",global:"Color"},freeze:{display:"冻结(F)",local:"冻结",global:"Freeze"},thaw:{display:"解冻(T)",local:"解冻",global:"Thaw"},lock:{display:"锁定(L)",local:"锁定",global:"Lock"},unlock:{display:"解锁(U)",local:"解锁",global:"Unlock"},description:{display:"说明(D)",local:"说明",global:"Description"}}},layon:{alreadyOn:"所有图层都已经打开。",turnedOn:"已打开图层数量"},laycur:{prompt:"选择要更改到当前图层的对象",currentLayerNotFound:"未找到当前图层。",noObjects:"没有选择有效对象。",alreadyCurrent:"所选对象已位于当前图层。",changed:"已将对象更改到当前图层"},layfrz:{prompt:"选择要冻结其图层的对象或",invalidSelection:"所选对象无效。",settingsPrompt:"输入要修改的 LAYFRZ 设置",viewportPrompt:"指定视口冻结行为",blockSelectionPrompt:"指定嵌套块选择行为",vpfreezeFallback:"当前 viewer 不支持按视口冻结图层,已退化为普通 Freeze 行为。",nestedSelectionLimited:"嵌套块选择设置会被保存,但当前拾取仍只能解析顶层对象所在图层。",layerNotFound:"未找到图层",cannotFreezeCurrent:"不能冻结当前图层。",alreadyFrozen:"图层已处于冻结状态",frozen:"已冻结图层",restored:"已恢复图层",nothingToUndo:"当前没有可撤销的 LAYFRZ 操作。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},viewports:{display:"视口(V)",local:"视口",global:"Viewports"},blockSelection:{display:"块选择(B)",local:"块选择",global:"BlockSelection"},freeze:{display:"冻结(F)",local:"冻结",global:"Freeze"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"},block:{display:"块(B)",local:"块",global:"Block"},entity:{display:"对象(E)",local:"对象",global:"Entity"},none:{display:"无(N)",local:"无",global:"None"}}},layiso:{prompt:"选择要隔离其图层的对象或",settingsPrompt:"输入未隔离图层的处理设置",offModePrompt:"输入未隔离图层的关闭行为",noLayers:"未选择有效图层。",layerNotFound:"未找到图层",isolated:"已隔离图层",affectedLayers:"受影响图层数",vpfreezeFallback:"当前 viewer 不支持按视口冻结图层,已退化为普通 Off 行为。",lockFadeFallback:"当前 viewer 不支持图层淡显显示,未隔离图层将仅被锁定。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},off:{display:"关闭(O)",local:"关闭",global:"Off"},lockAndFade:{display:"锁定并淡显(L)",local:"锁定并淡显",global:"LockAndFade"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"}}},laythw:{alreadyThawed:"所有图层都已经解冻。",thawed:"已解冻图层数量"},layuniso:{noPrevious:"没有可恢复的上一次 LAYISO 图层状态。",layerNotFound:"未找到图层",nothingRestored:"没有恢复任何 LAYISO 图层改动。",restored:"已恢复图层数量"},laylck:{prompt:"选择要锁定其图层的对象",invalidSelection:"所选对象无效。",layerNotFound:"未找到图层",alreadyLocked:"图层已处于锁定状态",locked:"已锁定图层"},layulk:{prompt:"选择要解锁其图层的对象",invalidSelection:"所选对象无效。",layerNotFound:"未找到图层",alreadyUnlocked:"图层已处于解锁状态",unlocked:"已解锁图层"},layoff:{prompt:"选择要关闭其图层的对象或",invalidSelection:"所选对象无效。",settingsPrompt:"输入要修改的 LAYOFF 设置",viewportPrompt:"指定视口行为",blockSelectionPrompt:"指定嵌套块选择行为",vpfreezeFallback:"当前 viewer 不支持按视口关闭图层,已退化为普通 Off 行为。",nestedSelectionLimited:"嵌套块选择设置会被保存,但当前拾取仍只能解析顶层对象所在图层。",layerNotFound:"未找到图层",cannotTurnOffCurrent:"不能关闭当前图层。",alreadyOff:"图层已处于关闭状态",turnedOff:"已关闭图层",restored:"已恢复图层",nothingToUndo:"当前没有可撤销的 LAYOFF 操作。",keywords:{settings:{display:"设置(S)",local:"设置",global:"Settings"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},viewports:{display:"视口(V)",local:"视口",global:"Viewports"},blockSelection:{display:"块选择(B)",local:"块选择",global:"BlockSelection"},off:{display:"关闭(O)",local:"关闭",global:"Off"},vpfreeze:{display:"视口冻结(V)",local:"视口冻结",global:"Vpfreeze"},block:{display:"块(B)",local:"块",global:"Block"},entity:{display:"对象(E)",local:"对象",global:"Entity"},none:{display:"无(N)",local:"无",global:"None"}}},layerp:{restored:"恢复了之前的图层状态。",noPreviousState:"没有可恢复的先前图层状态。"},line:{firstPoint:"指定第一个点:",firstPointOrContinue:"请指定第一个点或",nextPoint:"指定下一个点:",nextPointWithOptions:"请指定下一个点或",keywords:{continue:{display:"继续(C)",local:"继续",global:"Continue"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"}}},xline:{firstPointOrOptions:"指定点或",secondPoint:"指定第二个点:",throughPoint:"指定穿过点:",angle:"输入构造线角度:",invalidDirection:"XLINE 的方向无效。",keywords:{hor:{display:"水平(H)",local:"水平",global:"Hor"},ver:{display:"垂直(V)",local:"垂直",global:"Ver"},ang:{display:"角度(A)",local:"角度",global:"Ang"}}},ray:{startPoint:"指定起点:",throughPoint:"指定通过点:"},mline:{startPointWithOptions:"指定起点或",nextPointWithOptions:"指定下一点或",justificationPrompt:"输入对正方式",scalePrompt:"指定多线比例:",stylePrompt:"输入多线样式名或 [?] 列出样式:",styleNotFound:"未找到多线样式",styleListHeader:"已加载的多线样式:",styleListEmpty:"当前图纸没有已加载的多线样式。",keywords:{justification:{display:"对正(J)",local:"对正",global:"Justification"},scale:{display:"比例(S)",local:"比例",global:"Scale"},style:{display:"样式(ST)",local:"样式",global:"Style"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},top:{display:"上(T)",local:"上",global:"Top"},zero:{display:"零(Z)",local:"零",global:"Zero"},bottom:{display:"下(B)",local:"下",global:"Bottom"}}},measureArc:{startPoint:"指定弧的起点:",throughPoint:"指定弧上的一个点:",endPoint:"指定弧的终点:"},measureAngle:{vertex:"指定顶点:",arm1:"指定第一条边上的点:",arm2:"指定第二条边上的点:"},measureArea:{firstPoint:"指定第一个点:",nextPoint:"指定下一个点(或按 Enter 完成):"},measureDistance:{firstPoint:"指定第一个点:",secondPoint:"指定第二个点:"},move:{basePointOrDisplacement:"指定基点或",secondPointOrDisplacement:"指定第二个点或",displacement:"指定位移:",keywords:{displacement:{display:"位移(D)",local:"位移",global:"Displacement"}}},offset:{distance:"指定偏移距离:",selectObject:"选择要偏移的对象,或按 Enter 结束:",sidePoint:"指定要偏移到的那一侧的点:",invalidDistance:"偏移距离必须大于 0。",invalidSelection:"所选对象不能偏移。",offsetFailed:"无法在指定侧创建偏移曲线。"},mtext:{point:"指定多行文本插入点:"},pngout:{boundsFirstCorner:"指定边界的第一个角点",boundsSecondCorner:"指定对角点",longSidePrompt:"输入长边像素大小"},point:{point:"指定点"},polygon:{numberOfSides:"输入边数:",centerOrEdge:"指定多边形中心点或",radiusOrType:"输入选项",edgeStart:"指定边的第一个端点:",edgeEnd:"指定边的第二个端点:",keywords:{edge:{display:"边(E)",local:"边",global:"Edge"},inscribed:{display:"内接于圆(I)",local:"内接于圆",global:"Inscribed"},circumscribed:{display:"外切于圆(C)",local:"外切于圆",global:"Circumscribed"}},invalid:{sides:"边数无效:请输入 3 到 1024 之间的整数。",radius:"半径无效:半径必须大于 0。",edge:"边无效:边长必须大于 0。"}},polyline:{firstPoint:"指定第一个点:",nextPoint:"指定下一个点(或按 Enter 完成):",nextPointWithOptions:"请指定下一个点或",nextPointWithArcOptions:"请指定下一个点或",keywords:{arc:{display:"圆弧(A)",local:"圆弧",global:"Arc"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},line:{display:"直线(L)",local:"直线",global:"Line"},angle:{display:"角度(A)",local:"角度",global:"Angle"},center:{display:"圆心(C)",local:"圆心",global:"Center"},secondPoint:{display:"第二点(P)",local:"第二点",global:"SecondPoint"},radius:{display:"半径(R)",local:"半径",global:"Radius"}},arcAngle:"指定弧角度:",arcCenter:"指定圆心:",arcSecondPoint:"指定弧上的第二点:",arcEndPoint:"指定弧的终点:",arcRadius:"指定弧半径:"},rotate:{basePoint:"指定基点:",rotationAngleOrOptions:"指定旋转角度或",referenceAngleOrPoints:"指定参考角或",firstReferencePoint:"指定参考角的第一点:",secondReferencePoint:"指定第二点:",newAngle:"指定新角度:",keywords:{copy:{display:"复制(C)",local:"复制",global:"Copy"},reference:{display:"参照(R)",local:"参照",global:"Reference"},points:{display:"点(P)",local:"点",global:"Points"}},invalid:{referencePoints:"参考点输入无效:两点必须不同。"}},rect:{firstPoint:"指定第一个角点:",nextPoint:"指定另一个角点:",firstPointWithOptions:"指定第一个角点或者",otherCornerWithOptions:"指定另一个角点或者",chamferFirst:"指定第一个倒角距离:",chamferSecond:"指定第二个倒角距离:",filletRadius:"指定圆角半径:",segmentWidth:"指定矩形线宽:",elevationValue:"指定标高:",thicknessValue:"指定厚度:",rotationAngle:"指定矩形旋转角度:",dimensionLength:"指定矩形长度:",dimensionWidth:"指定矩形宽度:",areaValue:"指定矩形面积:",areaLengthOrWidth:"指定矩形长度",areaSpecifyWidth:"指定矩形宽度:",invalidPositive:"输入无效:请输入大于 0 的数值。",invalidRect:"无法创建矩形:请输入有效的角点或尺寸。",thicknessNotSupported:"当前版本暂不支持将矩形厚度写入图元,已忽略厚度设置。",keywords:{chamfer:{display:"倒角(C)",local:"倒角",global:"Chamfer"},elevation:{display:"标高(E)",local:"标高",global:"Elevation"},fillet:{display:"圆角(F)",local:"圆角",global:"Fillet"},thickness:{display:"厚度(T)",local:"厚度",global:"Thickness"},width:{display:"宽度(W)",local:"宽度",global:"Width"},area:{display:"面积(A)",local:"面积",global:"Area"},dimensions:{display:"尺寸(D)",local:"尺寸",global:"Dimensions"},rotation:{display:"旋转(R)",local:"旋转",global:"Rotation"},length:{display:"长度(L)",local:"长度",global:"Length"},rectWidth:{display:"宽度(W)",local:"宽度",global:"Width"}}},sketch:{firstPoint:"指定第一个点:",nextPoint:"指定结束点:"},spline:{firstPoint:"指定第一个点:",nextPoint:"指定下一个点(或按 Enter 完成):",firstPointWithOptions:"指定第一个点或",nextPointWithFitOptions:"指定下一个点或",nextPointWithCvOptions:"指定下一个控制顶点或",methodPrompt:"输入样条创建方式",knotsPrompt:"输入节点参数化方式",degreePrompt:"指定样条次数:",keywords:{method:{display:"方法(M)",local:"方法",global:"Method"},fit:{display:"拟合(F)",local:"拟合",global:"Fit"},cv:{display:"控制顶点(C)",local:"控制顶点",global:"CV"},knots:{display:"节点(K)",local:"节点",global:"Knots"},degree:{display:"次数(D)",local:"次数",global:"Degree"},undo:{display:"放弃(U)",local:"放弃",global:"Undo"},close:{display:"闭合(C)",local:"闭合",global:"Close"},chord:{display:"弦长(C)",local:"弦长",global:"Chord"},sqrtChord:{display:"平方根弦长(S)",local:"平方根弦长",global:"SqrtChord"},uniform:{display:"均匀(U)",local:"均匀",global:"Uniform"}}},sysvar:{prompt:"请输入新的值:"},zoom:{mainPrompt:"指定窗口角点或",firstCorner:"指定第一个角点:",secondCorner:"指定对角点:",centerPoint:"指定缩放中心点:",heightOrScale:"输入高度或比例因子(nX 或 nXP):",scaleFactor:"输入比例因子(nX 或 nXP):",keywords:{all:{display:"全部(A)",local:"全部",global:"All"},center:{display:"中心(C)",local:"中心",global:"Center"},extents:{display:"范围(E)",local:"范围",global:"Extents"},previous:{display:"上一个(P)",local:"上一个",global:"Previous"},scale:{display:"比例(S)",local:"比例",global:"Scale"},window:{display:"窗口(W)",local:"窗口",global:"Window"}}}},ll={commandLine:{noLast:"(无上一次命令)",unknownCommand:"未知命令",executed:"已执行命令",showHistory:"显示命令历史",placeholder:"输入命令",showMessages:"显示消息历史",canceled:"*已取消*",noHistory:"(无历史记录)",close:"关闭命令行"},inputManager:{firstCorner:"指定第一个角点或",secondCorner:"指定第二个角点或"},message:{fetchingDrawingFile:"正在加载图纸文件..."},progress:{start:"开始解析文件...",parse:"正在解析文件 ...",font:"正在下载图纸所需字体...",ltype:"正在解析线形...",style:"正在解析文字样式...",dimstyle:"正在解析标注样式...",layer:"正在解析图层...",vport:"正在解析视口...",blockrecord:"正在解析BTRs...",header:"正在解析文件头...",block:"正在解析块..",entity:"正在解析图元...",object:"正在解析NODs...",end:"完成!"}};g.mergeLocaleMessage("en",{command:sl,jig:rl,main:ol}),g.mergeLocaleMessage("zh",{command:al,jig:cl,main:ll});const _n=(o,e)=>{const t=`command.${o}.${e}`;return g.t(t)},hl=o=>_n(he.SYSTEMT_COMMAND_GROUP_NAME,o),ul=o=>_n(he.DEFAUT_COMMAND_GROUP_NAME,o);class lr{constructor(e){this.options=e}parse(e){const t=e.trim();if(t.length===0)return this.options.allowNone,null;const i=this.options.keywords.findByName(t);return i?i.globalName:this.options.allowArbitraryInput?t:null}}class dl{start(){return new Promise(e=>{this.resolve=e,this.onStart()})}finish(e){this.cleanup(),this.resolve(e)}}class gl extends dl{constructor(e,t,i=!0){super(),this.cli=e,this.options=t,this.allowTyping=i,this.handler=new lr(t)}onStart(){this.cli.clearInput(),this.cli.setInputReadOnly(!this.allowTyping),this.cli.renderKeywordPrompt(this.options,e=>this.finish(e)),this.cli.focusInput()}handleEnter(e){if(!this.allowTyping)return!0;if(!e.trim()){const i=this.options.keywords.default;return i!=null&&i.enabled?(this.finish(i.globalName),!0):this.options.allowNone?(this.finish(""),!0):!1}const t=this.handler.parse(e);return t!==null?(this.finish(t),!0):!1}handleEscape(){this.finish("")}cleanup(){this.cli.setInputReadOnly(!1),this.cli.clear()}}class hr{constructor(e=document.body){this.isPromptActive=!1,this.recentMessages=[],this.isCommandLifecycleBound=!1,this.container=e,this.history=[],this.historyIndex=-1,this.lastExecuted=null,this.isCmdPopupOpen=!1,this.isMsgPanelOpen=!1,this.minWidth=420,this.widthRatio=.66,this.autoCompleteIndex=-1,this.injectCSS(),this.createUI(),this.bindEvents(),this.bindCommandLifecycleEvents(),this.resizeHandler(),window.addEventListener("resize",()=>this.resizeHandler()),this.resizeObserver=new ResizeObserver(()=>this.resizeHandler()),this.resizeObserver.observe(this.container),g.events.localeChanged.addEventListener(()=>this.refreshLocale())}get visible(){return this.cliContainer.style.display!=="none"}set visible(e){this.cliContainer.style.display=e?"block":"none"}setPrompt(e){this.isPromptActive=!0,this.promptEl.innerHTML=e??"",this.textInput.placeholder="",this.recordRecentMessage(e)}clear(){this.clearPrompt(),this.clearInput()}clearPrompt(){this.promptEl.innerHTML="",this.isPromptActive=!1}clearInput(){this.textInput.value="",this.textInput.placeholder=this.isPromptActive?"":this.localize("main.commandLine.placeholder")}focusInput(){this.textInput.focus()}setInputReadOnly(e){this.textInput.readOnly=e}showMessage(e,t="info",i){this.appendMessage(e,t,i)}cancelActiveSession(){this.activeSession&&(this.activeSession.handleEscape(),this.activeSession=void 0)}async getKeywords(e,t=!0){this.activeSession=new gl(this,e,t);const i=await this.activeSession.start();return this.activeSession=void 0,i}localize(e,t){return g.t(e,{fallback:t})}refreshLocale(){Array.from(this.msgPanel.children).forEach(e=>{var n,s,r,a;const t=e,i=t.dataset.msgKey;if(i)if(i==="main.commandLine.executed"){const c=((s=(n=t.textContent)==null?void 0:n.split(":")[1])==null?void 0:s.trim())??"";t.textContent=`${this.localize(i)}: ${c}`}else if(i==="main.commandLine.unknownCommand"){const c=((a=(r=t.textContent)==null?void 0:r.split(":")[1])==null?void 0:a.trim())??"";t.textContent=`${this.localize(i)}: ${c}`}else t.textContent=this.localize(i)}),this.centerEl.setAttribute("data-placeholder",this.localize("main.commandLine.placeholder")),!this.isPromptActive&&!this.textInput.value&&(this.textInput.placeholder=this.localize("main.commandLine.placeholder")),this.downBtn.title=this.localize("main.commandLine.showHistory"),this.upBtn.title=this.localize("main.commandLine.showMessages")}executeCommand(e){if(!e||!e.trim())if(this.lastExecuted)e=this.lastExecuted;else{this.showMessage(this.localize("main.commandLine.noLast","(no last command)"));return}const t=this.resolveCommand(e);if(!t){const n=this.localize("main.commandLine.unknownCommand");this.showMessage(`${n}: ${e}`,"warning");return}this.history.push(t.globalName),this.historyIndex=this.history.length,this.lastExecuted=t.globalName,this.printHistoryLine(e);const i=this.localize("main.commandLine.executed");this.showMessage(`${i}: ${t.localName}`),A.instance.sendStringToExecute(e),this.clearInput()}injectCSS(){const e=document.createElement("style");e.textContent=`
|
|
352
|
+
.ml-cli-container {
|
|
353
|
+
position: fixed;
|
|
354
|
+
bottom: 10px;
|
|
355
|
+
left: 50%;
|
|
356
|
+
transform: translateX(-50%);
|
|
357
|
+
font-family: "Segoe UI", Arial, sans-serif;
|
|
358
|
+
font-size: 13px;
|
|
359
|
+
box-sizing: border-box;
|
|
360
|
+
user-select: none;
|
|
361
|
+
max-width: calc(100% - 20px);
|
|
362
|
+
z-index: 5;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
.ml-cli-bar {
|
|
366
|
+
display: flex;
|
|
367
|
+
align-items: center;
|
|
368
|
+
gap: 6px;
|
|
369
|
+
border-radius: 6px;
|
|
370
|
+
background: var(--ml-ui-bg, linear-gradient(#ededed, #e0e0e0));
|
|
371
|
+
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.35));
|
|
372
|
+
box-shadow: var(--ml-ui-shadow, 0 2px 6px rgba(0, 0, 0, 0.25));
|
|
373
|
+
min-width: 300px;
|
|
374
|
+
height: 30px;
|
|
375
|
+
max-width: 100%;
|
|
376
|
+
overflow: hidden;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
.ml-cli-left {
|
|
380
|
+
display: flex;
|
|
381
|
+
align-items: center;
|
|
382
|
+
gap: 4px;
|
|
383
|
+
background: var(--ml-ui-bg, rgba(0, 0, 0, 0.06));
|
|
384
|
+
border-radius: 4px;
|
|
385
|
+
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.08));
|
|
386
|
+
height: 100%;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
.ml-cli-close-btn {
|
|
390
|
+
width: 18px;
|
|
391
|
+
height: 16px;
|
|
392
|
+
display: inline-flex;
|
|
393
|
+
align-items: center;
|
|
394
|
+
justify-content: center;
|
|
395
|
+
font-weight: 700;
|
|
396
|
+
color: var(--ml-ui-text, #222);
|
|
397
|
+
font-size: 12px;
|
|
398
|
+
background: transparent;
|
|
399
|
+
cursor: pointer;
|
|
400
|
+
padding: 0;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
.ml-cli-close-btn:hover {
|
|
404
|
+
background: var(--ml-ui-border, rgba(0, 0, 0, 0.10));
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
.ml-cli-down,
|
|
408
|
+
.ml-cli-up {
|
|
409
|
+
width: 16px;
|
|
410
|
+
height: 16px;
|
|
411
|
+
display: inline-flex;
|
|
412
|
+
align-items: center;
|
|
413
|
+
justify-content: center;
|
|
414
|
+
border-radius: 3px;
|
|
415
|
+
background: transparent;
|
|
416
|
+
border: none;
|
|
417
|
+
cursor: pointer;
|
|
418
|
+
font-size: 16px;
|
|
419
|
+
color: var(--ml-ui-text, #222);
|
|
420
|
+
padding: 0;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
.ml-cli-up {
|
|
424
|
+
transform: rotate(180deg);
|
|
425
|
+
transform-origin: center;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
.ml-cli-right {
|
|
429
|
+
display: flex;
|
|
430
|
+
align-items: center;
|
|
431
|
+
justify-content: center;
|
|
432
|
+
background: var(--ml-ui-bg, rgba(0, 0, 0, 0.06));
|
|
433
|
+
border-radius: 4px;
|
|
434
|
+
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.08));
|
|
435
|
+
height: 100%;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
.ml-cli-center {
|
|
439
|
+
display: flex;
|
|
440
|
+
align-items: center;
|
|
441
|
+
flex: 1;
|
|
442
|
+
min-width: 0;
|
|
443
|
+
overflow: hidden;
|
|
444
|
+
color: var(--ml-ui-text-muted, #333);
|
|
445
|
+
height: 100%;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
.ml-cli-prompt {
|
|
449
|
+
display: flex;
|
|
450
|
+
align-items: center;
|
|
451
|
+
white-space: nowrap;
|
|
452
|
+
flex: 0 1 auto;
|
|
453
|
+
min-width: 0;
|
|
454
|
+
max-width: calc(100% - 80px);
|
|
455
|
+
overflow: hidden;
|
|
456
|
+
user-select: none;
|
|
457
|
+
margin-right: 4px;
|
|
458
|
+
line-height: 1;
|
|
459
|
+
font-family: "Microsoft YaHei", "PingFang SC", "Segoe UI", Arial, sans-serif;
|
|
460
|
+
font-size: 12px;
|
|
461
|
+
letter-spacing: 0;
|
|
462
|
+
word-spacing: 0;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
.ml-cli-text {
|
|
466
|
+
flex: 1;
|
|
467
|
+
min-width: 76px;
|
|
468
|
+
height: 100%;
|
|
469
|
+
border: none;
|
|
470
|
+
outline: none;
|
|
471
|
+
background: transparent;
|
|
472
|
+
|
|
473
|
+
font-family: "Microsoft YaHei", "PingFang SC", "Segoe UI", Arial, sans-serif;
|
|
474
|
+
font-size: 13px;
|
|
475
|
+
line-height: 1;
|
|
476
|
+
letter-spacing: 0;
|
|
477
|
+
word-spacing: 0;
|
|
478
|
+
padding: 0;
|
|
479
|
+
margin: 0;
|
|
480
|
+
|
|
481
|
+
display: flex;
|
|
482
|
+
align-items: center;
|
|
483
|
+
color: var(--ml-ui-text-muted, #333);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
.ml-cli-option {
|
|
487
|
+
display: inline-block;
|
|
488
|
+
background: var(--ml-ui-bg, #f7f7f7);
|
|
489
|
+
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.06));
|
|
490
|
+
padding: 1px 4px;
|
|
491
|
+
border-radius: 3px;
|
|
492
|
+
margin: 0 1px;
|
|
493
|
+
cursor: pointer;
|
|
494
|
+
font-size: 12px;
|
|
495
|
+
line-height: 1.1;
|
|
496
|
+
letter-spacing: 0;
|
|
497
|
+
word-spacing: 0;
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
.ml-cli-option:hover {
|
|
501
|
+
background: var(--ml-ui-border, #eaeaea);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
.ml-cli-cmd-popup {
|
|
505
|
+
position: absolute;
|
|
506
|
+
bottom: 100%;
|
|
507
|
+
left: 0;
|
|
508
|
+
transform: translate(0, 0);
|
|
509
|
+
max-height: 220px;
|
|
510
|
+
overflow-y: auto;
|
|
511
|
+
background: var(--ml-ui-bg, #333);
|
|
512
|
+
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.5));
|
|
513
|
+
box-shadow: var(--ml-ui-shadow, 0 6px 18px rgba(0, 0, 0, 0.35));
|
|
514
|
+
border-radius: 4px;
|
|
515
|
+
padding: 6px 0;
|
|
516
|
+
color: var(--ml-ui-text, #fff);
|
|
517
|
+
z-index: 3;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
.ml-cli-cmd-popup .item {
|
|
521
|
+
padding: 8px 14px;
|
|
522
|
+
cursor: pointer;
|
|
523
|
+
color: var(--ml-ui-text, #fff);
|
|
524
|
+
font-size: 14px;
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
.ml-cli-cmd-popup .item:hover {
|
|
528
|
+
background: var(--ml-ui-border, #444);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
.ml-cli-msg-panel {
|
|
532
|
+
position: absolute;
|
|
533
|
+
bottom: 100%;
|
|
534
|
+
left: 0;
|
|
535
|
+
transform: translate(0, 0);
|
|
536
|
+
max-height: 340px;
|
|
537
|
+
overflow-y: auto;
|
|
538
|
+
background: var(--ml-ui-bg, #333);
|
|
539
|
+
border: 1px solid var(--ml-ui-border, rgba(0, 0, 0, 0.5));
|
|
540
|
+
box-shadow: var(--ml-ui-shadow, 0 6px 18px rgba(0, 0, 0, 0.35));
|
|
541
|
+
border-radius: 4px;
|
|
542
|
+
padding: 6px 0;
|
|
543
|
+
font-family: "Microsoft YaHei", Arial, sans-serif;
|
|
544
|
+
color: var(--ml-ui-text, #fff);
|
|
545
|
+
font-size: 14px;
|
|
546
|
+
white-space: pre-wrap;
|
|
547
|
+
line-height: 1.35;
|
|
548
|
+
z-index: 4;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
.ml-cli-history-line {
|
|
552
|
+
padding: 4px 6px;
|
|
553
|
+
color: var(--ml-ui-text, #fff);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
.ml-cli-msg-error {
|
|
557
|
+
color: var(--ml-ui-danger, #ff5555);
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
.ml-cli-wrapper {
|
|
561
|
+
position: relative;
|
|
562
|
+
width: 100%;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
.ml-cli-recent {
|
|
566
|
+
position: absolute;
|
|
567
|
+
left: 0;
|
|
568
|
+
bottom: calc(100% + 8px);
|
|
569
|
+
display: flex;
|
|
570
|
+
flex-direction: column;
|
|
571
|
+
align-items: flex-start;
|
|
572
|
+
gap: 4px;
|
|
573
|
+
pointer-events: none;
|
|
574
|
+
z-index: 2;
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
.ml-cli-recent-line {
|
|
578
|
+
display: inline-block;
|
|
579
|
+
max-width: 100%;
|
|
580
|
+
overflow: hidden;
|
|
581
|
+
text-overflow: ellipsis;
|
|
582
|
+
white-space: nowrap;
|
|
583
|
+
color: rgba(230, 233, 238, 0.95);
|
|
584
|
+
background: rgba(45, 48, 54, 0.88);
|
|
585
|
+
border-radius: 4px;
|
|
586
|
+
padding: 4px 8px;
|
|
587
|
+
font-family: "Microsoft YaHei", "PingFang SC", "Segoe UI", Arial, sans-serif;
|
|
588
|
+
font-size: 12px;
|
|
589
|
+
line-height: 1.25;
|
|
590
|
+
letter-spacing: 0;
|
|
591
|
+
word-spacing: 0;
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
.ml-cli-recent-covered {
|
|
595
|
+
opacity: 0;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
.hidden {
|
|
599
|
+
display: none !important;
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
.ml-cli-cmd-popup::-webkit-scrollbar,
|
|
603
|
+
.ml-cli-msg-panel::-webkit-scrollbar {
|
|
604
|
+
width: 10px;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
.ml-cli-cmd-popup::-webkit-scrollbar-thumb,
|
|
608
|
+
.ml-cli-msg-panel::-webkit-scrollbar-thumb {
|
|
609
|
+
background: var(--ml-ui-border, rgba(255, 255, 255, 0.2));
|
|
610
|
+
border-radius: 6px;
|
|
611
|
+
}
|
|
612
|
+
`,document.head.appendChild(e)}createUI(){this.cliContainer=document.createElement("div"),this.cliContainer.className="ml-cli-container",this.cliContainer.style.position=this.useViewportPositioning()?"fixed":"absolute",this.useViewportPositioning()||getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.wrapper=document.createElement("div"),this.wrapper.className="ml-cli-wrapper",this.cliContainer.appendChild(this.wrapper),this.recentPanel=document.createElement("div"),this.recentPanel.className="ml-cli-recent",this.wrapper.appendChild(this.recentPanel),this.bar=document.createElement("div"),this.bar.className="ml-cli-bar",this.wrapper.appendChild(this.bar),this.leftGroup=document.createElement("div"),this.leftGroup.className="ml-cli-left",this.bar.appendChild(this.leftGroup),this.closeBtn=document.createElement("div"),this.closeBtn.className="ml-cli-close-btn",this.closeBtn.innerHTML="✕",this.leftGroup.appendChild(this.closeBtn),this.downBtn=document.createElement("button"),this.downBtn.className="ml-cli-down",this.downBtn.innerHTML="▾",this.leftGroup.appendChild(this.downBtn),this.centerEl=document.createElement("div"),this.centerEl.className="ml-cli-center",this.bar.appendChild(this.centerEl),this.promptEl=document.createElement("div"),this.promptEl.className="ml-cli-prompt",this.centerEl.appendChild(this.promptEl),this.textInput=document.createElement("input"),this.textInput.className="ml-cli-text",this.textInput.type="text",this.textInput.spellcheck=!1,this.textInput.autocomplete="off",this.textInput.placeholder=this.localize("main.commandLine.placeholder"),this.centerEl.appendChild(this.textInput);const e=document.createElement("div");e.className="ml-cli-right",this.bar.appendChild(e),this.upBtn=document.createElement("button"),this.upBtn.className="ml-cli-up",this.upBtn.innerHTML="▾",e.appendChild(this.upBtn),this.cmdPopup=document.createElement("div"),this.cmdPopup.className="ml-cli-cmd-popup hidden",this.wrapper.appendChild(this.cmdPopup),this.msgPanel=document.createElement("div"),this.msgPanel.className="ml-cli-msg-panel hidden",this.wrapper.appendChild(this.msgPanel),this.container.appendChild(this.cliContainer)}bindEvents(){this.closeBtn.addEventListener("click",e=>{e.stopPropagation(),this.visible=!1,me.instance.isShowCommandLine=!1}),this.downBtn.addEventListener("click",e=>{e.stopPropagation(),this.isCmdPopupOpen=!this.isCmdPopupOpen,this.updatePopups({showCmd:this.isCmdPopupOpen,showMsg:!1}),this.isCmdPopupOpen&&this.showCommandHistoryPopup()}),this.upBtn.addEventListener("click",e=>{e.stopPropagation(),this.isMsgPanelOpen=!this.isMsgPanelOpen,this.updatePopups({showCmd:!1,showMsg:this.isMsgPanelOpen}),this.isMsgPanelOpen&&this.showMessagePanel()}),document.addEventListener("click",e=>{this.cliContainer.contains(e.target)||this.updatePopups({showCmd:!1,showMsg:!1})}),this.textInput.addEventListener("keydown",e=>this.handleKeyDown(e)),this.textInput.addEventListener("input",()=>this.handleInputChange()),this.centerEl.addEventListener("focus",()=>this.updatePopups({showCmd:!1,showMsg:!1})),this.cmdPopup.addEventListener("click",e=>{const t=e.target.closest(".item");t&&(this.setInputText(t.dataset.value||""),this.centerEl.focus(),this.updatePopups({showCmd:!1,showMsg:!1}))})}handleKeyDown(e){if(!e.isComposing)switch(e.key){case"Enter":{if(e.preventDefault(),e.stopImmediatePropagation(),this.activeSession){this.activeSession.handleEnter(this.getInputText())||this.showMessage(this.localize("main.commandLine.invalidKeyword"),"warning");return}this.executeCommand(this.getInputText()),this.historyIndex=this.history.length,this.updatePopups({showCmd:!1,showMsg:!1});return}case"Escape":{if(e.preventDefault(),e.stopImmediatePropagation(),this.activeSession){this.activeSession.handleEscape(),this.activeSession=void 0;return}this.clear(),this.showMessage(this.localize("main.commandLine.canceled")),this.updatePopups({showCmd:!1,showMsg:!1});return}case"ArrowUp":{e.preventDefault(),this.isCmdPopupOpen?this.navigateAutoComplete(-1):this.navigateHistory(-1);return}case"ArrowDown":{e.preventDefault(),this.isCmdPopupOpen?this.navigateAutoComplete(1):this.navigateHistory(1);return}case"Backspace":case"Delete":{e.stopPropagation(),e.stopImmediatePropagation();return}}}handleInputChange(){const e=this.getInputText();if(!e){this.updatePopups({showCmd:!1});return}const t=A.instance.searchCommandsByPrefix(e);t.length?(this.autoCompleteIndex=-1,this.cmdPopup.innerHTML="",t.forEach((i,n)=>{const s=document.createElement("div");s.className="item",s.dataset.value=i.command.globalName;const r=g.cmdDescription(i.commandGroup,i.command.globalName),a=A.instance.commandManager.getCommandAliases(i.command,i.commandGroup),c=a.length?`(${a.join(", ")})`:"";s.innerHTML=`<strong>${i.command.globalName}${c} - ${r}</strong>`,n===this.autoCompleteIndex&&s.classList.add("selected"),this.cmdPopup.appendChild(s)}),this.updatePopups({showCmd:!0})):this.updatePopups({showCmd:!1})}navigateAutoComplete(e){const t=Array.from(this.cmdPopup.querySelectorAll(".item"));if(!t.length)return;this.autoCompleteIndex+=e,this.autoCompleteIndex<0&&(this.autoCompleteIndex=0),this.autoCompleteIndex>=t.length&&(this.autoCompleteIndex=t.length-1),t.forEach((n,s)=>{n.classList.toggle("selected",s===this.autoCompleteIndex)});const i=t[this.autoCompleteIndex];i&&this.setInputText(i.dataset.value??"")}navigateHistory(e){this.history.length&&(this.historyIndex===-1&&(this.historyIndex=this.history.length),this.historyIndex+=e,this.historyIndex<0&&(this.historyIndex=0),this.historyIndex>this.history.length&&(this.historyIndex=this.history.length),this.historyIndex>=0&&this.historyIndex<this.history.length?this.setInputText(this.history[this.historyIndex]):this.setInputText(""))}getInputText(){return this.textInput.value.trim()}setInputText(e=""){this.textInput.value=e,this.textInput.focus()}renderKeywordPrompt(e,t){var s;this.promptEl.innerHTML="",this.isPromptActive=!0,this.textInput.placeholder="",e.message&&this.promptEl.append(e.message.trim()+" ");const i=e.getKeywordPromptFormat();if(!i.visibleKeywords.length)return;const n=(s=e.keywords)==null?void 0:s.toArray().filter(r=>r.visible);n!=null&&n.length&&(this.promptEl.append("["),n.forEach((r,a)=>{a>0&&this.promptEl.append("/");const c=document.createElement("span");c.className="ml-cli-option",c.textContent=r.displayName,r.enabled?c.onclick=()=>t(r.globalName):(c.style.opacity="0.45",c.style.pointerEvents="none"),this.promptEl.append(c)}),this.promptEl.append("]"),i.defaultKeyword&&this.promptEl.append(` <${i.defaultKeyword}>`),this.promptEl.append(": "),this.recordRecentMessage(this.promptEl.textContent??e.message))}bindCommandLifecycleEvents(){if(this.isCommandLifecycleBound)return;let e;try{e=A.instance.editor.events}catch{setTimeout(()=>this.bindCommandLifecycleEvents(),0);return}e.commandWillStart.addEventListener(()=>{this.cancelRecentAutoHide(),this.showRecentPanel()}),e.commandEnded.addEventListener(()=>{this.scheduleRecentAutoHide()}),this.isCommandLifecycleBound=!0}resolveCommand(e){const i=e.trim().split(/\s+/)[0].toUpperCase();return A.instance.lookupLocalCmd(i)}updatePopups({showCmd:e=!1,showMsg:t=!1}={}){this.isCmdPopupOpen=e,this.isMsgPanelOpen=t,this.cmdPopup.classList.toggle("hidden",!e),this.msgPanel.classList.toggle("hidden",!t),this.recentPanel.classList.toggle("ml-cli-recent-covered",t),e&&this.positionCmdPopup(),t&&this.positionMsgPanel()}showCommandHistoryPopup(){if(this.cmdPopup.innerHTML="",this.history.length)for(let e=this.history.length-1;e>=0;e--){const t=document.createElement("div");t.className="item",t.dataset.value=this.history[e],t.textContent=this.history[e],this.cmdPopup.appendChild(t)}else{const e=document.createElement("div");e.className="item",e.textContent=this.localize("main.commandLine.noHistory"),this.cmdPopup.appendChild(e)}this.positionCmdPopup()}positionCmdPopup(){this.cmdPopup.style.left="0px",this.cmdPopup.style.width=this.bar.offsetWidth+"px"}showMessagePanel(){if(!this.msgPanel.children.length){const e=document.createElement("div");e.className="ml-cli-history-line",e.textContent=this.localize("main.commandLine.noHistory"),e.dataset.msgKey="main.commandLine.noHistory",this.msgPanel.appendChild(e)}this.msgPanel.scrollTop=this.msgPanel.scrollHeight,this.positionMsgPanel()}positionMsgPanel(){this.msgPanel.style.width=this.bar.offsetWidth+"px"}clearNoHistoryPlaceholder(){Array.from(this.msgPanel.children).forEach(e=>{const t=e;t.dataset.msgKey==="main.commandLine.noHistory"&&this.msgPanel.removeChild(t)})}appendMessage(e,t="info",i){this.clearNoHistoryPlaceholder();const n=document.createElement("div");n.className=t==="warning"?"ml-cli-history-line ml-cli-msg-error":"ml-cli-history-line",n.textContent=e,i&&(n.dataset.msgKey=i),this.msgPanel.appendChild(n),this.recordRecentMessage(e),this.showMessagePanel()}printHistoryLine(e){this.clearNoHistoryPlaceholder();const t=document.createElement("div");t.className="ml-cli-history-line",t.textContent="> "+e,t.dataset.msgKey="main.commandLine.executed",this.msgPanel.appendChild(t),this.showMessagePanel()}resizeHandler(){const e=this.useViewportPositioning()?window.innerWidth:this.container.getBoundingClientRect().width;let t=Math.max(this.minWidth,e*this.widthRatio);t=Math.min(t,Math.max(200,e-20)),this.bar.style.width=t+"px",this.recentPanel.style.width=t+"px",this.positionMsgPanel(),this.positionCmdPopup()}recordRecentMessage(e){const t=e==null?void 0:e.replace(/\s+/g," ").trim();t&&(this.recentMessages.push(t),this.recentMessages.length>2&&this.recentMessages.shift(),this.showRecentPanel(),this.renderRecentMessages())}renderRecentMessages(){this.recentPanel.innerHTML="",this.recentMessages.forEach(e=>{const t=document.createElement("div");t.className="ml-cli-recent-line",t.textContent=e,this.recentPanel.appendChild(t)})}scheduleRecentAutoHide(){this.cancelRecentAutoHide(),this.recentHideTimer=setTimeout(()=>{this.hideRecentPanel(),this.recentHideTimer=void 0},2e3)}cancelRecentAutoHide(){this.recentHideTimer&&(clearTimeout(this.recentHideTimer),this.recentHideTimer=void 0)}showRecentPanel(){this.recentPanel.classList.remove("hidden")}hideRecentPanel(){this.recentPanel.classList.add("hidden")}useViewportPositioning(){return this.container===document.body}}class pl{constructor(e){this.options=e}parse(e){const t=Number(e);return isNaN(t)||!this.options.allowNegative&&t<0||!this.options.allowZero&&t===0?null:t}}class Ln{constructor(e){this.options=e}parse(e){const t=Number(e);return isNaN(t)||!this.options.allowNegative&&t<0||!this.options.allowZero&&t===0?null:t}}class ml extends Ln{}class fl extends Ln{}class ur extends Ln{constructor(e){super(e)}parse(e){const t=super.parse(e);return t==null?t:!Number.isInteger(t)||this.options.lowerLimit!==void 0&&t<this.options.lowerLimit||this.options.upperLimit!==void 0&&t>this.options.upperLimit?null:t}}class dr{constructor(e){this.options=e}parse(e,t){const i=Number(e),n=Number(t);return isNaN(i)||isNaN(n)?null:{x:i,y:n,z:0}}}class gr{constructor(e){this.options=e}parse(e){return!this.options.allowSpaces&&e.includes(" ")||!this.options.allowEmpty&&e.length===0||this.options.maxLength&&e.length>this.options.maxLength?null:e}}class Ai{constructor(e="rect",t=12,i="var(--ml-ui-canvas-line, green)",n){this._type=e,this._size=t,this._color=i,this._host=n,Ai.injectCSS(),getComputedStyle(this._host).position==="static"&&(this._host.style.position="relative"),this._el=document.createElement("div"),this._el.classList.add("ml-marker"),this._el.style.color=i,this.applyShape(),this._host.appendChild(this._el)}get color(){return this._color}set color(e){this._color=e,this._el.style.color=e}get type(){return this._type}set type(e){this._type=e,this.applyShape()}static injectCSS(){if(document.getElementById("ml-marker-style"))return;const e=document.createElement("style");e.id="ml-marker-style",e.textContent=`
|
|
613
|
+
.ml-marker {
|
|
614
|
+
position: absolute;
|
|
615
|
+
pointer-events: none;
|
|
616
|
+
transform: translate(-50%, -50%);
|
|
617
|
+
z-index: 1;
|
|
618
|
+
box-sizing: border-box;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
.ml-marker-circle {
|
|
622
|
+
border-radius: 50%;
|
|
623
|
+
border: 2px solid currentColor;
|
|
624
|
+
background: transparent;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
.ml-marker-rect {
|
|
628
|
+
border: 2px solid currentColor;
|
|
629
|
+
background: transparent;
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
.ml-marker-triangle {
|
|
633
|
+
background: currentColor;
|
|
634
|
+
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
|
|
635
|
+
/* Centroid of the upward triangle is 2/3 of the height from the apex. */
|
|
636
|
+
transform: translate(-50%, -66.6667%);
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
.ml-marker-diamond {
|
|
640
|
+
border: 2px solid currentColor;
|
|
641
|
+
background: transparent;
|
|
642
|
+
transform: translate(-50%, -50%) rotate(45deg);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
.ml-marker-x::before,
|
|
646
|
+
.ml-marker-x::after {
|
|
647
|
+
content: '';
|
|
648
|
+
position: absolute;
|
|
649
|
+
top: 50%;
|
|
650
|
+
left: 50%;
|
|
651
|
+
width: 100%;
|
|
652
|
+
height: 2px;
|
|
653
|
+
background: currentColor;
|
|
654
|
+
transform-origin: center;
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
.ml-marker-x::before {
|
|
658
|
+
transform: translate(-50%, -50%) rotate(45deg);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
.ml-marker-x::after {
|
|
662
|
+
transform: translate(-50%, -50%) rotate(-45deg);
|
|
663
|
+
}
|
|
664
|
+
`,document.head.appendChild(e)}applyShape(){switch(this._el.className="ml-marker",this._el.style.width="",this._el.style.height="",this._el.style.fontSize="",this._el.style.transform="translate(-50%, -50%)",this._type){case"circle":this._el.classList.add("ml-marker-circle"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"rect":this._el.classList.add("ml-marker-rect"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"triangle":this._el.classList.add("ml-marker-triangle"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"diamond":this._el.classList.add("ml-marker-diamond"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break;case"x":this._el.classList.add("ml-marker-x"),this._el.style.width=`${this._size}px`,this._el.style.height=`${this._size}px`;break}}setPosition(e){this._el.style.left=`${e.x}px`,this._el.style.top=`${e.y}px`}destroy(){this._el.remove()}}class pr{constructor(e){this.stack=[],this.view=e}showMarker(e,t,i,n){const s=this.view.worldToScreen(e),r=this.view.canvasToContainer(s),a=new Ai(t,i,n,this.view.container);return a.setPosition(r),this.stack.push(a),a}repositionTop(e){const t=this.top();if(!t)return;const i=this.view.worldToScreen(e),n=this.view.canvasToContainer(i);t.setPosition(n)}hideMarker(){const e=this.stack.pop();e&&e.destroy()}clear(){for(const e of this.stack)e.destroy();this.stack=[]}top(){return this.stack[this.stack.length-1]}}class mr{constructor(e){this.userTyped=!1,this.parent=e,this.input=document.createElement("input"),this.input.type="text",this.boundOnInput=()=>{this.userTyped=!0,this.resetValidation()},this.input.addEventListener("input",this.boundOnInput),this.parent.appendChild(this.input)}markInvalid(){this.input.classList.add("invalid")}markValid(){this.input.classList.remove("invalid")}resetValidation(){this.input.classList.remove("invalid")}get placeholder(){return this.input.placeholder}set placeholder(e){e&&(this.input.placeholder=e)}set value(e){e!==void 0&&(this.input.value=e)}get value(){return this.input.value}get focused(){return document.activeElement===this.input}focus(){this.input.focus()}blur(){this.input.blur()}select(){this.input.select()}remove(){this.input.remove()}isEventTarget(e){return e.target===this.input}dispose(){this.input.removeEventListener("input",this.boundOnInput),this.remove()}addEventListener(e,t,i){this.input.addEventListener(e,t,i)}removeEventListener(e,t,i){this.input.removeEventListener(e,t,i)}}class yl{constructor(e){this.parent=e.parent,this.twoInputs=e.twoInputs??!0,this.boundOnInput=()=>this.handleInput(),this.boundOnKeyDown=t=>this.handleKeyDown(t),this.xInput=new mr(this.parent),this.xInput.addEventListener("input",this.boundOnInput),this.xInput.addEventListener("keydown",this.boundOnKeyDown),this.twoInputs&&(this.yInput=new mr(this.parent),this.yInput.addEventListener("input",this.boundOnInput),this.yInput.addEventListener("keydown",this.boundOnKeyDown)),this.validateFn=e.validate,this.onCommit=e.onCommit,this.onChange=e.onChange,this.onCancel=e.onCancel,this.onNone=e.onNone,this.allowNone=e.allowNone??!1,this.useDefaultValue=e.useDefaultValue??!1,this.defaultValue=e.defaultValue,e.autoFocus!==!1&&setTimeout(()=>{this.yInput&&this.yInput.select(),this.xInput.focus(),this.xInput.select()},0)}get userTyped(){var e;return this.xInput.userTyped||!!((e=this.yInput)!=null&&e.userTyped)}get focused(){var e;return this.xInput.focused||((e=this.yInput)==null?void 0:e.focused)}focus(){this.xInput.focus()}blur(){var e;this.xInput.blur(),(e=this.yInput)==null||e.blur()}setValue(e){this.xInput.userTyped||(this.xInput.value=e.x),this.twoInputs&&this.yInput&&!this.yInput.userTyped&&(this.yInput.value=e.y??"")}dispose(){var e;this.xInput.removeEventListener("input",this.boundOnInput),this.xInput.removeEventListener("keydown",this.boundOnKeyDown),this.xInput.dispose(),this.yInput&&(this.yInput.removeEventListener("input",this.boundOnInput),this.yInput.removeEventListener("keydown",this.boundOnKeyDown),(e=this.yInput)==null||e.dispose())}handleInput(){var t;const e=this.validate();(t=this.onChange)==null||t.call(this,e)}handleKeyDown(e){var n,s,r;let t=this.xInput,i=this.yInput;if(this.yInput&&this.yInput.isEventTarget(e)&&(t=this.yInput,i=this.xInput),e.key==="Enter"){if(this.useDefaultValue&&!this.userTyped){!this.onCommit||this.onCommit(this.defaultValue)?t.markValid():t.markInvalid(),e.preventDefault(),e.stopPropagation();return}if(this.allowNone&&!this.userTyped)(n=this.onNone)==null||n.call(this);else{const a=this.validate();a.isValid&&a.value!=null?((s=this.onCommit)==null||s.call(this,a.value),t.markValid()):t.markInvalid()}e.preventDefault(),e.stopPropagation()}else e.key==="Escape"?((r=this.onCancel)==null||r.call(this),e.preventDefault(),e.stopPropagation()):e.key==="Tab"&&(e.preventDefault(),i&&(i==null||i.focus(),i==null||i.select()))}validate(){const e=this.xInput.value.trim(),t=this.twoInputs&&this.yInput?this.yInput.value.trim():void 0;return this.validateFn({x:e,y:t})}}const Ht=class Ht{constructor(e,t){this.visible=!1,this.disposed=!1,this.isHovering=!1,this.view=e,this.parent=t.parent??this.view.canvas,this.host=this.view.container,getComputedStyle(this.host).position==="static"&&(this.host.style.position="relative"),this.container=document.createElement("div"),this.container.className="ml-floating-input",this.allowPrompt=t.allowPrompt!==!1;const n=t.message??"";this.label=document.createElement("span"),this.label.className="ml-floating-input-label",this.label.textContent=n,n.trim()||(this.label.style.display="none"),this.container.appendChild(this.label),this.host.appendChild(this.container),this.boundOnMouseEnter=s=>this.handleMouseEnter(s),this.boundOnMouseLeave=()=>this.handleMouseLeave(),this.boundOnMouseMove=s=>this.handleMouseMove(s),this.parent.addEventListener("mouseenter",this.boundOnMouseEnter),this.parent.addEventListener("mouseleave",this.boundOnMouseLeave),this.boundOnSysVarChanged=s=>{var a;const r=(a=s.name)==null?void 0:a.toLowerCase();(r===u.AcDbSystemVariables.DYNMODE.toLowerCase()||r===u.AcDbSystemVariables.DYNPROMPT.toLowerCase())&&this.updateDynamicDisplay()},u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.boundOnSysVarChanged),this.updateDynamicDisplay(),this.injectCSS()}injectCSS(){if(Ht.stylesInjected)return;Ht.stylesInjected=!0;const e=document.createElement("style");e.textContent=`
|
|
665
|
+
.ml-floating-input {
|
|
666
|
+
position: absolute;
|
|
667
|
+
display: flex;
|
|
668
|
+
align-items: center;
|
|
669
|
+
padding: 2px 4px;
|
|
670
|
+
background: var(--ml-ui-bg, #444);
|
|
671
|
+
color: var(--ml-ui-text, #fff);
|
|
672
|
+
border-radius: 4px;
|
|
673
|
+
font-size: 12px;
|
|
674
|
+
pointer-events: none;
|
|
675
|
+
z-index: 2;
|
|
676
|
+
}
|
|
677
|
+
.ml-floating-input-label {
|
|
678
|
+
white-space: nowrap;
|
|
679
|
+
color: var(--ml-ui-text, #fff);
|
|
680
|
+
}
|
|
681
|
+
`,document.head.appendChild(e)}get isVisible(){return this.visible}showAt(e){this.disposed||this.shouldShowPrompt()&&(this.visible=!0,this.container.style.display="flex",this.setPosition(e),this.parent.addEventListener("mousemove",this.boundOnMouseMove))}hide(){this.visible&&(this.visible=!1,this.container.style.display="none",this.parent.removeEventListener("mousemove",this.boundOnMouseMove))}dispose(){this.disposed||(this.disposed=!0,this.hide(),this.parent.removeEventListener("mouseenter",this.boundOnMouseEnter),this.parent.removeEventListener("mouseleave",this.boundOnMouseLeave),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.boundOnSysVarChanged),this.container.remove())}setPosition(e){const t=this.host.getBoundingClientRect(),i=this.container.getBoundingClientRect(),n=this.view.viewportToCanvas(e),s=this.view.viewportToContainer(e);let r=s.x+10,a=s.y+10;return r=Math.min(r,t.width-i.width),a=Math.min(a,t.height-i.height),r=Math.max(r,0),a=Math.max(a,0),this.container.style.left=`${r}px`,this.container.style.top=`${a}px`,n}handleMouseEnter(e){this.isHovering=!0,this.showAt(e)}handleMouseLeave(){this.isHovering=!1,this.hide()}handleMouseMove(e){this.visible&&this.setPosition(e)}getSysVarValue(e){const t=u.acdbHostApplicationServices().workingDatabase;return u.AcDbSysVarManager.instance().getVar(e,t)}isDynamicInputEnabled(){return this.getSysVarValue(u.AcDbSystemVariables.DYNMODE)!==0}isDynamicPromptEnabled(){return!!this.getSysVarValue(u.AcDbSystemVariables.DYNPROMPT)}shouldShowPrompt(){var t;return!(!!!((t=this.label.textContent)!=null&&t.trim())||!this.allowPrompt||!this.isDynamicInputEnabled()||!this.isDynamicPromptEnabled())}updateDynamicDisplay(){if(!this.shouldShowPrompt()){this.hide();return}this.isHovering&&this.showAt(this.view.canvasToViewport(this.view.curMousePos))}};Ht.stylesInjected=!1;let Et=Ht;class fr{constructor(e){this.container=null,this.baseLine=null,this.perpLineAtBase=null,this.perpLineAtCursor=null,this.connectorLine=null,this.labelEl=null,this.angleLabelEl=null,this.xAxisLine=null,this.angleSvg=null,this.anglePath=null,this.options={},this.view=e}get element(){return this.container}toContainerPoint(e){return this.view.canvasToContainer(this.view.worldToScreen(e))}ensureHostPositioned(){const e=this.view.container;getComputedStyle(e).position==="static"&&(e.style.position="relative")}start(e,t){this.basePoint=new u.AcGePoint3d(e),this.options=t||{};const i=this.options.color||"var(--ml-ui-canvas-line, #0f0)";this.ensureHostPositioned(),this.container=document.createElement("div"),this.container.style.position="absolute",this.container.style.left="0",this.container.style.top="0",this.container.style.width="100%",this.container.style.height="100%",this.container.style.pointerEvents="none",this.container.style.zIndex="1",this.view.container.appendChild(this.container),this.baseLine=document.createElement("div"),this.baseLine.style.position="absolute",this.baseLine.style.borderTop=`1px solid ${i}`,this.container.appendChild(this.baseLine);const n=()=>{const s=document.createElement("div");return s.style.position="absolute",s.style.borderTop=`1px dashed ${i}`,this.container.appendChild(s),s};this.options.showBaseLineOnly||(this.perpLineAtBase=n(),this.perpLineAtCursor=n(),this.connectorLine=n(),this.labelEl=document.createElement("div"),this.labelEl.style.position="absolute",this.labelEl.style.color=i,this.labelEl.style.fontSize="12px",this.labelEl.style.padding="2px 4px",this.labelEl.style.borderRadius="4px",this.container.appendChild(this.labelEl),this.xAxisLine=document.createElement("div"),this.xAxisLine.style.position="absolute",this.xAxisLine.style.borderTop=`1px solid ${i}`,this.container.appendChild(this.xAxisLine),this.angleSvg=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.angleSvg.setAttribute("style","position:absolute; overflow:visible; pointer-events:none;"),this.anglePath=document.createElementNS("http://www.w3.org/2000/svg","path"),this.anglePath.setAttribute("fill","none"),this.anglePath.setAttribute("stroke",i),this.anglePath.setAttribute("stroke-width","1"),this.anglePath.setAttribute("stroke-dasharray","4 4"),this.angleSvg.appendChild(this.anglePath),this.container.appendChild(this.angleSvg),this.angleLabelEl=document.createElement("div"),this.angleLabelEl.style.position="absolute",this.angleLabelEl.style.color=i,this.angleLabelEl.style.fontSize="12px",this.angleLabelEl.style.padding="2px 4px",this.angleLabelEl.style.borderRadius="4px",this.container.appendChild(this.angleLabelEl))}update(e){var m,f;if(!this.container||!this.basePoint||!this.baseLine)return;const t=this.toContainerPoint(this.basePoint),i=this.toContainerPoint(e),n=(w,x,b)=>{const v=b.x-x.x,C=b.y-x.y,P=Math.sqrt(v*v+C*C),L=Math.atan2(C,v)*(180/Math.PI);w.style.width=`${P}px`,w.style.transformOrigin="0 0",w.style.transform=`translate(${x.x}px, ${x.y}px) rotate(${L}deg)`};if(n(this.baseLine,t,i),this.options.showBaseLineOnly||!this.perpLineAtBase||!this.perpLineAtCursor||!this.connectorLine)return;const s=i.x-t.x,r=i.y-t.y,a=Math.sqrt(s*s+r*r);if(a===0){this.perpLineAtBase&&(this.perpLineAtBase.style.width="0px"),this.perpLineAtCursor&&(this.perpLineAtCursor.style.width="0px"),this.connectorLine&&(this.connectorLine.style.width="0px"),this.xAxisLine&&(this.xAxisLine.style.width="0px"),this.anglePath&&this.anglePath.setAttribute("d",""),this.angleLabelEl&&(this.angleLabelEl.style.display="none");return}const c=this.options.perpendicularLength??50,l=-r/a,h=s/a,d={x:t.x+l*c,y:t.y+h*c},p={x:i.x+l*c,y:i.y+h*c};if(n(this.perpLineAtBase,t,d),n(this.perpLineAtCursor,i,p),n(this.connectorLine,d,p),this.labelEl){const w=(d.x+p.x)/2,x=(d.y+p.y)/2-24,b=Math.sqrt((e.x-this.basePoint.x)**2+(e.y-this.basePoint.y)**2),v=(m=A.instance.curDocument)==null?void 0:m.database;this.labelEl.textContent=v?v.formatter.formatLength(b):b.toFixed(3),this.labelEl.style.left=`${w-20}px`,this.labelEl.style.top=`${x}px`,this.labelEl.style.display=""}if(this.xAxisLine){const w=(this.options.baseAngle??0)*Math.PI/180,x={x:this.basePoint.x+Math.cos(w),y:this.basePoint.y+Math.sin(w),z:0},b=this.toContainerPoint(x),v=Math.atan2(b.y-t.y,b.x-t.x),C={x:t.x+a*Math.cos(v),y:t.y+a*Math.sin(v)};n(this.xAxisLine,t,C)}if(this.angleSvg&&this.anglePath&&this.angleLabelEl){const w=a,x=t.x,b=t.y,v=(this.options.baseAngle??0)*Math.PI/180,C={x:this.basePoint.x+Math.cos(v),y:this.basePoint.y+Math.sin(v),z:0},P=this.toContainerPoint(C),L=Math.atan2(P.y-t.y,P.x-t.x);let k=Math.atan2(i.y-t.y,i.x-t.x)-L;for(;k<=-Math.PI;)k+=Math.PI*2;for(;k>Math.PI;)k-=Math.PI*2;const E=L+k/2,T=x-w,F=b-w,O=w*2;this.angleSvg.style.left=`${T}px`,this.angleSvg.style.top=`${F}px`,this.angleSvg.setAttribute("width",`${O}`),this.angleSvg.setAttribute("height",`${O}`),this.angleSvg.setAttribute("viewBox",`0 0 ${O} ${O}`);const z=w,U=w,V=z+w*Math.cos(L),G=U+w*Math.sin(L),K=z+w*Math.cos(L+k),W=U+w*Math.sin(L+k),te=Math.abs(k)>Math.PI?"1":"0",Ae=k>=0?"1":"0",bt=`M ${V} ${G} A ${w} ${w} 0 ${te} ${Ae} ${K} ${W}`;this.anglePath.setAttribute("d",bt);const Ge=Math.abs(k),vt=(f=A.instance.curDocument)==null?void 0:f.database,Qt=vt?vt.formatter.formatAngle(Ge,{showUnits:!0,applyAngbaseAngdir:!1}):`${(Ge*180/Math.PI).toFixed(1)}°`,gs=x+w*Math.cos(E),cn=b+w*Math.sin(E);this.angleLabelEl.textContent=Qt;const ku=40;this.angleLabelEl.style.left=`${gs-ku/2}px`,this.angleLabelEl.style.top=`${cn-12}px`,this.angleLabelEl.style.display=""}}dispose(){this.container&&this.container.remove(),this.container=null,this.baseLine=null,this.perpLineAtBase=null,this.perpLineAtCursor=null,this.connectorLine=null,this.labelEl=null,this.angleLabelEl=null,this.xAxisLine=null,this.angleSvg=null,this.anglePath=null}}const Yt=class Yt extends Et{constructor(e,t){super(e,t),this.lastPoint=null,this.suppressDisplay=!1,this.allowPrompt=t.allowPrompt!==!1,this.suppressDisplay=!this.isDynamicInputEnabled(),this.orthoReferencePoint=t.orthoReferencePoint??t.basePoint??void 0,t.disableOSnap||(this.osnapMarkerManager=new pr(e)),t.basePoint&&(this.rubberBand=new fr(e),this.rubberBand.start(t.basePoint,{color:"var(--ml-ui-canvas-line, #0f0)",showBaseLineOnly:t.showBaseLineOnly,baseAngle:t.baseAngle})),this.validateFn=t.validate,this.getDynamicValue=t.getDynamicValue,this.drawPreview=t.drawPreview,this.onCommit=t.onCommit,this.onChange=t.onChange,this.onCancel=t.onCancel,this.onNone=t.onNone,t.inputCount!==0&&(this.inputs=new yl({parent:this.container,twoInputs:t.inputCount===2,validate:this.validateFn,onCancel:this.onCancel,onNone:this.onNone,onCommit:this.onCommit,onChange:this.onChange,autoFocus:this.isDynamicInputEnabled(),allowNone:t.allowNone,useDefaultValue:t.useDefaultValue,defaultValue:t.defaultValue})),this.boundOnClick=i=>this.handleClick(i),this.parent.addEventListener("click",this.boundOnClick),this.boundOnInputSysVarChanged=i=>{var s;const n=(s=i.name)==null?void 0:s.toLowerCase();n===u.AcDbSystemVariables.DYNMODE.toLowerCase()||n===u.AcDbSystemVariables.DYNPROMPT.toLowerCase()?this.updateDynamicInputDisplay():(n===u.AcDbSystemVariables.ORTHOMODE.toLowerCase()||n===u.AcDbSystemVariables.POLARMODE.toLowerCase()||n===u.AcDbSystemVariables.POLARANG.toLowerCase()||n===u.AcDbSystemVariables.POLARADDANG.toLowerCase())&&this.requestPreviewRefresh()},u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(this.boundOnInputSysVarChanged),this.boundOnViewChanged=()=>this.requestPreviewRefresh(),this.view.events.viewChanged.addEventListener(this.boundOnViewChanged),this.view.events.viewResize.addEventListener(this.boundOnViewChanged),this.updateDynamicInputDisplay(),this.injectInputCSS()}showAt(e){if(this.disposed)return;if(this.updateDynamicInputDisplay(),!this.suppressDisplay){super.showAt(e);const i=this.view.screenToWorld(this.view.viewportToCanvas(e));this.updateDynamicPreview(i);return}this.visible=!0,this.container.style.display="none",this.setPosition(e),this.parent.addEventListener("mousemove",this.boundOnMouseMove);const t=this.view.screenToWorld(this.view.viewportToCanvas(e));this.updateDynamicPreview(t)}injectInputCSS(){if(Yt.inputStylesInjected)return;Yt.inputStylesInjected=!0;const e=document.createElement("style");e.textContent=`
|
|
682
|
+
.ml-floating-input input {
|
|
683
|
+
font-size: 12px;
|
|
684
|
+
padding: 2px 4px;
|
|
685
|
+
margin-left: 6px;
|
|
686
|
+
height: 22px;
|
|
687
|
+
width: 90px;
|
|
688
|
+
background: var(--ml-ui-bg, #888);
|
|
689
|
+
border: 1px solid var(--ml-ui-border, #666);
|
|
690
|
+
color: var(--ml-ui-text, #fff);
|
|
691
|
+
border-radius: 2px;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
.ml-floating-input input.invalid {
|
|
695
|
+
border-color: var(--ml-ui-danger, red);
|
|
696
|
+
color: var(--ml-ui-danger, red);
|
|
697
|
+
}
|
|
698
|
+
`,document.head.appendChild(e)}dispose(){var e,t,i;this.disposed||(super.dispose(),this.parent.removeEventListener("click",this.boundOnClick),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(this.boundOnInputSysVarChanged),this.view.events.viewChanged.removeEventListener(this.boundOnViewChanged),this.view.events.viewResize.removeEventListener(this.boundOnViewChanged),(e=this.inputs)==null||e.dispose(),(t=this.rubberBand)==null||t.dispose(),(i=this.osnapMarkerManager)==null||i.clear())}handleMouseMove(e){if(!this.visible)return;const t=this.getPosition(e);this.updateDynamicPreview(t)}requestPreviewRefresh(){!this.visible||!this.lastDynamicPoint||(this.updateDynamicPreview(this.lastDynamicPoint),this.osnapMarkerManager&&this.lastOsnapPoint&&this.osnapMarkerManager.repositionTop(this.lastOsnapPoint),!this.suppressDisplay&&this.view.curMousePos&&this.setPosition(this.view.canvasToViewport(this.view.curMousePos)))}handleClick(e){var s;if(!this.visible)return;const t=this.getPosition(e),i=this.getDynamicValue(t);(((s=this.onCommit)==null?void 0:s.call(this,i.value,t))??!0)&&(this.lastPoint=t)}setBasePoint(e,t){this.disposed||this.rubberBand||(this.rubberBand=new fr(this.view),this.rubberBand.start(e,{color:(t==null?void 0:t.color)??"var(--ml-ui-canvas-line, #0f0)",showBaseLineOnly:t==null?void 0:t.showBaseLineOnly,baseAngle:t==null?void 0:t.baseAngle}),this.orthoReferencePoint=e,this.requestPreviewRefresh())}updateDynamicPreview(e){var i,n,s;this.lastDynamicPoint={x:e.x,y:e.y};const t=this.getDynamicValue(e);(i=this.inputs)==null||i.setValue(t.raw),this.inputs&&!this.inputs.focused&&!this.suppressDisplay&&this.inputs.focus(),(n=this.rubberBand)==null||n.update(e),(s=this.drawPreview)==null||s.call(this,e)}getPosition(e){const t=super.setPosition(e),i=this.view.screenToWorld(t);if(this.osnapMarkerManager&&(this.osnapMarkerManager.hideMarker(),this.lastOsnapPoint=this.getOsnapPoint(),this.lastOsnapPoint&&(i.x=this.lastOsnapPoint.x,i.y=this.lastOsnapPoint.y,this.osnapMarkerManager.showMarker(this.lastOsnapPoint,this.osnapMode2MarkerType(this.lastOsnapPoint.type)))),this.orthoReferencePoint){const n=rr(i,this.orthoReferencePoint);i.x=n.x,i.y=n.y}return i}updateDynamicInputDisplay(){const e=this.isDynamicInputEnabled(),t=this.isDynamicPromptEnabled();this.setSuppressDisplay(!e),this.setPromptVisible(this.allowPrompt&&e&&t)}setSuppressDisplay(e){var t;this.suppressDisplay!==e&&(this.suppressDisplay=e,this.visible&&(this.suppressDisplay?(this.container.style.display="none",(t=this.inputs)==null||t.blur()):(this.container.style.display="flex",this.inputs&&!this.inputs.focused&&this.inputs.focus())))}setPromptVisible(e){var i;if(!!!((i=this.label.textContent)!=null&&i.trim())){this.label.style.display="none";return}this.label.style.display=e?"inline":"none"}osnapMode2MarkerType(e){switch(e){case u.AcDbOsnapMode.EndPoint:return"rect";case u.AcDbOsnapMode.MidPoint:return"triangle";case u.AcDbOsnapMode.Center:return"circle";case u.AcDbOsnapMode.Quadrant:return"diamond";case u.AcDbOsnapMode.Nearest:return"x";default:return"rect"}}osnapModePriority(e){switch(e){case u.AcDbOsnapMode.EndPoint:case u.AcDbOsnapMode.MidPoint:case u.AcDbOsnapMode.Center:return 0;case u.AcDbOsnapMode.Quadrant:return 1;case u.AcDbOsnapMode.Nearest:return 2;default:return 1}}getOsnapPoint(e,t=20){const i=this.getOsnapPoints(e,t);if(i.length===0)return;const n=this.view.screenToWorld({x:0,y:0}),r=this.view.screenToWorld({x:t,y:0}).x-n.x;let a=Number.MAX_VALUE,c=Number.MAX_VALUE,l=-1;for(let h=0;h<i.length;h++){const d=this.view.curPos.distanceTo(i[h]);if(d>=r)continue;const p=this.osnapModePriority(i[h].type);(p<a||p===a&&d<c)&&(a=p,c=d,l=h)}return l!==-1?i[l]:void 0}getOsnapPoints(e,t=20){const i=this.view.pick(e,t),s=u.acdbHostApplicationServices().workingDatabase.tables.blockTable.modelSpace,r=[];return i.forEach(a=>{const c=s.getIdAt(a.id);c&&(a.children&&a.children.length>0?a.children.forEach(l=>this.getOsnapPointsInAvailableModes(c,r,l.id)):this.getOsnapPointsInAvailableModes(c,r))}),r}getOsnapPointsInAvailableModes(e,t,i){u.acdbMaskToOsnapModes(me.instance.osnapModes).forEach(s=>this.getOsnapPointsByMode(e,s,t,i))}getOsnapPointsByMode(e,t,i,n){const s=i.length,r={...this.view.curPos,z:0},a=this.lastPoint?{...this.lastPoint,z:0}:r;e.subGetOsnapPoints(t,r,a,i,n);for(let c=s;c<i.length;c++)i[c].type=t}};Yt.inputStylesInjected=!1;let Tn=Yt;class kt extends Error{constructor(e){super("keyword"),this.keyword=e}}class Ci extends Error{constructor(){super("none")}}const Xt=class Xt{constructor(e){this.lastPoint=null,this._scriptInputs=[],this._modifierState={ctrlKey:!1,shiftKey:!1,altKey:!1,metaKey:!1},this._ctrlArcFlip=!1,this.active=!1,this.entitySelectionActive=!1,this.view=e,this.injectCSS(),getComputedStyle(this.view.container).position==="static"&&(this.view.container.style.position="relative");const i=new hr(this.view.container);this._commandLine=i,i.visible=me.instance.isShowCommandLine,me.instance.events.modified.addEventListener(()=>{i.visible=me.instance.isShowCommandLine})}get isActive(){return this.active}get isEntitySelectionActive(){return this.entitySelectionActive}get modifiers(){return this._modifierState}get toggles(){return{ctrlArcFlip:this._ctrlArcFlip}}resetToggles(){this._ctrlArcFlip=!1}enqueueScriptInputs(e){e.length&&this._scriptInputs.push(...e)}clearScriptInputs(){this._scriptInputs.length=0}showMessage(e,t="info",i){this._commandLine.showMessage(e,t,i)}peekScriptInput(){return this._scriptInputs[0]}consumeScriptInput(){return this.dequeueScriptInput()}injectCSS(){if(Xt.stylesInjected)return;Xt.stylesInjected=!0;const e=document.createElement("style");e.textContent=`
|
|
699
|
+
.ml-jig-preview-rect {
|
|
700
|
+
position: absolute;
|
|
701
|
+
border: 1px dashed var(--line-color, var(--ml-ui-canvas-line, #0f0));
|
|
702
|
+
background: var(--ml-ui-canvas-fill-mix, var(--ml-ui-canvas-fill, rgba(64, 158, 255, 0.12)));
|
|
703
|
+
pointer-events: none;
|
|
704
|
+
z-index: 1;
|
|
705
|
+
}
|
|
706
|
+
.ml-jig-preview-line {
|
|
707
|
+
position: absolute;
|
|
708
|
+
height: 1px;
|
|
709
|
+
background: var(--line-color, var(--ml-ui-canvas-line, #0f0));
|
|
710
|
+
transform-origin: 0 0;
|
|
711
|
+
pointer-events: none;
|
|
712
|
+
z-index: 1;
|
|
713
|
+
}
|
|
714
|
+
`,document.head.appendChild(e)}formatNumber(e,t){var n;const i=(n=A.instance.curDocument)==null?void 0:n.database;if(!i)switch(t){case"angle":return e.toFixed(2);case"distance":case"point":default:return e.toFixed(3)}switch(t){case"angle":return i.formatter.formatAngle(e*Math.PI/180,{applyAngbaseAngdir:!1});case"distance":case"point":default:return i.formatter.formatLength(e)}}hasKeywords(e){var i;return(((i=e.keywords)==null?void 0:i.toArray())??[]).length>0}buildKeywordOptions(e){var n;const t=new X(e.message);return t.appendKeywordsToMessage=e.appendKeywordsToMessage,(((n=e.keywords)==null?void 0:n.toArray())??[]).forEach(s=>{const r=t.keywords.add(s.displayName,s.globalName,s.localName,s.enabled,s.visible);e.keywords.default===s&&(t.keywords.default=r)}),t}copyKeywords(e,t){var n;t.appendKeywordsToMessage=e.appendKeywordsToMessage,(((n=e.keywords)==null?void 0:n.toArray())??[]).forEach(s=>{const r=t.keywords.add(s.displayName,s.globalName,s.localName,s.enabled,s.visible);e.keywords.default===s&&(t.keywords.default=r)})}getEntityById(e){return A.instance.curDocument.database.tables.blockTable.getEntityById(e)}isEntityOnLockedLayer(e){var i;const t=e.layer;return t?!!((i=A.instance.curDocument.database.tables.layerTable.getAt(t))!=null&&i.isLocked):!1}isEntityClassAllowed(e,t){var s;const i=new Set;e.type&&i.add(e.type);const n=(s=e.constructor)==null?void 0:s.name;n&&i.add(n);for(const r of i)if(t.isClassAllowed(r))return!0;return!1}startKeywordSession(e,t){if(!this.hasKeywords(e))return;const i=this.buildKeywordOptions(e);return{promise:this._commandLine.getKeywords(i,t),cancel:()=>this._commandLine.cancelActiveSession()}}isPromptKeyword(e){return e instanceof kt}mapPromptError(e,t){if(t.none&&this.isPromptNone(e))return t.none();if(t.cancel&&this.isPromptCancelled(e))return t.cancel();if(t.keyword&&this.isPromptKeyword(e))return t.keyword(e.keyword)}withKeywordResult(e,t){return e.stringResult=t,e}mapPromptErrorToResult(e,t,i){const n=(i==null?void 0:i.none)??!0,s=(i==null?void 0:i.cancel)??!0,r=(i==null?void 0:i.keyword)??!0;return this.mapPromptError(e,{none:n?()=>t(S.None):void 0,cancel:s?()=>t(S.Cancel):void 0,keyword:r?a=>this.withKeywordResult(t(S.Keyword),a):void 0})}async executePrompt(e,t,i,n){try{const s=await e();return t(s)}catch(s){const r=this.mapPromptErrorToResult(s,i,n);if(r)return r;throw s}}resolvePromptDefaultValue(e){return"useDefaultValue"in e&&"defaultValue"in e&&e.useDefaultValue?{useDefaultValue:!0,defaultValue:e.defaultValue}:{useDefaultValue:!1}}async getPoint(e){return this.executePrompt(()=>this.getPointInternal(e),t=>new Si(S.OK,t),t=>new Si(t))}getNumberTyped(e,t){const i=()=>({value:0,raw:{x:""}});return this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:i})}resolveDistanceBasePoint(e){if(e.useBasePoint&&e.basePoint)return{x:e.basePoint.x,y:e.basePoint.y}}createDistanceDynamicValue(e){return t=>{const i=t.x-e.x,n=t.y-e.y,s=Math.sqrt(i*i+n*n);return{value:s,raw:{x:this.formatNumber(s,"distance")}}}}async getDistanceTwoPoint(e,t){let i,n;const s=r=>i?this.createDistanceDynamicValue(i)(r):{value:0,raw:{x:""}};return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:s,onFloatingInputCreated:r=>{n=r},onCommit:(r,a)=>i?!0:a?(i={x:a.x,y:a.y},n==null||n.setBasePoint(i,{showBaseLineOnly:!e.useDashedLine}),!1):!0})}async getDistance(e){const t=new ml(e),i=this.tryGetScriptedNumber(t);if(i!=null)return new se(S.OK,i);const n=this.resolveDistanceBasePoint(e);return this.executePrompt(async()=>n?await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:this.createDistanceDynamicValue(n)}):await this.getDistanceTwoPoint(e,t),s=>new se(S.OK,s),s=>new se(s))}async getAngle(e){const t=new pl(e),i=this.tryGetScriptedNumber(t);if(i!=null)return new se(S.OK,i);const n=e.useBasePoint&&e.basePoint?e.basePoint:this.lastPoint;if(!n)return this.executePrompt(()=>this.getNumberTyped(e,t),r=>new se(S.OK,r),r=>new se(r));const s=r=>{const a=r.x-n.x,c=r.y-n.y,l=Math.atan2(c,a),h=e.baseAngle*Math.PI/180;let d=l-h;for(;d<=-Math.PI;)d+=Math.PI*2;for(;d>Math.PI;)d-=Math.PI*2;const p=d*180/Math.PI;return{value:p,raw:{x:this.formatNumber(p,"angle")}}};return this.executePrompt(()=>this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:t,getDynamicValue:s}),r=>new se(S.OK,r),r=>new se(r))}async getDouble(e){const t=new fl(e),i=this.tryGetScriptedNumber(t);return i!=null?new se(S.OK,i):this.executePrompt(()=>this.getNumberTyped(e,t),n=>new se(S.OK,n),n=>new se(n))}async getInteger(e){const t=this.tryGetScriptedNumber(new ur(e));return t!=null?new xi(S.OK,t):this.executePrompt(()=>this.getNumberTyped(e,new ur(e)),i=>new xi(S.OK,i),i=>new xi(i))}async getString(e){const t=this.tryGetScriptedValue(new gr(e));return t!=null?new ce(S.OK,t):this.executePrompt(async()=>{const i=()=>({value:"",raw:{x:""}}),n=new gr(e);return await this.makeFloatingInputPromise({inputCount:1,promptOptions:e,handler:n,getDynamicValue:i})},i=>new ce(S.OK,i),i=>new ce(i))}async getKeywords(e){const t=this.tryGetScriptedValue(new lr(e));return t!=null?new ce(S.OK,t):this.executePrompt(async()=>{const i=await this._commandLine.getKeywords(e,!0);if(!i)throw e.allowNone?new Ci:new Error("cancelled");return i},i=>new ce(S.OK,i),i=>new ce(i),{keyword:!1})}async getSelection(e){return this.executePrompt(()=>new Promise((t,i)=>{this.active=!0,this.entitySelectionActive=!0;const n=this.startKeywordSession(e,!0);n||this._commandLine.setPrompt(e.message);const s=new Et(this.view,{parent:this.view.canvas,message:e.message}),r=new Set;let a=null,c=null,l=null,h=null;const d=P=>{if(!a||!l||!c)return;const L=this.view.screenToWorld(this.view.viewportToCanvas({x:P.clientX,y:P.clientY})),M=this.view.viewportToCanvas({x:P.clientX,y:P.clientY}),k=this.view.worldToScreen(a),E=this.view.worldToScreen(L),T=Math.min(k.x,E.x),F=Math.min(k.y,E.y),O=Math.abs(k.x-E.x),z=Math.abs(k.y-E.y),U=this.view.getSelectionMode(c,M),V=this.view.getSelectionActionFromEvent(P,"add"),G=this.view.getSelectionPreviewStyle(U,V);Object.assign(l.style,{left:`${T}px`,top:`${F}px`,width:`${O}px`,height:`${z}px`,borderStyle:G.borderStyle,background:G.background}),l.style.setProperty("--line-color",G.lineColor)},p=()=>{h&&d(h)};let m=!1;const f=()=>{m||(m=!0,this.active=!1,this.entitySelectionActive=!1,s==null||s.dispose(),l==null||l.remove(),n==null||n.cancel(),this._commandLine.clear(),document.removeEventListener("keydown",w),this.view.canvas.removeEventListener("mousedown",b),this.view.canvas.removeEventListener("mousemove",v),this.view.canvas.removeEventListener("mouseup",C),this.view.canvas.removeEventListener("contextmenu",x),this.view.events.viewChanged.removeEventListener(p),this.view.events.viewResize.removeEventListener(p))};n==null||n.promise.then(P=>{if(!m){if(!P){f(),i(new Error("cancelled"));return}f(),i(new kt(P))}});const w=P=>{if(P.key==="Escape"){f(),i(new Error("cancelled"));return}P.key==="Enter"&&(f(),t([...r]))},x=P=>{this.shouldUseRightClickEnter()&&P.preventDefault()},b=P=>{if(P.button===2){this.shouldUseRightClickEnter()&&(P.preventDefault(),f(),t([...r]));return}P.button===0&&(c=this.view.viewportToCanvas({x:P.clientX,y:P.clientY}),a=this.view.screenToWorld(c),l=document.createElement("div"),l.className="ml-jig-preview-rect",this.view.container.appendChild(l))},v=P=>{P.buttons===1&&(!a||!l||!c||(h=P,d(P)))},C=P=>{if(P.button!==0||!a||!c)return;const L=this.view.screenToWorld(this.view.viewportToCanvas({x:P.clientX,y:P.clientY})),M=this.view.viewportToCanvas({x:P.clientX,y:P.clientY});l==null||l.remove(),l=null,h=null;const k=this.view.getSelectionActionFromEvent(P,"add");if(this.view.isSelectionClick(c,M)){const E=this.view.pick(L);E.length>0?this.view.applySelection([E[0].id],k):k==="replace"&&this.view.selectionSet.clear()}else{const E=new u.AcGeBox2d().expandByPoint(a).expandByPoint(L),T=this.view.getSelectionMode(c,M);this.view.selectByBoxWithMode(E,T,k)}r.clear();for(const E of this.view.selectionSet.ids)r.add(E);e.singleOnly&&k!=="remove"&&r.size>0&&(f(),t([...r])),a=null,c=null};document.addEventListener("keydown",w),this.view.canvas.addEventListener("mousedown",b),this.view.canvas.addEventListener("mousemove",v),this.view.canvas.addEventListener("mouseup",C),this.view.canvas.addEventListener("contextmenu",x),this.view.events.viewChanged.addEventListener(p),this.view.events.viewResize.addEventListener(p)}),t=>new It(S.OK,new fi(t)),t=>new It(t),{none:!1})}async getEntity(e){let t;return this.executePrompt(()=>new Promise((i,n)=>{this.active=!0,this.entitySelectionActive=!0;const s=this.startKeywordSession(e,!0),r=new Et(this.view,{parent:this.view.canvas,message:e.message});s||this._commandLine.setPrompt(e.message);let a=!1;const c=()=>{var m;a||(a=!0,this.active=!1,this.entitySelectionActive=!1,(m=e.jig)==null||m.end(),document.removeEventListener("keydown",d),this.view.canvas.removeEventListener("mousedown",l),this.view.canvas.removeEventListener("click",h),this.view.canvas.removeEventListener("contextmenu",p),r==null||r.dispose(),s==null||s.cancel(),this._commandLine.clear())};s==null||s.promise.then(m=>{if(!a){if(!m){c(),n(new Error("cancelled"));return}c(),n(new kt(m))}});const l=m=>{if(m.button===2){this.shouldUseRightClickEnter()&&e.allowNone&&(m.preventDefault(),c(),i(null));return}},h=m=>{if(m.button!==0)return;const f=this.view.screenToWorld(this.view.viewportToCanvas({x:m.clientX,y:m.clientY})),w=this.view.pick(f,void 0,!0);if(w.length==0){this._commandLine.showMessage(e.rejectMessage,"warning");return}const x=this.getEntityById(w[0].id);if(!x){this._commandLine.showMessage(e.rejectMessage,"warning");return}if(!e.allowObjectOnLockedLayer&&this.isEntityOnLockedLayer(x)){this._commandLine.showMessage(e.rejectMessage,"warning");return}if(!this.isEntityClassAllowed(x,e)){this._commandLine.showMessage(e.rejectMessage,"warning");return}t={x:f.x,y:f.y,z:0},c(),i(w[0].id)},d=m=>{if(m.key==="Escape"){c(),n(new Error("cancelled"));return}m.key==="Enter"&&e.allowNone&&(c(),i(null))},p=m=>{this.shouldUseRightClickEnter()&&m.preventDefault()};document.addEventListener("keydown",d),this.view.canvas.addEventListener("mousedown",l),this.view.canvas.addEventListener("click",h),this.view.canvas.addEventListener("contextmenu",p)}),i=>new vi(S.OK,i||void 0,t),i=>new vi(i),{none:!1})}async getBox(e){return this.executePrompt(async()=>{const t=e.firstCornerMessage||g.t("main.inputManager.firstCorner"),i=new D(t);this.copyKeywords(e,i),i.useDashedLine=e.useDashedLine,i.useBasePoint=e.useBasePoint,i.disableOSnap=e.disableOSnap;const n=await this.getPoint(i);if(n.status!==S.OK)return new wi(n.status,void 0,n.stringResult);const s=n.value,r=this.view.worldToScreen(s),a=document.createElement("div");a.className="ml-jig-preview-rect",this.view.container.appendChild(a);const c=()=>{a.remove()},l=f=>{const w=this.view.worldToScreen(f),x=Math.min(w.x,r.x),b=Math.min(w.y,r.y),v=Math.abs(w.x-r.x),C=Math.abs(w.y-r.y);Object.assign(a.style,{left:`${x}px`,top:`${b}px`,width:`${v}px`,height:`${C}px`})},h=e.secondCornerMessage||g.t("main.inputManager.secondCorner"),d=new D(h);this.copyKeywords(e,d),d.useDashedLine=e.useDashedLine,d.useBasePoint=e.useBasePoint,d.disableOSnap=e.disableOSnap;const p=await this.getPointInternal(d,c,l),m=new u.AcGeBox2d().expandByPoint(s).expandByPoint(p);return new wi(S.OK,m)},t=>t,t=>new wi(t))}async getPointInternal(e,t,i){const n=this.tryGetScriptedPoint(e);if(n!=null)return t==null||t(),Promise.resolve(n);const s=a=>({value:{x:a.x,y:a.y,z:0},raw:{x:this.formatNumber(a.x,"point"),y:this.formatNumber(a.y,"point")}}),r=new dr(e);return this.makeFloatingInputPromise({inputCount:2,promptOptions:e,disableOSnap:e.disableOSnap,cleanup:t,handler:r,getDynamicValue:s,drawPreview:i})}tryGetScriptedPoint(e){const t=this.dequeueScriptInput();if(t===void 0)return;const i=t.trim();if(!i&&e.allowNone)throw new Ci;const n=e.keywords.findByName(i);if(n)throw new kt(n.globalName);const s=this.splitScriptedPoint(t);if(!s)throw new Error(`Invalid point input '${t}'`);const r=new dr(e).parse(s.x,s.y);if(r==null)throw new Error(`Invalid point input '${t}'`);return this.lastPoint={x:r.x,y:r.y},r}tryGetScriptedValue(e){const t=this.dequeueScriptInput();if(t===void 0)return;const i=e.parse(t);if(i==null)throw new Error(`Invalid scripted input '${t}'`);return i}tryGetScriptedNumber(e){return this.tryGetScriptedValue(e)}dequeueScriptInput(){if(this._scriptInputs.length)return this._scriptInputs.shift()}splitScriptedPoint(e){const t=e.trim();if(!t)return;if(t.includes(",")){const n=t.split(",").map(s=>s.trim());return n.length!==2&&n.length!==3||n.length===3&&Number.isNaN(Number(n[2]))?void 0:{x:n[0],y:n[1]}}const i=t.split(/\s+/);if(!(i.length<2))return{x:i[0],y:i[1]}}isPromptCancelled(e){return e instanceof Error&&e.message==="cancelled"}isPromptNone(e){return e instanceof Ci}getShortcutMenuMode(){const e=u.acdbHostApplicationServices().workingDatabase,t=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.SHORTCUTMENU,e),i=Math.trunc(Number(t));return Number.isNaN(i)?0:i&3}shouldUseRightClickEnter(){const e=this.getShortcutMenuMode();return e===0?!0:e===1?this.active:!1}updateModifierStateFromEvent(e){const t={ctrlKey:!!e.ctrlKey,shiftKey:!!e.shiftKey,altKey:!!e.altKey,metaKey:!!e.metaKey},i=this._modifierState,n=i.ctrlKey!==t.ctrlKey||i.shiftKey!==t.shiftKey||i.altKey!==t.altKey||i.metaKey!==t.metaKey;return n&&(this._modifierState=t),n}handleCtrlToggleKey(e){return e.key!=="Control"||e.repeat||e.type!=="keydown"?!1:(this._ctrlArcFlip=!this._ctrlArcFlip,!0)}resolvePromptDefaults(e){const t="basePoint"in e,i="useBasePoint"in e,n="useDashedLine"in e,s="baseAngle"in e,r=t&&e.basePoint?e.basePoint:void 0,a=i?e.useBasePoint:!1,c=n?!e.useDashedLine:!1,l=s?e.baseAngle:void 0;return{message:e.message,jig:e.jig,basePoint:r,useBasePoint:a,showBaseLineOnly:c,baseAngle:l}}async makeFloatingInputPromise(e){return new Promise((t,i)=>{var M;this.active=!0,this.entitySelectionActive=!1;let n=!1;const s=k=>{const E=e.handler.parse(k.x,k.y);return{isValid:E!=null,value:E??void 0}},r=this.resolvePromptDefaults(e.promptOptions),a=this.startKeywordSession(e.promptOptions,!0);let c;r.useBasePoint&&r.basePoint&&(c=r.basePoint);const l=r.useBasePoint&&r.basePoint?r.basePoint:this.lastPoint??void 0,h=r.message;a||this._commandLine.setPrompt(h);const d="allowNone"in e.promptOptions?e.promptOptions.allowNone:!1,p=this.resolvePromptDefaultValue(e.promptOptions),m=new Tn(this.view,{parent:this.view.canvas,inputCount:e.inputCount,message:r.message,disableOSnap:e.disableOSnap,showBaseLineOnly:r.showBaseLineOnly,basePoint:c,orthoReferencePoint:l,baseAngle:r.baseAngle,allowPrompt:e.allowPrompt!==!1,allowNone:d,useDefaultValue:p.useDefaultValue,defaultValue:p.defaultValue,validate:s,getDynamicValue:e.getDynamicValue,drawPreview:k=>{var E;if(r.jig){const T=e.getDynamicValue(k);r.jig.update(T.value),r.jig.render()}(E=e.drawPreview)==null||E.call(e,k)},onCommit:(k,E)=>{let T=!1;return(!e.onCommit||e.onCommit(k,E))&&(w(k),T=!0),T&&m.lastPoint&&(this.lastPoint={x:m.lastPoint.x,y:m.lastPoint.y}),T},onCancel:()=>x(),onNone:()=>b()});(M=e.onFloatingInputCreated)==null||M.call(e,m);const f=()=>{var k,E;n||(n=!0,this.active=!1,this.entitySelectionActive=!1,(k=e.cleanup)==null||k.call(e),(E=r.jig)==null||E.end(),document.removeEventListener("keydown",C),document.removeEventListener("keydown",P),document.removeEventListener("keyup",P),this.view.canvas.removeEventListener("contextmenu",L),m.dispose(),a==null||a.cancel(),this._commandLine.clear())},w=k=>{f(),t(k)},x=k=>{f(),i(k??new Error("cancelled"))},b=()=>{x(new Ci)},v=k=>{x(new kt(k))},C=k=>{k.key==="Escape"&&x()},P=k=>{const E=this.handleCtrlToggleKey(k),T=this.updateModifierStateFromEvent(k);(E||T)&&m.requestPreviewRefresh()},L=k=>{this.shouldUseRightClickEnter()&&(k.preventDefault(),b())};document.addEventListener("keydown",C),document.addEventListener("keydown",P),document.addEventListener("keyup",P),this.view.canvas.addEventListener("contextmenu",L),m.showAt(this.view.canvasToViewport(this.view.curMousePos)),a==null||a.promise.then(k=>{if(!n){if(!k){x();return}v(k)}})})}};Xt.stylesInjected=!1;let Pi=Xt;const _i="simkai";function wl(){return{fontFamily:_i,fontSize:24,bold:!1,italic:!1,underline:!1,overline:!1,strike:!1,script:"normal",aci:null,rgb:16777215,obliqueAngle:0,widthFactor:1,tracking:1,paragraphAlignment:B.MTextParagraphAlignment.DEFAULT}}function yr(o,e){return o.fontFamily===e.fontFamily&&o.fontSize===e.fontSize&&o.bold===e.bold&&o.italic===e.italic&&o.underline===e.underline&&o.overline===e.overline&&o.strike===e.strike&&o.script===e.script&&o.aci===e.aci&&o.rgb===e.rgb&&o.obliqueAngle===e.obliqueAngle&&o.widthFactor===e.widthFactor&&o.tracking===e.tracking&&o.paragraphAlignment===e.paragraphAlignment}function re(o,e,t){return Math.min(t,Math.max(e,o))}function bl(o,e){const t=Math.max(o.y-o.height/2,e.y-e.height/2),i=Math.min(o.y+o.height/2,e.y+e.height/2);return Math.max(0,i-t)}class vl{constructor(e){I(this,"containerBox");I(this,"charBoxes");I(this,"explicitLineBreakIndices",[]);I(this,"explicitLineLayouts",[]);I(this,"cursorLineHint",null);I(this,"verticalAlign");I(this,"lineTolerance");I(this,"debug");I(this,"lines",[]);I(this,"cursorIndex",0);I(this,"selection",null);I(this,"dragAnchor",null);I(this,"preferredX",null);I(this,"handlers",{cursorMove:new Set,selectionChange:new Set,linesUpdate:new Set});this.containerBox={...e.containerBox};const t=this.normalizeCharLayout(e.charBoxes,e.lineBreakIndices);this.charBoxes=t.charBoxes,this.explicitLineBreakIndices=t.lineBreakIndices,this.explicitLineLayouts=this.normalizeLineLayouts(e.lineLayouts),this.verticalAlign=e.verticalAlign??"center",this.lineTolerance=e.lineTolerance??5,this.debug=e.debug??!1,this.cursorIndex=re(e.initialIndex??0,0,this.charBoxes.length),this.recomputeLines(),e.initialSelection&&this.setSelection(e.initialSelection.start,e.initialSelection.end)}moveLeft(){if(this.selection&&!this.selection.isCollapsed){this.cursorIndex=this.selection.start,this.cursorLineHint=null,this.clearSelection(),this.emitCursor();return}const e=this.getCurrentLineIndex();if(e>=0){const t=this.lines[e];if(t){if(this.cursorIndex>t.startIndex&&this.cursorIndex<=t.endIndex+1){this.moveTo(this.cursorIndex-1,e);return}if(this.cursorIndex===t.startIndex&&e>0){this.moveTo(this.cursorIndex,e-1);return}}}this.moveTo(this.cursorIndex-1)}moveRight(){if(this.selection&&!this.selection.isCollapsed){this.cursorIndex=this.selection.end,this.cursorLineHint=null,this.clearSelection(),this.emitCursor();return}const e=this.getCurrentLineIndex();if(e>=0){const t=this.lines[e],i=e+1;if(t&&this.cursorIndex===t.endIndex&&i<this.lines.length&&this.isHardBreakChar(t.endIndex)){this.moveTo(t.endIndex+1,i);return}if(t&&this.cursorIndex===t.endIndex+1&&i<this.lines.length){this.moveTo(this.cursorIndex,i);return}}this.cursorIndex>=this.charBoxes.length||this.moveTo(this.cursorIndex+1)}moveUp(){this.moveVertical(-1)}moveDown(){this.moveVertical(1)}moveTo(e,t=null){const i=re(e,0,this.charBoxes.length);i===this.cursorIndex&&this.cursorLineHint===t||(this.cursorIndex=i,this.cursorLineHint=t,this.preferredX=null,this.emitCursor())}moveToStart(){this.moveTo(0)}moveToEnd(){this.moveTo(this.charBoxes.length)}moveToLineStart(){const e=this.getCurrentLineIndex();if(e<0){this.moveToStart();return}const t=this.lines[e];t&&this.moveTo(t.startIndex,e)}moveToLineEnd(){const e=this.getCurrentLineIndex();if(e<0){this.moveToEnd();return}const t=this.lines[e];t&&this.moveTo(t.endIndex+1,e)}setSelection(e,t){const i=re(e,0,this.charBoxes.length),n=re(t,0,this.charBoxes.length);this.setSelectionWithDirection(i,n)}clearSelection(){this.selection&&(this.selection=null,this.dragAnchor=null,this.emit("selectionChange",null))}selectAll(){this.setSelectionWithDirection(0,this.charBoxes.length),this.cursorIndex=this.charBoxes.length,this.cursorLineHint=null,this.emitCursor()}setSelectionWithDirection(e,t){const i=re(e,0,this.charBoxes.length),n=re(t,0,this.charBoxes.length),s=Math.min(i,n),r=Math.max(i,n);this.selection={start:s,end:r,isCollapsed:s===r,anchor:i,active:n,isBackwards:n<i,selectedLines:this.resolveSelectedLines(s,r)},this.cursorIndex=n,this.cursorLineHint=null,this.emit("selectionChange",this.selection),this.emitCursor()}extendSelection(e){var n;const t=re(e,0,this.charBoxes.length),i=((n=this.selection)==null?void 0:n.anchor)??this.cursorIndex;this.setSelectionWithDirection(i,t)}getSelection(){return this.selection?{...this.selection,selectedLines:[...this.selection.selectedLines]}:null}getSelectedCharBoxes(){return!this.selection||this.selection.isCollapsed?[]:this.charBoxes.slice(this.selection.start,this.selection.end).map(e=>({...e}))}getSelectedLines(){if(!this.selection||this.selection.isCollapsed)return[];const e=[],{start:t,end:i}=this.selection;for(let n=0;n<this.lines.length;n++){const s=this.lines[n];if(!s)continue;const r=s.startIndex,a=s.endIndex+1,c=Math.max(t,r),l=Math.min(i,a);c<l&&e.push({lineIndex:n,startOffset:c-r,endOffset:l-r})}return e}hasSelection(){return!!this.selection&&!this.selection.isCollapsed}moveToClick(e,t){const i=this.hitTest(e,t);if(i<0)return!1;const n=this.hitTestLine(t);return this.clearSelection(),this.moveTo(i,n>=0?n:null),!0}extendSelectionToClick(e,t){const i=this.hitTestClamped(e,t);i<0||(this.dragAnchor===null&&(this.dragAnchor=this.cursorIndex),this.setSelectionWithDirection(this.dragAnchor,i))}updateSelectionDrag(e,t){const i=this.hitTestClamped(e,t);i<0||(this.dragAnchor===null&&(this.dragAnchor=this.cursorIndex),this.setSelectionWithDirection(this.dragAnchor,i))}hitTest(e,t){if(!this.isInContainer(e,t))return-1;if(this.charBoxes.length===0)return 0;const i=this.hitTestLine(t);return i<0?-1:this.closestIndexInLine(i,e)}hitTestLine(e){if(this.lines.length===0)return-1;let t=-1,i=Number.POSITIVE_INFINITY;for(let n=0;n<this.lines.length;n++){const s=this.lines[n];if(!s)continue;const r=s.y-s.height/2,a=s.y+s.height/2;if(e>=r&&e<=a)return n;const c=e<r?r-e:e-a;c<i&&(i=c,t=n)}return t}getLines(){return this.lines.map(e=>({...e}))}getLineCount(){return this.lines.length}getLineIndex(e){if(this.lines.length===0)return-1;const t=re(e,0,this.charBoxes.length);for(let i=0;i<this.lines.length;i++){const n=this.lines[i];if(n&&t>=n.startIndex&&t<=n.endIndex+1)return i}return this.lines.length-1}getLineInfo(e){const t=this.lines[e];if(!t)throw new Error(`Line index out of range: ${e}`);return{...t}}getCurrentLineInfo(){const e=this.getCurrentLineIndex();if(e<0)return{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0};const t=this.lines[e];return t?{...t}:{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0}}getCursorState(){var n,s;const e=this.getCurrentLineIndex(),t=this.getCursorPosition(),i=e>=0&&this.lines[e]?this.lines[e]:{startIndex:0,endIndex:-1,y:this.containerBox.y,height:this.containerBox.height,charCount:0};return{index:this.cursorIndex,position:t,lineIndex:e,lineInfo:{...i},isAtStart:this.cursorIndex===0,isAtEnd:this.cursorIndex===this.charBoxes.length,isAtLineStart:e<0?!0:this.cursorIndex===(((n=this.lines[e])==null?void 0:n.startIndex)??this.cursorIndex),isAtLineEnd:e<0?!0:this.cursorIndex===(((s=this.lines[e])==null?void 0:s.endIndex)??this.cursorIndex-1)+1}}getCurrentIndex(){return this.cursorIndex}getCursorPosition(){if(this.lines.length===0)return{x:this.containerBox.x,y:this.alignY(this.containerBox.y,this.containerBox.height)};const e=this.getCurrentLineIndex(),t=this.lines[Math.max(0,e)];if(!t)return{x:this.containerBox.x,y:this.alignY(this.containerBox.y,this.containerBox.height)};const i=this.alignY(t.y,t.height);return{x:this.indexToX(this.cursorIndex,e),y:i}}getCharBoxes(){return this.charBoxes.map(e=>({...e}))}getContainerBox(){return{...this.containerBox}}updateData(e,t,i,n){this.containerBox={...e};const s=this.normalizeCharLayout(t,i);if(this.charBoxes=s.charBoxes,this.explicitLineBreakIndices=s.lineBreakIndices,this.explicitLineLayouts=this.normalizeLineLayouts(n),this.recomputeLines(),this.cursorIndex=re(this.cursorIndex,0,this.charBoxes.length),this.cursorLineHint=null,this.selection){const r=re(this.selection.anchor,0,this.charBoxes.length),a=re(this.selection.active,0,this.charBoxes.length);r===a?this.selection=null:this.setSelectionWithDirection(r,a)}this.emit("linesUpdate",this.getLines()),this.emitCursor()}setLineTolerance(e){this.lineTolerance=Math.max(0,e),this.recomputeLines(),this.emit("linesUpdate",this.getLines()),this.emitCursor(),this.selection&&(this.selection.selectedLines=this.resolveSelectedLines(this.selection.start,this.selection.end),this.emit("selectionChange",this.selection))}on(e,t){this.handlers[e].add(t)}off(e,t){(e==="cursorMove"||e==="selectionChange"||e==="linesUpdate")&&this.handlers[e].delete(t)}enableDebug(){this.debug=!0}disableDebug(){this.debug=!1}getDebugInfo(){return{debug:this.debug,container:this.getContainerBox(),cursor:this.getCursorState(),selection:this.getSelection(),lines:this.getLines(),gaps:this.lines.map((e,t)=>this.getGapPositions(t))}}destroy(){this.handlers.cursorMove.clear(),this.handlers.selectionChange.clear(),this.handlers.linesUpdate.clear(),this.selection=null,this.dragAnchor=null,this.preferredX=null}emitCursor(){this.emit("cursorMove",this.getCursorState())}emit(e,t){for(const i of this.handlers[e])i(t)}moveVertical(e){const t=this.getCurrentLineIndex();if(t<0)return;const i=this.lines[t],n=t+e;if(n<0||n>=this.lines.length)return;(this.preferredX===null||(i==null?void 0:i.charCount)===0)&&(this.preferredX=this.getCursorPosition().x);const s=this.closestIndexInLine(n,this.preferredX);this.cursorIndex=s,this.cursorLineHint=n,this.emitCursor()}getCurrentLineIndex(){const e=this.getLineIndex(this.cursorIndex);if(e<0||this.cursorLineHint===null)return e;const t=this.lines[this.cursorLineHint];return t&&this.cursorIndex>=t.startIndex&&this.cursorIndex<=t.endIndex+1?this.cursorLineHint:e}isHardBreakChar(e){const t=this.charBoxes[e];return t?t.width===0:!1}resolveSelectedLines(e,t){if(e===t)return[];const i=[];for(let n=0;n<this.lines.length;n++){const s=this.lines[n];s&&t>s.startIndex&&e<s.endIndex+1&&i.push(n)}return i}isInContainer(e,t){return e>=this.containerBox.x&&e<=this.containerBox.x+this.containerBox.width&&t>=this.containerBox.y&&t<=this.containerBox.y+this.containerBox.height}hitTestClamped(e,t){if(this.charBoxes.length===0)return 0;const i=this.lines.length===0?-1:this.hitTestLine(t);return i<0?e<=this.containerBox.x?0:e>=this.containerBox.x+this.containerBox.width?this.charBoxes.length:re(this.cursorIndex,0,this.charBoxes.length):this.closestIndexInLine(i,e)}recomputeLines(){if(this.explicitLineBreakIndices.length>0){this.lines=this.linesFromBreakIndices(this.charBoxes,this.explicitLineBreakIndices,this.explicitLineLayouts);return}this.lines=this.detectLines(this.charBoxes,this.lineTolerance)}normalizeCharLayout(e,t){const i=[],n=[];for(const a of e){if(!a){n.push(i.length);continue}i.push({...a})}const s=[...n,...t??[]],r=this.normalizeBreakIndices(s,i.length);return{charBoxes:i,lineBreakIndices:r}}normalizeBreakIndices(e,t){if(e.length===0)return[];const i=[];for(const n of e){if(!Number.isFinite(n))continue;const s=re(Math.round(n),0,t);i.push(s)}return i.sort((n,s)=>n-s)}normalizeLineLayouts(e){if(!e||e.length===0)return[];const t=[];for(const i of e)i&&(!Number.isFinite(i.y)||!Number.isFinite(i.height)||t.push({y:i.y,height:Math.max(1,i.height)}));return t}linesFromBreakIndices(e,t,i){if(e.length===0&&t.length===0)return[];if(t.length===0)return this.detectLines(e,this.lineTolerance);const n=[];let s=0;for(const r of t)if(!(r<s||r>e.length)){if(r===s){n.push(this.createEmptyLine(s,n[n.length-1],i[n.length]));continue}n.push(this.withLineLayout(this.aggregateLine(e,s,r-1),i[n.length])),s=r}return s<e.length?n.push(this.withLineLayout(this.aggregateLine(e,s,e.length-1),i[n.length])):n.push(this.createEmptyLine(s,n[n.length-1],i[n.length])),n}detectLines(e,t){if(e.length===0)return[];const i=[],n=.65;let s=0;for(let r=1;r<e.length;r++){const a=e[r-1],c=e[r];if(!a||!c)continue;const l=Math.abs(c.y-a.y),h=c.x+t<a.x,d=bl(a,c),p=Math.min(a.height,c.height),f=(p>0?d/p:0)<n;(h||l>t&&f)&&(i.push(this.aggregateLine(e,s,r-1)),s=r)}return i.push(this.aggregateLine(e,s,e.length-1)),i}aggregateLine(e,t,i){let n=0,s=0,r=0;for(let a=t;a<=i;a++){const c=e[a];c&&(n+=c.y,s+=1,r=Math.max(r,c.height))}return s===0?{startIndex:t,endIndex:i,y:this.containerBox.y,height:this.containerBox.height,charCount:Math.max(0,i-t+1)}:{startIndex:t,endIndex:i,y:n/s,height:r,charCount:i-t+1}}withLineLayout(e,t){return t?{...e,y:t.y,height:Math.max(1,t.height)}:e}createEmptyLine(e,t,i){if(i)return{startIndex:e,endIndex:e-1,y:i.y,height:Math.max(1,i.height),charCount:0};const n=Math.max(1,(t==null?void 0:t.height)??this.containerBox.height),s=t!==void 0?t.y+n:this.alignY(this.containerBox.y,this.containerBox.height);return{startIndex:e,endIndex:e-1,y:s,height:n,charCount:0}}alignY(e,t){return this.verticalAlign==="top"?e-t/2:this.verticalAlign==="bottom"?e+t/2:e}indexToX(e,t){if(this.charBoxes.length===0)return this.containerBox.x;if(e<=0)return this.containerBox.x;const i=t??this.getLineIndex(e);if(i<0)return this.containerBox.x;const n=this.lines[i];if(!n)return this.containerBox.x;if(e<=n.startIndex)return this.containerBox.x;if(e>n.endIndex+1){const r=this.charBoxes[this.charBoxes.length-1];return r?r.x+r.width:this.containerBox.x}const s=this.charBoxes[e-1];return s?s.x+s.width:this.containerBox.x}getGapPositions(e){const t=this.lines[e];if(!t)return[];const i=[{index:t.startIndex,x:this.containerBox.x}];for(let n=t.startIndex;n<=t.endIndex;n++){const s=this.charBoxes[n];s&&i.push({index:n+1,x:s.x+s.width})}return i}closestIndexInLine(e,t){const i=this.getGapPositions(e);if(i.length===0)return 0;let n=i[0],s=Math.abs(t-n.x);for(let r=1;r<i.length;r++){const a=i[r];if(!a)continue;const c=Math.abs(t-a.x);c<s&&(n=a,s=c)}return n.index}}const xl={width:4,height:24,heightMode:"lineHeight",color:"#00f5ff",glowColor:"#00f5ff",glowIntensity:.9,blinkSpeed:1.05,blinkEnabled:!0,billboard:!0,depthTest:!1,renderOrder:100,mode:"plane"},Sl={fillColor:"rgba(0,120,255,0.30)",blendMode:"normal",animate:!1,strategy:"perChar"},Al={charBoxColor:"rgba(64,160,255,0.55)",charBoxFill:"rgba(64,160,255,0.10)",charIndexColor:"rgba(255,255,255,0.85)",rowHoverColor:"rgba(200,200,200,0.10)",rowBoundaryColor:"rgba(255,255,255,0.22)",gapColor:"rgba(255,153,0,0.7)",baselineColor:"rgba(255,51,51,0.55)",containerColor:"rgba(255,255,255,0.30)"},Cl={showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0};class Pl{constructor(e){I(this,"renderer");I(this,"cursorStyle");I(this,"selectionStyle");I(this,"debugStyle");I(this,"debugVisibility");I(this,"enableSelection");I(this,"enableDebug");I(this,"debugYAxisUp");I(this,"visible",!0);I(this,"cursorState",null);I(this,"selectionBoxes",[]);I(this,"debugData",null);I(this,"viewTransform",{x:0,y:0,scaleX:1,scaleY:1,rotation:0});this.renderer=e.renderer,this.cursorStyle={...xl,...e.cursorStyle},this.selectionStyle={...Sl,...e.selectionStyle},this.debugStyle={...Al,...e.debugStyle},this.debugVisibility={...Cl,...e.debugVisibility},this.enableSelection=e.enableSelection??!0,this.enableDebug=e.enableDebug??!1,this.debugYAxisUp=e.debugYAxisUp??!1}updateCursor(e,t){this.cursorState={position:e,lineHeight:t}}updateSelection(e){this.selectionBoxes=e.map(t=>({...t}))}updateDebugInfo(e){const t={containerBox:{...e.containerBox},charBoxes:e.charBoxes.map(i=>({...i})),lines:e.lines.map(i=>({...i}))};e.chars&&(t.chars=[...e.chars]),e.gapPositions&&(t.gapPositions=[...e.gapPositions]),e.hoverLineIndex!==void 0&&(t.hoverLineIndex=e.hoverLineIndex),this.debugData=t}setCursorStyle(e){this.cursorStyle={...this.cursorStyle,...e}}setSelectionStyle(e){this.selectionStyle={...this.selectionStyle,...e}}setDebugMode(e){this.enableDebug=e}setDebugVisibility(e){this.debugVisibility={...this.debugVisibility,...e}}setViewTransform(e){this.viewTransform={...this.viewTransform,...e}}show(){this.visible=!0}hide(){this.visible=!1}toggle(){this.visible=!this.visible}render(){if(this.renderer.beginFrame(),!this.visible){this.renderer.endFrame();return}this.renderer.setTransform({x:this.viewTransform.x??0,y:this.viewTransform.y??0,scaleX:this.viewTransform.scaleX??1,scaleY:this.viewTransform.scaleY??1,rotation:this.viewTransform.rotation??0}),this.enableDebug&&this.debugData&&this.drawDebug(this.debugData),this.enableSelection&&this.selectionBoxes.length>0&&this.drawSelection(this.selectionBoxes),this.cursorState&&this.drawCursor(this.cursorState.position,this.cursorState.lineHeight),this.renderer.resetTransform(),this.renderer.endFrame()}dispose(){this.renderer.destroy(),this.selectionBoxes=[],this.cursorState=null,this.debugData=null}drawCursor(e,t){const i=Math.max(.2,this.cursorStyle.blinkSpeed)*1e3;if(!(!this.cursorStyle.blinkEnabled||Date.now()%i<i/2))return;const s=this.cursorStyle.heightMode==="fixed"?this.cursorStyle.height:Math.max(this.cursorStyle.height,t*.8);this.cursorStyle.glowColor&&(this.cursorStyle.glowIntensity??0)>0&&this.renderer.drawLine({x1:e.x,y1:e.y-s/2,x2:e.x,y2:e.y+s/2,color:this.cursorStyle.glowColor,width:this.cursorStyle.width+2,opacity:Math.min(1,this.cursorStyle.glowIntensity??0)}),this.renderer.drawLine({x1:e.x,y1:e.y-s/2,x2:e.x,y2:e.y+s/2,color:this.cursorStyle.color,width:this.cursorStyle.width,opacity:1})}drawSelection(e){if(this.selectionStyle.strategy==="merged"){this.mergeBoxes(e).forEach(t=>this.drawSelectionQuad(t));return}e.forEach(t=>this.drawSelectionQuad(t))}drawSelectionQuad(e){const t={x:e.x,y:e.y,width:e.width,height:e.height,fillColor:this.selectionStyle.fillColor,blendMode:this.selectionStyle.blendMode==="additive"?"lighter":this.selectionStyle.blendMode==="multiply"?"multiply":"source-over"};this.renderer.drawQuad({...t,...this.selectionStyle.borderColor?{borderColor:this.selectionStyle.borderColor}:{},...this.selectionStyle.borderWidth!==void 0?{borderWidth:this.selectionStyle.borderWidth}:{},...this.selectionStyle.cornerRadius!==void 0?{cornerRadius:this.selectionStyle.cornerRadius}:{}})}drawDebug(e){var i;this.renderer.drawBox({box:{x:e.containerBox.x,y:e.containerBox.y+e.containerBox.height/2,width:e.containerBox.width,height:e.containerBox.height},color:this.debugStyle.containerColor,opacity:1,lineWidth:1});const t=e.containerBox.x+e.containerBox.width+60;e.lines.forEach((n,s)=>{const r=this.debugYAxisUp?n.y+n.height/2:n.y-n.height/2,a=this.debugYAxisUp?n.y-n.height/2:n.y+n.height/2;e.hoverLineIndex===s&&this.renderer.drawQuad({x:0,y:n.y,width:t,height:n.height,fillColor:this.debugStyle.rowHoverColor}),this.renderer.drawLine({x1:0,y1:r,x2:t,y2:r,color:this.debugStyle.rowBoundaryColor,dashed:[5,5]}),this.renderer.drawLine({x1:0,y1:a,x2:t,y2:a,color:this.debugStyle.rowBoundaryColor,dashed:[5,5]}),this.debugVisibility.showLineIndices&&this.renderer.drawText({text:`L${s}`,x:8,y:r+(this.debugYAxisUp?-2:2),color:"rgba(255,255,255,0.65)",font:"12px monospace"})}),e.charBoxes.forEach((n,s)=>{var l;const r=this.debugYAxisUp?n.y+n.height/2:n.y-n.height/2,a=this.debugYAxisUp?-2:2,c=this.debugYAxisUp?-Math.max(8,n.height*.2):Math.max(8,n.height*.2);if(this.debugVisibility.showCharBoxes&&this.renderer.drawQuad({x:n.x,y:n.y,width:n.width,height:n.height,fillColor:this.debugStyle.charBoxFill,borderColor:this.debugStyle.charBoxColor,borderWidth:1}),this.debugVisibility.showCharIndices&&this.renderer.drawText({text:String(s),x:n.x+2,y:r+a,color:this.debugStyle.charIndexColor,font:"10px monospace"}),this.debugVisibility.showChars){const h=(l=e.chars)==null?void 0:l[s];if(!h)return;this.renderer.drawText({text:h,x:n.x+2,y:r+c,color:"rgba(255,255,255,0.95)",font:`${Math.max(12,Math.round(n.height*.6))}px monospace`})}}),(i=e.gapPositions)==null||i.forEach(n=>{this.renderer.drawLine({x1:n.x,y1:n.y-n.height/2,x2:n.x,y2:n.y+n.height/2,color:this.debugStyle.gapColor,opacity:n.strong?.9:.55,width:1})})}mergeBoxes(e){if(e.length===0)return[];const t=[...e].sort((n,s)=>n.y===s.y?n.x-s.x:n.y-s.y),i=[];for(const n of t){const s=i[i.length-1];if(!s){i.push({...n});continue}const r=Math.abs(s.y-n.y)<=1,a=n.x<=s.x+s.width+1,c=Math.abs(s.height-n.height)<=1;r&&a&&c?s.width=Math.max(s.x+s.width,n.x+n.width)-s.x:i.push({...n})}return i}}function Li(o){const e=o.match(/rgba?\(([^)]+)\)/i);if(e){const n=(e[1]??"").split(",").map(l=>Number(l.trim())),[s=255,r=255,a=255,c=1]=n;return{color:new y.Color(s/255,r/255,a/255),alpha:Number.isFinite(c)?c:1}}const t=new y.Color;return t.setStyle(o),{color:t,alpha:1}}class _l{constructor(e){I(this,"scene");I(this,"camera");I(this,"frameGroup",new y.Group);I(this,"currentTransform",{x:0,y:0,scaleX:1,scaleY:1,rotation:0});I(this,"canvas",null);this.scene=e.scene,this.camera=e.camera,this.scene.add(this.frameGroup)}initialize(e){this.canvas=e}destroy(){this.clearFrame(),this.scene.remove(this.frameGroup)}beginFrame(){this.clearFrame()}endFrame(){this.camera}drawQuad(e){const t=this.currentTransform.scaleX??1,i=this.currentTransform.scaleY??1,n=this.transformPoint(e.x+e.width/2,e.y),s=this.createQuadMesh(n.x-e.width*t/2,n.y,Math.abs(e.width*t),Math.abs(e.height*i),e.fillColor,e.opacity);if(s&&this.frameGroup.add(s),e.borderColor){const r=this.createRectBorder(n.x-e.width*t/2,n.y,Math.abs(e.width*t),Math.abs(e.height*i),e.borderColor,e.borderWidth??1,e.opacity??1);this.frameGroup.add(r)}}drawLine(e){const t=this.transformPoint(e.x1,e.y1),i=this.transformPoint(e.x2,e.y2),n=Li(e.color),s=(e.opacity??1)*n.alpha;if(e.dashed&&e.dashed.length>0){const h=[new y.Vector3(t.x,t.y,0),new y.Vector3(i.x,i.y,0)],d=new y.BufferGeometry().setFromPoints(h),p=new y.LineDashedMaterial({color:n.color,linewidth:e.width??1,transparent:s<1,opacity:s,dashSize:e.dashed[0]??4,gapSize:e.dashed[1]??2,depthTest:!1}),m=new y.Line(d,p);m.computeLineDistances(),m.renderOrder=e.renderOrder??1,this.frameGroup.add(m);return}const r=new Wa.LineGeometry;r.setPositions([t.x,t.y,0,i.x,i.y,0]);const a=new xt.LineMaterial({color:n.color,linewidth:e.width??1,worldUnits:!1,transparent:s<1,opacity:s,depthTest:!1}),c=this.getResolution();a.resolution.set(c.x,c.y);const l=new $a.Line2(r,a);l.computeLineDistances(),l.renderOrder=e.renderOrder??1,this.frameGroup.add(l)}drawText(e){var O;const t=e.font??"20px monospace",i=Number(((O=t.match(/(\d+(?:\.\d+)?)px/))==null?void 0:O[1])??20),n=4,s=document.createElement("canvas");let r=s.getContext("2d");if(!r)return;r.font=t;const c=Math.max(1,Math.ceil(r.measureText(e.text).width))+n*2,l=Math.max(1,Math.ceil(i*1.4));if(s.width=c,s.height=l,r=s.getContext("2d"),!r)return;r.clearRect(0,0,s.width,s.height),r.font=t;const h=e.align??"left",d=e.baseline??"top";r.textAlign=h,r.textBaseline=d;const p=Li(e.color);r.fillStyle=`rgba(${Math.round(p.color.r*255)}, ${Math.round(p.color.g*255)}, ${Math.round(p.color.b*255)}, ${e.opacity??p.alpha})`;const m=h==="center"?s.width/2:h==="right"?s.width-n:n,f=d==="middle"?s.height/2:d==="bottom"?s.height-n:n;r.fillText(e.text,m,f);const w=this.isYAxisUp(),x=new y.CanvasTexture(s);x.flipY=w,x.needsUpdate=!0;const b=Math.abs(this.currentTransform.scaleX??1),v=Math.abs(this.currentTransform.scaleY??1),C=Math.max(1,s.width*b),P=Math.max(1,s.height*v),L=new y.PlaneGeometry(C,P),M=new y.MeshBasicMaterial({map:x,transparent:!0,depthTest:!1,depthWrite:!1,side:y.DoubleSide}),k=new y.Mesh(L,M),E=this.transformPoint(e.x,e.y),T=h==="center"?0:h==="right"?-C/2:C/2,F=d==="middle"?0:d==="bottom"?w?P/2:-P/2:w?-P/2:P/2;k.position.set(E.x+T,E.y+F,.2),k.renderOrder=10,this.frameGroup.add(k)}drawBox(e){const t=this.currentTransform.scaleX??1,i=this.currentTransform.scaleY??1,n=this.transformPoint(e.box.x+e.box.width/2,e.box.y),s=this.createRectBorder(n.x-e.box.width*t/2,n.y,Math.abs(e.box.width*t),Math.abs(e.box.height*i),e.color,e.lineWidth??1,e.opacity??1);s.renderOrder=e.renderOrder??2,this.frameGroup.add(s)}setTransform(e){this.currentTransform={x:e.x??0,y:e.y??0,scaleX:e.scaleX??1,scaleY:e.scaleY??1,rotation:e.rotation??0}}resetTransform(){this.currentTransform={x:0,y:0,scaleX:1,scaleY:1,rotation:0}}transformPoint(e,t){const i=this.currentTransform.scaleX??1,n=this.currentTransform.scaleY??1,s=(this.currentTransform.x??0)+e*i,r=(this.currentTransform.y??0)+t*n,a=this.currentTransform.rotation??0;if(a===0)return{x:s,y:r};const c=Math.cos(a),l=Math.sin(a);return{x:s*c-r*l,y:s*l+r*c}}isYAxisUp(){return this.camera instanceof y.OrthographicCamera?this.camera.top>=this.camera.bottom:!0}createLineQuad(e,t,i,n,s){const r=t.x-e.x,a=t.y-e.y,c=Math.max(.001,Math.hypot(r,a)),l=Math.atan2(a,r),h=new y.PlaneGeometry(c,i),d=new y.MeshBasicMaterial({color:n,transparent:s<1,opacity:s,side:y.DoubleSide,depthTest:!1}),p=new y.Mesh(h,d);return p.position.set((e.x+t.x)/2,(e.y+t.y)/2,0),p.rotation.z=l,p}createQuadMesh(e,t,i,n,s,r=1){if(!s)return null;const a=new y.PlaneGeometry(i,n),c=Li(s),l=new y.MeshBasicMaterial({color:c.color,transparent:r*c.alpha<1,opacity:r*c.alpha,side:y.DoubleSide,depthTest:!1}),h=new y.Mesh(a,l);return h.position.set(e+i/2,t,0),h.renderOrder=1,h}createRectBorder(e,t,i,n,s,r,a){const c=Li(s),l=i/2,h=n/2,d=e+l,p=t,m=[new y.Vector3(d-l,p-h,0),new y.Vector3(d+l,p-h,0),new y.Vector3(d+l,p+h,0),new y.Vector3(d-l,p+h,0)],f=new y.BufferGeometry().setFromPoints(m),w=new y.LineBasicMaterial({color:c.color,transparent:a*c.alpha<1,opacity:a*c.alpha,linewidth:r,depthTest:!1});return new y.LineLoop(f,w)}clearFrame(){for(;this.frameGroup.children.length>0;){const e=this.frameGroup.children.pop();e&&this.disposeObject(e)}}disposeObject(e){if("geometry"in e&&e.geometry instanceof y.BufferGeometry&&e.geometry.dispose(),"material"in e){const t=e.material;Array.isArray(t)?t.forEach(i=>this.disposeMaterial(i)):t&&this.disposeMaterial(t)}"children"in e&&e.children.length>0&&[...e.children].forEach(t=>this.disposeObject(t)),e.removeFromParent()}disposeMaterial(e){const t=e;t.map&&t.map.dispose(),e.dispose()}getResolution(){return this.canvas?{x:this.canvas.width||1,y:this.canvas.height||1}:typeof window<"u"?{x:window.innerWidth||1,y:window.innerHeight||1}:{x:1,y:1}}}function Ll(o){return o===B.MTextLineAlignment.TOP?"superscript":o===B.MTextLineAlignment.BOTTOM?"subscript":"normal"}function Tl(o){return o==="superscript"?B.MTextLineAlignment.TOP:o==="subscript"?B.MTextLineAlignment.BOTTOM:B.MTextLineAlignment.MIDDLE}function wr(o){return{...o,align:Tl(o.script)}}function Bt(o){return{underline:o.underline,overline:o.overline,strikeThrough:o.strikeThrough,script:Ll(o.align),aci:o.aci,rgb:o.rgb?[...o.rgb]:null,align:o.align,fontFace:{...o.fontFace},capHeight:{...o.capHeight},widthFactor:{...o.widthFactor},charTrackingFactor:{...o.charTrackingFactor},oblique:o.oblique,paragraph:{indent:o.paragraph.indent,left:o.paragraph.left,right:o.paragraph.right,align:o.paragraph.align,tabs:[...o.paragraph.tabs]}}}function J(o){return{underline:o.underline,overline:o.overline,strikeThrough:o.strikeThrough,script:o.script,aci:o.aci,rgb:o.rgb?[...o.rgb]:null,align:o.align,fontFace:{...o.fontFace},capHeight:{...o.capHeight},widthFactor:{...o.widthFactor},charTrackingFactor:{...o.charTrackingFactor},oblique:o.oblique,paragraph:{indent:o.paragraph.indent,left:o.paragraph.left,right:o.paragraph.right,align:o.paragraph.align,tabs:[...o.paragraph.tabs]}}}function Dt(o){return o.type==="char"||o.type==="stack"||o.type==="paragraphBreak"||o.type==="columnBreak"||o.type==="wrapAtDimLine"}function Il(o,e){return o.underline===e.underline&&o.overline===e.overline&&o.strikeThrough===e.strikeThrough&&o.script===e.script&&o.aci===e.aci&&JSON.stringify(o.rgb)===JSON.stringify(e.rgb)&&o.align===e.align&&o.fontFace.family===e.fontFace.family&&o.fontFace.style===e.fontFace.style&&o.fontFace.weight===e.fontFace.weight&&o.capHeight.value===e.capHeight.value&&o.capHeight.isRelative===e.capHeight.isRelative&&o.widthFactor.value===e.widthFactor.value&&o.widthFactor.isRelative===e.widthFactor.isRelative&&o.charTrackingFactor.value===e.charTrackingFactor.value&&o.charTrackingFactor.isRelative===e.charTrackingFactor.isRelative&&o.oblique===e.oblique&&o.paragraph.indent===e.paragraph.indent&&o.paragraph.left===e.paragraph.left&&o.paragraph.right===e.paragraph.right&&o.paragraph.align===e.paragraph.align&&JSON.stringify(o.paragraph.tabs)===JSON.stringify(e.paragraph.tabs)}function br(o,e){const t=o??Bt(new B.MTextContext),i=wr(t),n=wr(e);if(Il(i,n))return"";let s="";if(i.underline!==n.underline&&(s+=n.underline?"\\L":"\\l"),i.overline!==n.overline&&(s+=n.overline?"\\O":"\\o"),i.strikeThrough!==n.strikeThrough&&(s+=n.strikeThrough?"\\K":"\\k"),i.align!==n.align&&(s+=`\\A${n.align};`),(i.aci!==n.aci||JSON.stringify(i.rgb)!==JSON.stringify(n.rgb))&&(n.rgb?s+=`\\c${B.rgb2int(n.rgb)};`:s+=`\\C${n.aci??256};`),i.fontFace.family!==n.fontFace.family||i.fontFace.style!==n.fontFace.style||i.fontFace.weight!==n.fontFace.weight){const r=n.fontFace.weight>=700?1:0,a=n.fontFace.style==="Italic"?1:0;s+=`\\f${n.fontFace.family}|b${r}|i${a};`}return(i.capHeight.value!==n.capHeight.value||i.capHeight.isRelative!==n.capHeight.isRelative)&&(s+=`\\H${In(n.capHeight)};`),(i.widthFactor.value!==n.widthFactor.value||i.widthFactor.isRelative!==n.widthFactor.isRelative)&&(s+=`\\W${In(n.widthFactor)};`),(i.charTrackingFactor.value!==n.charTrackingFactor.value||i.charTrackingFactor.isRelative!==n.charTrackingFactor.isRelative)&&(s+=`\\T${In(n.charTrackingFactor)};`),i.oblique!==n.oblique&&(s+=`\\Q${Mt(n.oblique)};`),JSON.stringify(i.paragraph)!==JSON.stringify(n.paragraph)&&(s+=`\\p${El(n.paragraph)};`),s}function In(o){return`${Mt(o.value)}${o.isRelative?"x":""}`}function Mt(o){return Number.isInteger(o),o.toString()}function El(o){const e=[`i${Mt(o.indent)}`,`l${Mt(o.left)}`,`r${Mt(o.right)}`];return o.align!==B.MTextParagraphAlignment.DEFAULT&&e.push(`q${kl(o.align)}`),o.tabs.length>0&&e.push(`t${o.tabs.map(t=>String(t)).join(",")}`),e.join(",")}function kl(o){switch(o){case B.MTextParagraphAlignment.LEFT:return"l";case B.MTextParagraphAlignment.RIGHT:return"r";case B.MTextParagraphAlignment.CENTER:return"c";case B.MTextParagraphAlignment.JUSTIFIED:return"j";case B.MTextParagraphAlignment.DISTRIBUTED:return"d";default:return"x"}}function vr(o,e,t={}){const i=new B.MTextParser(o,e,{...t,yieldPropertyCommands:!1}),n=[];for(const s of i.parse()){const r=Bt(s.ctx);switch(s.type){case B.TokenType.WORD:{const a=s.data;for(const c of a)n.push({type:"char",value:c,style:J(r)});break}case B.TokenType.SPACE:n.push({type:"char",value:" ",style:J(r)});break;case B.TokenType.NBSP:n.push({type:"char",value:" ",style:J(r)});break;case B.TokenType.TABULATOR:n.push({type:"char",value:" ",style:J(r)});break;case B.TokenType.STACK:{const[a,c,l]=s.data,h=J(r);l==="^"&&(a.length===0&&c.length>0?h.script="subscript":a.length>0&&c.length===0?h.script="superscript":h.script="normal"),n.push({type:"stack",numerator:a,denominator:c,divider:l,style:h});break}case B.TokenType.NEW_PARAGRAPH:n.push({type:"paragraphBreak",style:J(r)});break;case B.TokenType.NEW_COLUMN:n.push({type:"columnBreak",style:J(r)});break;case B.TokenType.WRAP_AT_DIMLINE:n.push({type:"wrapAtDimLine",style:J(r)});break}}return{nodes:n}}function Bl(o){const e=Bt(new B.MTextContext);let t="",i=0;for(;i<o.nodes.length;){const n=o.nodes[i];if(!n)break;if(!Dt(n)){t+=Cr(n),i+=1;continue}const s=n.style;let r="",a=i;for(;a<o.nodes.length;){const c=o.nodes[a];if(!c||!Dt(c)||!Ar(s,c.style))break;r+=Cr(c),a+=1}Ar(s,e)?t+=r:t+=`{${br(null,s)}${r}}`,i=a}return t}function Ti(o,e,t){if(t<=0)return o;const i=Ii(e,0,o.nodes.length),n=Ii(t,0,o.nodes.length-i);return o.nodes.splice(i,n),o}function Dl(o,e,t,i,n){const s=Ii(e,0,o.nodes.length),r=Ii(t,0,o.nodes.length-s),a=n??xr(o,s)??Bt(new B.MTextContext),c=Fl(i,a);return o.nodes.splice(s,r,...c),o}function xr(o,e){for(let t=e-1;t>=0;t--){const i=o.nodes[t];if(i&&Dt(i))return J(i.style)}for(let t=e;t<o.nodes.length;t++){const i=o.nodes[t];if(i&&Dt(i))return J(i.style)}}function Ml(o){return o===" "?"\\~":o===" "?"^I":o==="\\"?"\\\\":o==="{"?"\\{":o==="}"?"\\}":o==="^"?"\\U+005E":o==="%"?"\\U+0025":o===`
|
|
715
|
+
`?"\\P":o==="\r"?"":o}function Sr(o){return o.replace(/[\\;/#^]/g,"\\$&")}function Ar(o,e){return br(o,e)===""}function Cr(o){switch(o.type){case"char":return Ml(o.value);case"stack":return Ol(o.numerator,o.denominator,o.divider);case"paragraphBreak":return"\\P";case"columnBreak":return"\\N";case"wrapAtDimLine":return"\\X"}}function Ol(o,e,t){const i=Sr(o),n=Sr(e);if(t==="^"){if(i.length===0&&n.length>0)return`\\S^ ${n};`;if(i.length>0&&n.length===0)return`\\S${i}^ ;`;if(i.length===0&&n.length===0)return"\\S^ ;"}return`\\S${i}${t}${n};`}function Fl(o,e){const t=[];for(const i of o){if(i===`
|
|
716
|
+
`){t.push({type:"paragraphBreak",style:J(e)});continue}t.push({type:"char",value:i,style:J(e)})}return t}function Ii(o,e,t){return Math.max(e,Math.min(t,o))}class Q{constructor(e={nodes:[]}){I(this,"_ast");I(this,"_cursor");I(this,"_selection",null);this._ast=typeof e=="string"?vr(e):Q.cloneAst(e),this._cursor=this._ast.nodes.length}static fromMText(e,t){return new Q(vr(e,t))}get ast(){return this._ast}get length(){return this._ast.nodes.length}get cursor(){return this._cursor}set cursor(e){this._cursor=Q.clamp(e,0,this.length),this._selection=null}get selection(){return this._selection?{...this._selection}:null}setSelection(e,t){const i=Q.normalizeSelection(e,t,this.length);return this._selection=i.start===i.end?null:i,this._cursor=Q.clamp(t,0,this.length),this}clearSelection(){return this._selection=null,this}moveCursor(e,t=!1){const i=Q.clamp(this._cursor+e,0,this.length);if(t){const n=this._selection?this._selection.start:this._cursor;this.setSelection(n,i)}else this.cursor=i;return this}selectAll(){return this.setSelection(0,this.length),this}insertText(e,t){const{start:i,end:n}=this.getActiveRange();return Dl(this._ast,i,n-i,e,t),this._cursor=i+e.length,this._selection=null,this}deleteBackward(e=1){if(this.hasSelection()){const{start:i,end:n}=this.getActiveRange();return Ti(this._ast,i,n-i),this._cursor=i,this._selection=null,this}if(e<=0||this._cursor<=0)return this;const t=Math.min(e,this._cursor);return Ti(this._ast,this._cursor-t,t),this._cursor-=t,this}deleteForward(e=1){if(this.hasSelection()){const{start:t,end:i}=this.getActiveRange();return Ti(this._ast,t,i-t),this._cursor=t,this._selection=null,this}return e<=0||this._cursor>=this.length?this:(Ti(this._ast,this._cursor,e),this)}replaceSelection(e,t){return this.insertText(e,t)}toMText(){return Bl(this._ast)}transaction(e){const t={ast:Q.cloneAst(this._ast),cursor:this._cursor,selection:this._selection?{...this._selection}:null};try{e(this)}catch(i){throw this._ast=t.ast,this._cursor=t.cursor,this._selection=t.selection,i}return this}hasSelection(){return!!(this._selection&&this._selection.start!==this._selection.end)}getActiveRange(){return this._selection?{...this._selection}:{start:this._cursor,end:this._cursor}}getReferenceStyle(e){return xr(this._ast,e)??Bt(new B.MTextContext)}static cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:J(t.style)}:t.type==="stack"?{...t,style:J(t.style)}:{...t,style:J(t.style)})}}static normalizeSelection(e,t,i){const n=Q.clamp(e,0,i),s=Q.clamp(t,0,i);return n<=s?{start:n,end:s}:{start:s,end:n}}static clamp(e,t,i){return Math.max(t,Math.min(i,e))}}class En{constructor(e){I(this,"document");I(this,"selectionAnchor",null);this.document=e}get anchor(){return this.selectionAnchor}execute(e){switch(e.type){case"setCursor":this.document.cursor=e.index,this.selectionAnchor=null;break;case"setSelection":this.document.setSelection(e.start,e.end),this.selectionAnchor=e.start;break;case"clearSelection":this.document.clearSelection(),this.selectionAnchor=null;break;case"moveLeft":this.moveCursorTo(this.document.cursor-1,e.extend??!1);break;case"moveRight":this.moveCursorTo(this.document.cursor+1,e.extend??!1);break;case"moveToStart":this.moveCursorTo(0,e.extend??!1);break;case"moveToEnd":this.moveCursorTo(this.document.length,e.extend??!1);break;case"selectAll":this.document.selectAll(),this.selectionAnchor=0;break;case"insertText":this.document.insertText(e.text,e.style),this.selectionAnchor=null;break;case"replaceSelection":this.document.replaceSelection(e.text,e.style),this.selectionAnchor=null;break;case"backspace":this.document.deleteBackward(e.count??1),this.selectionAnchor=null;break;case"delete":this.document.deleteForward(e.count??1),this.selectionAnchor=null;break}return this}handleKeyEvent(e){const t=!!(e.metaKey||e.ctrlKey);return t&&!e.altKey&&e.key.toLowerCase()==="a"?(this.execute({type:"selectAll"}),!0):e.key==="ArrowLeft"?(this.execute({type:"moveLeft",extend:!!e.shiftKey}),!0):e.key==="ArrowRight"?(this.execute({type:"moveRight",extend:!!e.shiftKey}),!0):e.key==="Home"?(this.execute({type:"moveToStart",extend:!!e.shiftKey}),!0):e.key==="End"?(this.execute({type:"moveToEnd",extend:!!e.shiftKey}),!0):e.key==="Backspace"?(this.execute({type:"backspace"}),!0):e.key==="Delete"?(this.execute({type:"delete"}),!0):e.key==="Enter"?(this.execute({type:"insertText",text:`
|
|
717
|
+
`}),!0):e.key==="Tab"?(this.execute({type:"insertText",text:" "}),!0):!t&&!e.altKey&&e.key.length===1?(this.execute({type:"insertText",text:e.key}),!0):!1}moveCursorTo(e,t){var n;const i=Math.max(0,Math.min(e,this.document.length));if(t){this.selectionAnchor===null&&(this.selectionAnchor=((n=this.document.selection)==null?void 0:n.start)??this.document.cursor),this.document.setSelection(this.selectionAnchor,i);return}this.document.cursor=i,this.selectionAnchor=null}}const Rl={bold:'<svg viewBox="0 0 24 24"><path d="M7.8 19c-.3 0-.5 0-.6-.2l-.2-.5V5.7c0-.2 0-.4.2-.5l.6-.2h5c1.5 0 2.7.3 3.5 1 .7.6 1.1 1.4 1.1 2.5a3 3 0 0 1-.6 1.9c-.4.6-1 1-1.6 1.2.4.1.9.3 1.3.6s.8.7 1 1.2c.4.4.5 1 .5 1.6 0 1.3-.4 2.3-1.3 3-.8.7-2.1 1-3.8 1H7.8Zm5-8.3c.6 0 1.2-.1 1.6-.5.4-.3.6-.7.6-1.3 0-1.1-.8-1.7-2.3-1.7H9.3v3.5h3.4Zm.5 6c.7 0 1.3-.1 1.7-.4.4-.4.6-.9.6-1.5s-.2-1-.7-1.4c-.4-.3-1-.4-2-.4H9.4v3.8h4Z" fill-rule="evenodd"></path></svg>',italic:'<svg viewBox="0 0 24 24"><path d="m16.7 4.7-.1.9h-.3c-.6 0-1 0-1.4.3-.3.3-.4.6-.5 1.1l-2.1 9.8v.6c0 .5.4.8 1.4.8h.2l-.2.8H8l.2-.8h.2c1.1 0 1.8-.5 2-1.5l2-9.8.1-.5c0-.6-.4-.8-1.4-.8h-.3l.2-.9h5.8Z" fill-rule="evenodd"></path></svg>',underline:'<svg viewBox="0 0 24 24"><path d="M16 5c.6 0 1 .4 1 1v5.5a4 4 0 0 1-.4 1.8l-1 1.4a5.3 5.3 0 0 1-5.5 1 5 5 0 0 1-1.6-1c-.5-.4-.8-.9-1.1-1.4a4 4 0 0 1-.4-1.8V6c0-.6.4-1 1-1s1 .4 1 1v5.5c0 .3 0 .6.2 1l.6.7a3.3 3.3 0 0 0 2.2.8 3.4 3.4 0 0 0 2.2-.8c.3-.2.4-.5.6-.8l.2-.9V6c0-.6.4-1 1-1ZM8 17h8c.6 0 1 .4 1 1s-.4 1-1 1H8a1 1 0 0 1 0-2Z" fill-rule="evenodd"></path></svg>',overline:'<svg viewBox="0 0 24 24"><path d="M5 4h14v1.5H5V4zm7 3.5c3.04 0 5.5 2.46 5.5 5.5v4.5h-2.25v-4.5c0-1.79-1.46-3.25-3.25-3.25S8.75 11.21 8.75 13v4.5H6.5V13c0-3.04 2.46-5.5 5.5-5.5z"></path></svg>',strike:'<svg viewBox="0 0 24 24"><g fill-rule="evenodd"><path d="M15.6 8.5c-.5-.7-1-1.1-1.3-1.3-.6-.4-1.3-.6-2-.6-2.7 0-2.8 1.7-2.8 2.1 0 1.6 1.8 2 3.2 2.3 4.4.9 4.6 2.8 4.6 3.9 0 1.4-.7 4.1-5 4.1A6.2 6.2 0 0 1 7 16.4l1.5-1.1c.4.6 1.6 2 3.7 2 1.6 0 2.5-.4 3-1.2.4-.8.3-2-.8-2.6-.7-.4-1.6-.7-2.9-1-1-.2-3.9-.8-3.9-3.6C7.6 6 10.3 5 12.4 5c2.9 0 4.2 1.6 4.7 2.4l-1.5 1.1Z"></path><path d="M5 11h14a1 1 0 0 1 0 2H5a1 1 0 0 1 0-2Z" fill-rule="nonzero"></path></g></svg>',superscript:'<svg viewBox="0 0 24 24"><path d="M15 9.4 10.4 14l4.6 4.6-1.4 1.4L9 15.4 4.4 20 3 18.6 7.6 14 3 9.4 4.4 8 9 12.6 13.6 8 15 9.4Zm5.9 1.6h-5v-1l1-.8 1.7-1.6c.3-.5.5-.9.5-1.3 0-.3 0-.5-.2-.7-.2-.2-.5-.3-.9-.3l-.8.2-.7.4-.4-1.2c.2-.2.5-.4 1-.5.3-.2.8-.2 1.2-.2.8 0 1.4.2 1.8.6.4.4.6 1 .6 1.6 0 .5-.2 1-.5 1.5l-1.3 1.4-.6.5h2.6V11Z" fill-rule="nonzero"></path></svg>',subscript:'<svg viewBox="0 0 24 24"><path d="m10.4 10 4.6 4.6-1.4 1.4L9 11.4 4.4 16 3 14.6 7.6 10 3 5.4 4.4 4 9 8.6 13.6 4 15 5.4 10.4 10ZM21 19h-5v-1l1-.8 1.7-1.6c.3-.4.5-.8.5-1.2 0-.3 0-.6-.2-.7-.2-.2-.5-.3-.9-.3a2 2 0 0 0-.8.2l-.7.3-.4-1.1 1-.6 1.2-.2c.8 0 1.4.3 1.8.7.4.4.6.9.6 1.5s-.2 1.1-.5 1.6a8 8 0 0 1-1.3 1.3l-.6.6h2.6V19Z" fill-rule="nonzero"></path></svg>',stack:'<svg viewBox="0 0 24 24"><path d="M12.4065 5.44832C12.8151 5.44832 13.1994 5.56542 13.5595 5.7996C13.9265 6.0267 14.2208 6.36024 14.4424 6.80022C14.664 7.23312 14.7748 7.74407 14.7748 8.33309C14.7748 8.9292 14.664 9.44725 14.4424 9.88724C14.2208 10.3201 13.9265 10.6501 13.5595 10.8772C13.1994 11.1043 12.8151 11.2179 12.4065 11.2179C12.0464 11.2179 11.7037 11.1291 11.3782 10.9517C11.0527 10.7743 10.7931 10.5082 10.5992 10.1534C10.5715 10.4585 10.5507 10.7743 10.5368 11.1008H9.75781V3H10.6407V6.4383C10.8415 6.11185 11.0977 5.86702 11.4094 5.7038C11.721 5.53348 12.0534 5.44832 12.4065 5.44832ZM12.2923 10.3663C12.7631 10.3663 13.1405 10.1888 13.4245 9.83402C13.7084 9.47919 13.8503 8.97888 13.8503 8.33309C13.8503 7.69439 13.7084 7.19763 13.4245 6.8428C13.1405 6.48797 12.7631 6.31056 12.2923 6.31056C11.8422 6.31056 11.4544 6.47378 11.1289 6.80022C10.8034 7.12667 10.6407 7.63762 10.6407 8.33309C10.6407 8.80856 10.7203 9.19887 10.8796 9.50402C11.0389 9.80918 11.2432 10.0292 11.4925 10.164C11.7417 10.2988 12.0083 10.3663 12.2923 10.3663Z"></path><path d="M12.0949 14.9531C12.7043 14.9531 13.2029 15.1447 13.5906 15.5279C13.9784 15.9041 14.1723 16.4434 14.1723 17.146V20.6056H13.3933C13.3725 20.2436 13.3587 20.0094 13.3517 19.903C13.1856 20.1727 12.9605 20.3785 12.6766 20.5204C12.3996 20.6552 12.0811 20.7227 11.721 20.7227C11.3747 20.7227 11.0493 20.6588 10.7446 20.531C10.4468 20.3962 10.2079 20.2011 10.0279 19.9456C9.84783 19.683 9.75781 19.3708 9.75781 19.0088C9.75781 18.4624 9.97248 18.033 10.4018 17.7208C10.8381 17.4014 11.399 17.2418 12.0845 17.2418C12.4723 17.2418 12.8739 17.295 13.2894 17.4014V17.3056C13.2894 16.7876 13.1856 16.4044 12.9778 16.156C12.777 15.9005 12.4688 15.7728 12.0534 15.7728C11.721 15.7728 11.444 15.8437 11.2224 15.9857C11.0008 16.1276 10.8138 16.337 10.6615 16.6137L9.98633 16.2199C10.1525 15.8367 10.4226 15.5315 10.7965 15.3044C11.1774 15.0702 11.6102 14.9531 12.0949 14.9531ZM13.2894 18.1572C12.8532 18.0437 12.455 17.9869 12.0949 17.9869C11.6448 17.9869 11.2951 18.0756 11.0458 18.253C10.8034 18.4305 10.6823 18.6788 10.6823 18.9982C10.6823 19.2962 10.7861 19.5304 10.9939 19.7007C11.2016 19.864 11.4717 19.9456 11.8041 19.9456C12.2126 19.9456 12.5623 19.8249 12.8532 19.5836C13.144 19.3353 13.2894 18.9946 13.2894 18.5617V18.1572Z""></path><rect x="6.02344" y="12.7119" width="11.9532" height="0.747077"></rect></svg>'},Pr="mlightcad-mtext-toolbar-style",_r=["Arial","Helvetica","Verdana","Tahoma","Trebuchet MS","Times New Roman","Georgia","Courier New","system-ui","sans-serif","serif","monospace"];function jl(){if(document.getElementById(Pr))return;const o=document.createElement("style");o.id=Pr,o.textContent=`
|
|
718
|
+
.ml-mtext-toolbar {
|
|
719
|
+
position: fixed;
|
|
720
|
+
left: 0;
|
|
721
|
+
top: 0;
|
|
722
|
+
z-index: 2147483000;
|
|
723
|
+
display: inline-flex;
|
|
724
|
+
align-items: center;
|
|
725
|
+
gap: 10px;
|
|
726
|
+
border-radius: 8px;
|
|
727
|
+
border: 1px solid;
|
|
728
|
+
padding: 8px;
|
|
729
|
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
|
|
730
|
+
font-size: 12px;
|
|
731
|
+
line-height: 1;
|
|
732
|
+
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.24);
|
|
733
|
+
user-select: none;
|
|
734
|
+
}
|
|
735
|
+
.ml-mtext-toolbar[data-theme='dark'] {
|
|
736
|
+
background: linear-gradient(180deg, #2a2d33 0%, #1d2025 100%);
|
|
737
|
+
border-color: #444b58;
|
|
738
|
+
color: #e8ecf4;
|
|
739
|
+
}
|
|
740
|
+
.ml-mtext-toolbar[data-theme='light'] {
|
|
741
|
+
background: linear-gradient(180deg, #ffffff 0%, #f2f4f8 100%);
|
|
742
|
+
border-color: #cfd5df;
|
|
743
|
+
color: #1e2430;
|
|
744
|
+
}
|
|
745
|
+
.ml-mtext-toolbar__group {
|
|
746
|
+
display: inline-flex;
|
|
747
|
+
align-items: center;
|
|
748
|
+
gap: 4px;
|
|
749
|
+
}
|
|
750
|
+
.ml-mtext-toolbar__separator {
|
|
751
|
+
width: 1px;
|
|
752
|
+
height: 24px;
|
|
753
|
+
opacity: 0.35;
|
|
754
|
+
}
|
|
755
|
+
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__separator {
|
|
756
|
+
background: #576177;
|
|
757
|
+
}
|
|
758
|
+
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__separator {
|
|
759
|
+
background: #b8c0ce;
|
|
760
|
+
}
|
|
761
|
+
.ml-mtext-toolbar__select,
|
|
762
|
+
.ml-mtext-toolbar__input,
|
|
763
|
+
.ml-mtext-toolbar__color,
|
|
764
|
+
.ml-mtext-toolbar__btn {
|
|
765
|
+
border: 1px solid;
|
|
766
|
+
border-radius: 6px;
|
|
767
|
+
height: 34px;
|
|
768
|
+
}
|
|
769
|
+
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__select,
|
|
770
|
+
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__input,
|
|
771
|
+
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__color,
|
|
772
|
+
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn {
|
|
773
|
+
background: #12161d;
|
|
774
|
+
border-color: #454d5f;
|
|
775
|
+
color: #f2f5fb;
|
|
776
|
+
}
|
|
777
|
+
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__select,
|
|
778
|
+
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__input,
|
|
779
|
+
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__color,
|
|
780
|
+
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn {
|
|
781
|
+
background: #ffffff;
|
|
782
|
+
border-color: #c7cdd8;
|
|
783
|
+
color: #1f2632;
|
|
784
|
+
}
|
|
785
|
+
.ml-mtext-toolbar__select {
|
|
786
|
+
min-width: 140px;
|
|
787
|
+
padding: 0 8px;
|
|
788
|
+
}
|
|
789
|
+
.ml-mtext-toolbar__input {
|
|
790
|
+
width: 64px;
|
|
791
|
+
padding: 0 8px;
|
|
792
|
+
}
|
|
793
|
+
.ml-mtext-toolbar__color {
|
|
794
|
+
width: 40px;
|
|
795
|
+
padding: 2px;
|
|
796
|
+
display: flex;
|
|
797
|
+
align-items: center;
|
|
798
|
+
justify-content: center;
|
|
799
|
+
}
|
|
800
|
+
.ml-mtext-toolbar__btn {
|
|
801
|
+
width: 34px;
|
|
802
|
+
display: inline-flex;
|
|
803
|
+
align-items: center;
|
|
804
|
+
justify-content: center;
|
|
805
|
+
cursor: pointer;
|
|
806
|
+
transition: border-color 0.14s ease, background 0.14s ease, color 0.14s ease;
|
|
807
|
+
}
|
|
808
|
+
.ml-mtext-toolbar__btn svg {
|
|
809
|
+
width: 24px;
|
|
810
|
+
height: 24px;
|
|
811
|
+
fill: currentColor;
|
|
812
|
+
}
|
|
813
|
+
.ml-mtext-toolbar__btn.is-active {
|
|
814
|
+
border-color: #2f9dff;
|
|
815
|
+
color: #2f9dff;
|
|
816
|
+
}
|
|
817
|
+
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn.is-active {
|
|
818
|
+
background: linear-gradient(180deg, #123252 0%, #0c243d 100%);
|
|
819
|
+
color: #8fcbff;
|
|
820
|
+
box-shadow: inset 0 0 0 1px rgba(143, 203, 255, 0.18);
|
|
821
|
+
}
|
|
822
|
+
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn.is-active {
|
|
823
|
+
background: linear-gradient(180deg, #dcebff 0%, #cfe3ff 100%);
|
|
824
|
+
color: #1d67ad;
|
|
825
|
+
box-shadow: inset 0 0 0 1px rgba(29, 103, 173, 0.16);
|
|
826
|
+
}
|
|
827
|
+
.ml-mtext-toolbar[data-theme='dark'] .ml-mtext-toolbar__btn:hover {
|
|
828
|
+
background: #1f2530;
|
|
829
|
+
}
|
|
830
|
+
.ml-mtext-toolbar[data-theme='light'] .ml-mtext-toolbar__btn:hover {
|
|
831
|
+
background: #edf3ff;
|
|
832
|
+
}
|
|
833
|
+
`,document.head.appendChild(o)}function kn(o){return Math.max(0,Math.min(16777215,Math.round(o)))}function Lr(o){return`#${(o===null?16777215:kn(o)).toString(16).padStart(6,"0")}`}function Nl(o){return/^#[0-9a-fA-F]{6}$/.test(o)?Number.parseInt(o.slice(1),16):16777215}function zl(o){return o.isRgb&&o.rgbValue!==null?Lr(o.rgbValue):o.isAci&&o.aci!==null?Lr(B.getColorByIndex(o.aci)):"#ffffff"}function Tr(o){const e=new B.MTextColor;return e.rgbValue=Nl(o),e}function Ir(o){const e=new B.MTextColor;return o.aci!==null&&Number.isFinite(o.aci)?(e.aci=o.aci,e):o.rgb!==null?(e.rgbValue=kn(o.rgb),e):(e.rgbValue=16777215,e)}function Vl(o){const e=o.trim().toLowerCase();return/^#[0-9a-f]{6}$/.test(e)?e:/^[0-9a-f]{6}$/.test(e)?`#${e}`:null}function je(o,e){const t=document.createElement("button");return t.type="button",t.className="ml-mtext-toolbar__btn",t.title=o,t.setAttribute("aria-label",o),t.setAttribute("aria-pressed","false"),t.innerHTML=Rl[e],t}function Gl(o){const e=o&&o.length>0?o:_r,t=[],i=new Set;for(const n of e){const s=n.trim();!s||i.has(s)||(i.add(s),t.push(s))}return t.length>0?t:[..._r]}class Kl{constructor(e){I(this,"anchorElement");I(this,"root");I(this,"controls");I(this,"onFormatChange");I(this,"onToggleStack");I(this,"onToggleSuperscript");I(this,"onToggleSubscript");I(this,"theme");I(this,"colorPicker");jl(),this.anchorElement=e.anchorElement,this.onFormatChange=e.onFormatChange,this.onToggleStack=e.onToggleStack??(()=>{}),this.onToggleSuperscript=e.onToggleSuperscript??(()=>!1),this.onToggleSubscript=e.onToggleSubscript??(()=>!1),this.theme=e.theme,this.root=document.createElement("div"),this.root.className="ml-mtext-toolbar";const t=document.createElement("div");t.className="ml-mtext-toolbar__group";const i=document.createElement("select");i.className="ml-mtext-toolbar__select";for(const w of Gl(e.fontFamilies)){const x=document.createElement("option");x.value=w,x.textContent=w,i.appendChild(x)}const n=document.createElement("input");n.className="ml-mtext-toolbar__input",n.type="number",n.min="1",n.max="1024",n.step="1",this.colorPicker=this.createColorPicker(e.colorPicker,e.initialFormat),t.append(i,n,this.colorPicker.host);const s=document.createElement("div");s.className="ml-mtext-toolbar__separator";const r=document.createElement("div");r.className="ml-mtext-toolbar__group";const a=je("Bold","bold"),c=je("Italic","italic"),l=je("Underline","underline"),h=je("Overline","overline"),d=je("Strike Through","strike"),p=je("Superscript","superscript"),m=je("Subscript","subscript"),f=je("Stack","stack");r.append(a,c,l,h,d,p,m,f),this.root.append(t,s,r),this.controls={fontFamily:i,fontSize:n,boldBtn:a,italicBtn:c,underlineBtn:l,overlineBtn:h,strikeBtn:d,superscriptBtn:p,subscriptBtn:m,stackBtn:f},this.setTheme(this.theme),this.bindEvents(),(e.container??document.body).appendChild(this.root)}setTheme(e){this.theme=e,this.root.dataset.theme=e,this.colorPicker.setTheme(e)}getTheme(){return this.theme}setVisible(e){this.root.style.display=e?"inline-flex":"none"}setSession(e){this.anchorElement=e.anchorElement,this.onFormatChange=e.onFormatChange,this.onToggleStack=e.onToggleStack,this.onToggleSuperscript=e.onToggleSuperscript??(()=>!1),this.onToggleSubscript=e.onToggleSubscript??(()=>!1)}setAnchor(e,t){const i=this.root.offsetWidth||0,n=this.root.offsetHeight||0,s=8,r=8,a=Math.max(s,window.innerWidth-i-8),c=Math.max(r,window.innerHeight-n-8),l=Math.max(s,Math.min(a,Math.round(e))),h=Math.max(r,Math.min(c,Math.round(t-n)));this.root.style.left=`${l}px`,this.root.style.top=`${h}px`}setFormat(e){this.ensureSelectValue(e.fontFamily),this.controls.fontSize.value=String(Math.max(1,Math.round(e.fontSize)));const t=Ir(e);this.colorPicker.setValue(t),this.setToggleState(this.controls.boldBtn,e.bold),this.setToggleState(this.controls.italicBtn,e.italic),this.setToggleState(this.controls.underlineBtn,e.underline),this.setToggleState(this.controls.overlineBtn,e.overline),this.setToggleState(this.controls.strikeBtn,e.strike),this.setToggleState(this.controls.superscriptBtn,e.script==="superscript"),this.setToggleState(this.controls.subscriptBtn,e.script==="subscript")}dispose(){this.colorPicker.dispose(),this.root.remove()}setStackActive(e){this.setToggleState(this.controls.stackBtn,e)}setToggleState(e,t){e.classList.toggle("is-active",t),e.setAttribute("aria-pressed",t?"true":"false")}ensureSelectValue(e){if(!Array.from(this.controls.fontFamily.options).some(i=>i.value===e)){const i=document.createElement("option");i.value=e,i.textContent=e,this.controls.fontFamily.appendChild(i)}this.controls.fontFamily.value=e}bindEvents(){const e=()=>{const t=Math.max(1,Number(this.controls.fontSize.value)||1);this.controls.fontSize.value=String(Math.round(t)),this.onFormatChange({fontSize:t})};this.controls.fontFamily.addEventListener("change",()=>{this.onFormatChange({fontFamily:this.controls.fontFamily.value})}),this.controls.fontSize.addEventListener("input",e),this.controls.fontSize.addEventListener("change",e),this.controls.fontSize.addEventListener("blur",e),this.controls.fontSize.addEventListener("keydown",t=>{t.key==="Enter"&&(e(),this.anchorElement.focus({preventScroll:!0}))}),this.controls.boldBtn.addEventListener("click",()=>{this.onFormatChange({bold:!this.controls.boldBtn.classList.contains("is-active")})}),this.controls.italicBtn.addEventListener("click",()=>{this.onFormatChange({italic:!this.controls.italicBtn.classList.contains("is-active")})}),this.controls.underlineBtn.addEventListener("click",()=>{this.onFormatChange({underline:!this.controls.underlineBtn.classList.contains("is-active")})}),this.controls.overlineBtn.addEventListener("click",()=>{this.onFormatChange({overline:!this.controls.overlineBtn.classList.contains("is-active")})}),this.controls.strikeBtn.addEventListener("click",()=>{this.onFormatChange({strike:!this.controls.strikeBtn.classList.contains("is-active")})}),this.controls.superscriptBtn.addEventListener("click",()=>{if(this.onToggleSuperscript())return;const t=this.controls.superscriptBtn.classList.contains("is-active");this.onFormatChange({script:t?"normal":"superscript"})}),this.controls.subscriptBtn.addEventListener("click",()=>{if(this.onToggleSubscript())return;const t=this.controls.subscriptBtn.classList.contains("is-active");this.onFormatChange({script:t?"normal":"subscript"})}),this.controls.stackBtn.addEventListener("click",()=>{this.onToggleStack()}),this.root.addEventListener("mousedown",t=>{const i=t.target;i&&(i.closest('[data-ml-mtext-toolbar-interactive="true"]')||i.tagName==="INPUT"||i.tagName==="SELECT"||i.tagName==="OPTION"||(t.preventDefault(),this.anchorElement.focus({preventScroll:!0})))})}createColorPicker(e,t){if(!e){const a=document.createElement("input");return a.className="ml-mtext-toolbar__color",a.type="color",a.dataset.mlMtextToolbarInteractive="true",a.addEventListener("input",()=>{this.applyColorChange(Tr(a.value))}),{host:a,setValue:c=>{const l=Vl(zl(c));l&&(a.value=l)},setTheme:()=>{},dispose:()=>{}}}const i=document.createElement("div");i.className="ml-mtext-toolbar__color",i.dataset.mlMtextToolbarInteractive="true";const n=t?Ir(t):Tr("#ffffff"),r=e({container:i,theme:this.theme,initialColor:n,onChange:a=>{this.applyColorChange(a)}})??{};return{host:i,setValue:a=>{var c;(c=r.setValue)==null||c.call(r,a)},setTheme:a=>{var c;(c=r.setTheme)==null||c.call(r,a)},dispose:()=>{var a;(a=r.dispose)==null||a.call(r)}}}applyColorChange(e){if(e.isAci&&e.aci!==null){this.onFormatChange({aci:e.aci});return}if(e.isRgb&&e.rgbValue!==null){this.onFormatChange({aci:null,rgb:kn(e.rgbValue)});return}this.onFormatChange({aci:null,rgb:16777215})}}function Er(o,e){const t=Math.max(1,o),i=e;return i===void 0||i===1||i===4||i===7||i===10?0:i===2||i===5||i===8||i===11?-t/2:i===3||i===6||i===9||i===12?-t:0}const Ei="__mlightcadMTextInputBoxSceneRoot",N=class N{constructor(e){I(this,"scene");I(this,"camera");I(this,"mtextRenderer");I(this,"cursorRenderer");I(this,"width");I(this,"position");I(this,"mtextInsertionOffset",new y.Vector3(0,0,0));I(this,"enableWordWrap");I(this,"mtextString","");I(this,"editorLineSpaceFactor",null);I(this,"editorAttachmentPoint",B.MTextAttachmentPoint.TopLeft);I(this,"cursorIndex",0);I(this,"selectionStart",0);I(this,"selectionEnd",0);I(this,"baseFormat");I(this,"currentFormat");I(this,"defaultTextStyle");I(this,"cursorLogic");I(this,"layoutContainer",{x:0,y:0,width:1,height:1});I(this,"isDragging",!1);I(this,"pendingCursorLineHint",null);I(this,"latestCursorLayoutData",{containerBox:{x:0,y:0,width:1,height:1},charBoxes:[]});I(this,"renderedObject",null);I(this,"boundingBoxObject",null);I(this,"boundingBoxPadding",1);I(this,"boundingBoxZOffset",.01);I(this,"rendererReady",!1);I(this,"pendingFontLoad",null);I(this,"lastFontKey","");I(this,"toolbarTheme","dark");I(this,"toolbarOffsetY",10);I(this,"debugMode",!1);I(this,"colorSettings");I(this,"debugVisibility",{showCharBoxes:!0,showLineIndices:!0,showCharIndices:!0,showChars:!0});I(this,"maxHistorySize",100);I(this,"undoStack",[]);I(this,"redoStack",[]);I(this,"document");I(this,"uiAdapter");I(this,"imeInput",null);I(this,"imeTarget",null);I(this,"lastImeTarget",null);I(this,"reopenTarget",null);I(this,"pointerTarget",null);I(this,"imeComposing",!1);I(this,"imeFocusTimer",null);I(this,"closed",!1);I(this,"toolbarEnabled",!0);I(this,"toolbarContainer",null);I(this,"toolbarFontFamilies",null);I(this,"toolbarColorPicker");I(this,"onImeKeyDown",e=>{if(!this.isActiveEditor()||!(e.ctrlKey||e.metaKey)&&!e.altKey&&e.key.length===1||e.isComposing||e.key==="Process")return;this.handleKeyDown(e)&&e.preventDefault()});I(this,"onWindowKeyDown",e=>{if(!this.isActiveEditor()||e.defaultPrevented)return;const t=e.target,i=(t==null?void 0:t.tagName)??"";if((i==="INPUT"||i==="TEXTAREA"||i==="SELECT"||!!(t!=null&&t.isContentEditable))&&t!==this.imeInput)return;if(!(e.ctrlKey||e.metaKey)&&!e.altKey&&e.key.length===1||this.imeComposing||e.isComposing||e.key==="Process"){this.refocusImeInputSoon();return}this.handleKeyDown(e)&&(e.preventDefault(),this.refocusImeInputSoon())});I(this,"onImeBeforeInput",e=>{if(!this.isActiveEditor()||e.isComposing)return;const t=e.inputType;if(t==="insertText"||t==="insertCompositionText"){this.handleTextInput(e.data??"")&&e.preventDefault();return}t==="insertParagraph"&&this.handleTextInput(`
|
|
834
|
+
`)&&e.preventDefault()});I(this,"onImeCompositionStart",()=>{this.isActiveEditor()&&(this.imeComposing=!0,this.updateImeAnchorPosition(),this.refocusImeInputSoon())});I(this,"onImeCompositionEnd",e=>{if(!this.isActiveEditor())return;this.imeComposing=!1;const t=e.data??"";this.handleTextInput(t)&&this.imeInput&&(this.imeInput.value=""),this.refocusImeInputSoon()});I(this,"onImeTargetMouseDown",()=>{this.isActiveEditor()&&this.refocusImeInputSoon()});I(this,"onPointerMouseDown",e=>{if(this.closed||e.altKey||e.button===1)return;const t=this.pointerEventToEditorLocal(e);if(!t)return;if(!this.isPointInContainer(t.x,t.y)){this.isActiveEditor()&&this.closeEditor();return}this.activateEditor(),this.handleMouseDown(t.x,t.y,e.shiftKey),this.refocusImeInputSoon()});I(this,"onPointerMouseMove",e=>{if(!this.isActiveEditor()||e.buttons===0||!this.isDragging)return;const t=this.pointerEventToEditorLocal(e);t&&this.handleMouseMove(t.x,t.y)});I(this,"onPointerMouseUp",()=>{this.isActiveEditor()&&this.handleMouseUp()});I(this,"onPointerDoubleClick",e=>{if(!this.isActiveEditor())return;const t=this.pointerEventToEditorLocal(e);t&&(this.handleDoubleClick(t.x,t.y),this.refocusImeInputSoon())});I(this,"onReopenDoubleClick",e=>{this.closed&&this.shouldReopenFromDoubleClick(e)&&this.showEditor()});I(this,"handlers",{change:new Set,selectionChange:new Set,cursorMove:new Set,show:new Set,close:new Set});var r,a,c,l,h,d,p,m;N.instances.add(this),this.scene=e.scene,this.camera=e.camera,this.toolbarTheme=((r=e.toolbar)==null?void 0:r.theme)??"dark",this.toolbarOffsetY=Math.max(0,((a=e.toolbar)==null?void 0:a.offsetY)??10),this.toolbarEnabled=((c=e.toolbar)==null?void 0:c.enabled)??!0,this.toolbarContainer=((l=e.toolbar)==null?void 0:l.container)??null,this.toolbarFontFamilies=((h=e.toolbar)==null?void 0:h.fontFamilies)??null,this.toolbarColorPicker=(d=e.toolbar)==null?void 0:d.colorPicker,this.colorSettings=e.colorSettings,this.width=Math.max(1,e.width),this.position=((p=e.position)==null?void 0:p.clone())??new y.Vector3(0,0,0),e.initialAttachmentPoint!==void 0&&(this.editorAttachmentPoint=e.initialAttachmentPoint),this.enableWordWrap=e.enableWordWrap??!0;const t=e.textStyle??N.DEFAULT_TEXT_STYLE,i=Math.max(1,Number.isFinite(t.fixedTextHeight)?t.fixedTextHeight:N.DEFAULT_TEXT_STYLE.fixedTextHeight),n=Math.max(1,Number.isFinite(t.lastHeight)?t.lastHeight:i);this.defaultTextStyle={...t,fixedTextHeight:i,lastHeight:n,widthFactor:Number.isFinite(t.widthFactor)?t.widthFactor:1,obliqueAngle:Number.isFinite(t.obliqueAngle)?t.obliqueAngle:0,textGenerationFlag:Number.isFinite(t.textGenerationFlag)?t.textGenerationFlag:0,standardFlag:Number.isFinite(t.standardFlag)?t.standardFlag:0,font:t.font||N.DEFAULT_TEXT_STYLE.font,bigFont:t.bigFont??""},this.baseFormat=this.createBaseFormatFromTextStyle(this.defaultTextStyle,this.resolveRenderColorSettings()),this.currentFormat={...this.baseFormat},this.document=new Q,this.uiAdapter=new En(this.document),this.mtextRenderer=new B.UnifiedRenderer("main",{workerUrl:typeof e.workerUrl=="string"?e.workerUrl:((m=e.workerUrl)==null?void 0:m.toString())??"./assets/mtext-renderer-worker.js"}),e.fontUrl&&this.mtextRenderer.setFontUrl(e.fontUrl),this.cursorLogic=new vl({containerBox:{x:0,y:0,width:this.width,height:1},charBoxes:[],lineTolerance:4});const s={...e.cursorStyle??{}};s.height===void 0&&s.heightMode!=="fixed"&&(s.height=0),s.color??(s.color="#ffffff"),s.glowColor??(s.glowColor="#ffffff"),this.cursorRenderer=new Pl({renderer:new _l({scene:this.scene,camera:this.camera}),cursorStyle:s,selectionStyle:e.selectionStyle,enableDebug:!1,enableSelection:!0,debugYAxisUp:this.camera instanceof y.OrthographicCamera?this.camera.top>=this.camera.bottom:!0,debugVisibility:this.debugVisibility}),this.cursorRenderer.setViewTransform({x:this.position.x,y:this.position.y,scaleX:1,scaleY:1}),this.createBoundingBox(e.showBoundingBox??!0,e.boundingBoxStyle),this.setText(e.initialText??""),this.attachIme(e.imeTarget),this.initializeRenderer()}setText(e){this.document=this.createNormalizedDocument(e),this.document.cursor=0,this.uiAdapter=new En(this.document),this.clearHistory(),this.syncUiStateFromDocument(),this.relayout(),this.emit("change")}getText(){return this.syncUiStateFromDocument(),this.mtextString}getPlainText(){return this.getChars().join("")}insertText(e){if(e.length!==0){if(e===`
|
|
835
|
+
`){const t=this.cursorLogic.getCursorState().lineIndex;this.pendingCursorLineHint=t>=0?t+1:0}this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"insertText",text:e,style:this.toDocumentStyle(this.currentFormat)}),this.syncUiStateFromDocument(),this.relayout()})}}deleteBackward(){this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"backspace"}),this.syncUiStateFromDocument(),this.relayout()})}deleteForward(){this.commitHistoryEdit(()=>{this.syncDocumentFromUiState(),this.uiAdapter.execute({type:"delete"}),this.syncUiStateFromDocument(),this.relayout()})}undo(){const e=this.undoStack.pop();return e?(this.redoStack.push(this.createHistorySnapshot()),this.restoreHistorySnapshot(e),!0):!1}redo(){const e=this.redoStack.pop();return e?(this.undoStack.push(this.createHistorySnapshot()),this.restoreHistorySnapshot(e),!0):!1}moveCursor(e){switch(e){case"left":this.cursorLogic.moveLeft();break;case"right":this.cursorLogic.moveRight();break;case"up":this.cursorLogic.moveUp();break;case"down":this.cursorLogic.moveDown();break;case"lineStart":this.cursorLogic.moveToLineStart();break;case"lineEnd":this.cursorLogic.moveToLineEnd();break;case"wordPrev":this.cursorLogic.moveTo(this.findPrevWordStart(this.cursorLogic.getCurrentIndex()));break;case"wordNext":this.cursorLogic.moveTo(this.findNextWordStart(this.cursorLogic.getCurrentIndex()));break}this.cursorLogic.clearSelection(),this.syncStateFromCursor(),this.emit("cursorMove"),this.emit("selectionChange")}extendSelection(e){const t=this.cursorLogic.getSelection(),i=t?t.anchor:this.cursorLogic.getCurrentIndex();switch(this.cursorLogic.clearSelection(),this.cursorLogic.moveTo(this.cursorIndex),e){case"left":this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex()-1);break;case"right":this.cursorLogic.moveTo(this.cursorLogic.getCurrentIndex()+1);break;case"up":this.cursorLogic.moveUp();break;case"down":this.cursorLogic.moveDown();break;case"lineStart":this.cursorLogic.moveToLineStart();break;case"lineEnd":this.cursorLogic.moveToLineEnd();break}this.cursorLogic.setSelectionWithDirection(i,this.cursorLogic.getCurrentIndex()),this.syncStateFromCursor(),this.emit("selectionChange")}selectAll(){this.cursorLogic.selectAll(),this.syncStateFromCursor(),this.emit("selectionChange")}clearSelection(){this.cursorLogic.clearSelection(),this.syncStateFromCursor(),this.emit("selectionChange")}setDebugMode(e){this.debugMode=e,this.cursorRenderer.setDebugMode(e)}isDebugMode(){return this.debugMode}setDebugVisibility(e){this.debugVisibility={...this.debugVisibility,...e},this.cursorRenderer.setDebugVisibility(e)}getDebugVisibility(){return{...this.debugVisibility}}setToolbarTheme(e){var t;this.toolbarTheme=e,this.isActiveEditor()&&((t=this.getActiveToolbar())==null||t.setTheme(e))}getToolbarTheme(){return this.toolbarTheme}attachIme(e){const t=this.closed;this.lastImeTarget=e,this.bindReopenDoubleClick(e),this.imeTarget=e,this.attachPointerInteractions(e),this.closed=!1,N.activeEditor?N.activeEditor===this?this.activateEditor():(this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1)):this.activateEditor(),t&&this.emit("show")}detachIme(){this.imeInput&&(this.imeInput.removeEventListener("keydown",this.onImeKeyDown),this.imeInput.removeEventListener("beforeinput",this.onImeBeforeInput),this.imeInput.removeEventListener("compositionstart",this.onImeCompositionStart),this.imeInput.removeEventListener("compositionend",this.onImeCompositionEnd),window.removeEventListener("keydown",this.onWindowKeyDown),this.imeTarget&&this.imeTarget.removeEventListener("mousedown",this.onImeTargetMouseDown),this.imeInput.remove(),this.imeInput=null,this.imeComposing=!1,this.imeFocusTimer!==null&&(window.clearTimeout(this.imeFocusTimer),this.imeFocusTimer=null))}getCursorIndex(){return this.cursorIndex}getSelectionRange(){const e=Math.min(this.selectionStart,this.selectionEnd),t=Math.max(this.selectionStart,this.selectionEnd);return{start:e,end:t,isCollapsed:e===t}}getCursorLayoutData(){const e={containerBox:{...this.latestCursorLayoutData.containerBox},charBoxes:this.latestCursorLayoutData.charBoxes.map(t=>({...t}))};return this.latestCursorLayoutData.lineBreakIndices&&(e.lineBreakIndices=[...this.latestCursorLayoutData.lineBreakIndices]),this.latestCursorLayoutData.lineLayouts&&(e.lineLayouts=this.latestCursorLayoutData.lineLayouts.map(t=>({...t}))),e}setCurrentFormat(e){var n;const t=this.mergeCharFormat(this.currentFormat,e);this.currentFormat=t;const i=this.getSelectionRange();i.isCollapsed||this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const s=this.getNodesByLogicalRange(i.start,i.end);for(const r of s){const a=this.toCharFormat(r.style),c=this.mergeCharFormat(a,e);r.style=this.toDocumentStyle(c,r.style)}this.syncUiStateFromDocument(),this.relayout()}),(n=this.getActiveToolbar())==null||n.setFormat(this.currentFormat)}getCurrentFormat(){return{...this.currentFormat}}setParagraphAlignment(e){const t=this.mapRibbonParagraphAlignment(e);t!==void 0&&this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const i=this.getSelectionRange(),n=this.toDocumentIndexFromLogicalIndex(Math.min(i.start,i.end),!0),s=this.toDocumentIndexFromLogicalIndex(Math.max(i.start,i.end),!1),r=this.document.ast.nodes;if(r.length===0)return;const a=p=>{var f;const m=Math.max(0,Math.min(p,r.length-1));return((f=r[m])==null?void 0:f.type)==="paragraphBreak"?Math.min(m+1,r.length):Math.min(p,r.length-1)},c=p=>{var f;const m=a(p);for(let w=m;w>=0;w--)if(((f=r[w])==null?void 0:f.type)==="paragraphBreak")return w+1;return 0},l=p=>{var f;const m=Math.min(Math.max(0,p),r.length-1);for(let w=m;w<r.length;w++)if(((f=r[w])==null?void 0:f.type)==="paragraphBreak")return w;return r.length},h=c(Math.min(n,s)),d=l(Math.max(n,s));if(!(h>=d)){for(let p=h;p<d;p++){const m=r[p];m&&Dt(m)&&(m.style.paragraph.align=t)}this.syncUiStateFromDocument(),this.relayout()}})}setAttachmentPoint(e){const t=this.mapRibbonAttachmentCode(e);if(!(t===void 0||t===this.editorAttachmentPoint)){if(Number.isFinite(this.layoutContainer.width)&&Number.isFinite(this.layoutContainer.height)){const i=this.position.x+this.layoutContainer.x,n=i+this.layoutContainer.width,s=this.position.y+this.layoutContainer.y,r=s+this.layoutContainer.height;if(Number.isFinite(i)&&Number.isFinite(n)&&Number.isFinite(s)&&Number.isFinite(r)&&n>=i-1e-9&&r>=s-1e-9){const a=this.computeAttachmentAnchorOnBounds(i,n,s,r,this.editorAttachmentPoint),c=this.computeAttachmentAnchorOnBounds(i,n,s,r,t);this.position.x+=c.x-a.x,this.position.y+=c.y-a.y,this.cursorRenderer.setViewTransform({x:this.position.x,y:this.position.y,scaleX:1,scaleY:1})}}this.editorAttachmentPoint=t,this.relayout(),this.emit("change")}}getAttachmentPointCode(){return this.attachmentPointToRibbonCode(this.editorAttachmentPoint)}getMTextAttachmentPoint(){return this.editorAttachmentPoint}toggleCase(){const e=this.getSelectionRange();e.isCollapsed||this.commitHistoryEdit(()=>{this.syncDocumentFromUiState();const t=this.toDocumentIndexFromLogicalIndex(e.start,!0),i=this.toDocumentIndexFromLogicalIndex(e.end,!1);if(i<=t)return;const n=this.document.ast.nodes.slice(t,i),s=n.map(c=>c.type==="char"?c.value:c.type==="stack"?`${c.numerator}${c.denominator}`:"").join("");if(!/[a-zA-Z]/.test(s))return;const r=/[a-z]/.test(s),a=c=>r?c.toUpperCase():c.toLowerCase();this.document.transaction(()=>{for(const c of n)c.type==="char"?c.value=a(c.value):c.type==="stack"&&(c.numerator=a(c.numerator),c.denominator=a(c.denominator));this.document.setSelection(t,i)}),this.syncUiStateFromDocument(),this.relayout()})}getDefaultTextStyle(){return{...this.defaultTextStyle}}handleKeyDown(e){if(e.isComposing||e.key==="Process")return!1;if(e.key==="Escape")return this.closeEditor(),!0;const t=this.isMacPlatform(),i=t?e.metaKey:e.ctrlKey,n=t?e.altKey:e.ctrlKey;if(i&&e.key.toLowerCase()==="a")return this.selectAll(),!0;if(i&&e.key.toLowerCase()==="z")return e.shiftKey?this.redo():this.undo();if(!t&&i&&e.key.toLowerCase()==="y")return this.redo();if(e.shiftKey){if(e.key==="ArrowLeft")return this.consumeExtend("left");if(e.key==="ArrowRight")return this.consumeExtend("right");if(e.key==="ArrowUp")return this.consumeExtend("up");if(e.key==="ArrowDown")return this.consumeExtend("down");if(e.key==="Home")return this.consumeExtend("lineStart");if(e.key==="End")return this.consumeExtend("lineEnd")}return t&&e.metaKey&&e.key==="ArrowLeft"?this.consumeMove("lineStart"):t&&e.metaKey&&e.key==="ArrowRight"?this.consumeMove("lineEnd"):e.key==="ArrowLeft"?this.consumeMove(n?"wordPrev":"left"):e.key==="ArrowRight"?this.consumeMove(n?"wordNext":"right"):e.key==="ArrowUp"?this.consumeMove("up"):e.key==="ArrowDown"?this.consumeMove("down"):e.key==="Home"?this.consumeMove("lineStart"):e.key==="End"?this.consumeMove("lineEnd"):e.key==="Backspace"?(this.deleteBackward(),!0):e.key==="Delete"?(this.deleteForward(),!0):e.key==="Enter"?(this.insertText(`
|
|
836
|
+
`),!0):!i&&!e.altKey&&e.key.length===1?(this.insertText(e.key),!0):!1}handleTextInput(e){return e?(this.insertText(e),!0):!1}handleMouseDown(e,t,i){if(i){const n=this.cursorLogic.hitTest(e,t);if(n<0)return;this.cursorLogic.setSelectionWithDirection(this.selectionStart,n)}else if(!this.cursorLogic.moveToClick(e,t))return;this.isDragging=!0,this.syncStateFromCursor(),this.emit("cursorMove"),this.emit("selectionChange")}handleMouseMove(e,t){this.isDragging&&(this.cursorLogic.updateSelectionDrag(e,t),this.syncStateFromCursor(),this.emit("selectionChange"))}handleMouseUp(){this.isDragging=!1}handleDoubleClick(e,t){const i=this.cursorLogic.hitTest(e,t);if(i<0)return;const n=this.getChars();let s=i,r=i;for(;s>0&&!/\s/.test(n[s-1]??"");)s-=1;for(;r<n.length&&!/\s/.test(n[r]??"");)r+=1;this.cursorLogic.setSelection(s,r),this.cursorLogic.moveTo(r),this.syncStateFromCursor(),this.emit("selectionChange")}update(){const e=this.cursorLogic.getCursorState(),t=this.cursorLogic.getSelection(),i=this.getActiveCursorRenderState(e.position,e.lineInfo.height),n=this.cursorLogic.getSelectedCharBoxes();this.cursorRenderer.updateCursor(i.position,i.height),this.cursorRenderer.updateSelection(n),this.cursorRenderer.updateDebugInfo({containerBox:this.layoutContainer,charBoxes:this.cursorLogic.getCharBoxes(),chars:this.getChars(),lines:this.cursorLogic.getLines()}),this.cursorRenderer.setSelectionStyle({fillColor:t!=null&&t.isBackwards?"rgba(150,0,255,0.25)":"rgba(0,120,255,0.30)"}),this.cursorRenderer.render(),this.updateImeAnchorPosition(),this.updateToolbarPosition()}dispose(){var e;N.activeEditor===this?this.deactivateEditor():this.detachIme(),this.detachPointerInteractions(),this.unbindReopenDoubleClick(),this.disposeRenderedObject(this.renderedObject),this.renderedObject=null,this.disposeBoundingBox(),this.mtextRenderer.destroy(),this.cursorRenderer.dispose(),this.cursorLogic.destroy(),this.handlers.change.clear(),this.handlers.selectionChange.clear(),this.handlers.cursorMove.clear(),this.handlers.show.clear(),this.handlers.close.clear(),N.instances.delete(this),N.instances.size===0&&((e=N.sharedToolbar)==null||e.dispose(),N.sharedToolbar=null,N.sharedToolbarContainer=null,N.sharedToolbarFontFamiliesKey="",N.sharedToolbarColorPickerFactory=null,N.activeEditor=null)}closeEditor(){this.closed||(this.closed=!0,this.detachPointerInteractions(),this.deactivateEditor(),this.emit("close"))}showEditor(){const e=this.lastImeTarget;if(!e)return!1;const t=this.closed;return this.closed=!1,this.attachPointerInteractions(e),this.activateEditor(),t&&this.emit("show"),!0}attachPointerInteractions(e){this.detachPointerInteractions(),this.pointerTarget=e,e.addEventListener("mousedown",this.onPointerMouseDown),e.addEventListener("mousemove",this.onPointerMouseMove),e.addEventListener("dblclick",this.onPointerDoubleClick),window.addEventListener("mouseup",this.onPointerMouseUp)}detachPointerInteractions(){this.pointerTarget&&(this.pointerTarget.removeEventListener("mousedown",this.onPointerMouseDown),this.pointerTarget.removeEventListener("mousemove",this.onPointerMouseMove),this.pointerTarget.removeEventListener("dblclick",this.onPointerDoubleClick),window.removeEventListener("mouseup",this.onPointerMouseUp),this.pointerTarget=null)}on(e,t){this.handlers[e].add(t)}off(e,t){(e==="change"||e==="selectionChange"||e==="cursorMove"||e==="show"||e==="close")&&this.handlers[e].delete(t)}getCursorWorldPosition(){const e=this.cursorLogic.getCursorState(),t=this.getActiveCursorRenderState(e.position,e.lineInfo.height).position;return{x:this.position.x+t.x,y:this.position.y+t.y,z:this.position.z}}getMTextInsertionPoint(){return this.position.clone()}getState(){return{mtextString:this.getText(),cursorIndex:this.cursorIndex,selectionStart:this.selectionStart,selectionEnd:this.selectionEnd,currentFormat:this.getCurrentFormat()}}isActiveEditor(){return N.activeEditor===this}activateEditor(){var i;if(this.closed)return;const e=N.activeEditor;e&&e!==this&&e.deactivateEditor(),N.activeEditor=this;const t=this.imeTarget??this.lastImeTarget;t&&this.attachImeBridge(t),this.cursorRenderer.show(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!0),t&&this.toolbarEnabled?this.mountToolbar(t):(i=N.sharedToolbar)==null||i.setVisible(!1)}deactivateEditor(){var e;this.isDragging=!1,this.detachIme(),this.cursorRenderer.hide(),this.boundingBoxObject&&(this.boundingBoxObject.visible=!1),N.activeEditor===this&&(N.activeEditor=null,(e=N.sharedToolbar)==null||e.setVisible(!1))}attachImeBridge(e){this.detachIme(),this.imeTarget=e;const t=document.createElement("textarea");t.setAttribute("aria-hidden","true"),t.autocapitalize="off",t.autocomplete="off",t.spellcheck=!1,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.style.width="2px",t.style.height="2px",t.style.opacity="0",t.style.pointerEvents="none",t.style.zIndex="2147483647",document.body.appendChild(t),this.imeInput=t,t.addEventListener("keydown",this.onImeKeyDown),t.addEventListener("beforeinput",this.onImeBeforeInput),t.addEventListener("compositionstart",this.onImeCompositionStart),t.addEventListener("compositionend",this.onImeCompositionEnd),window.addEventListener("keydown",this.onWindowKeyDown),e.addEventListener("mousedown",this.onImeTargetMouseDown),this.updateImeAnchorPosition(),this.focusImeInput()}getActiveToolbar(){if(!this.isActiveEditor())return null;const e=N.sharedToolbar;if(!e)throw new Error("[mtext-input-box] Failed to create shared toolbar");return e}createToolbarSessionOptions(e){return{anchorElement:e,onFormatChange:t=>{this.setCurrentFormat(t)},onToggleStack:()=>{this.toggleStackSelection()},onToggleSuperscript:()=>this.toggleScriptSelection("superscript"),onToggleSubscript:()=>this.toggleScriptSelection("subscript")}}ensureSharedToolbar(e){var r,a;const t=this.toolbarContainer??document.body,i=((r=this.toolbarFontFamilies)==null?void 0:r.join("\0"))??"";if(!N.sharedToolbar||N.sharedToolbarContainer!==t||N.sharedToolbarFontFamiliesKey!==i||N.sharedToolbarColorPickerFactory!==(this.toolbarColorPicker??null)){(a=N.sharedToolbar)==null||a.dispose();const c={...this.createToolbarSessionOptions(e),container:t,theme:this.toolbarTheme,initialFormat:this.currentFormat};this.toolbarFontFamilies&&(c.fontFamilies=this.toolbarFontFamilies),this.toolbarColorPicker&&(c.colorPicker=this.toolbarColorPicker),N.sharedToolbar=new Kl(c),N.sharedToolbarContainer=t,N.sharedToolbarFontFamiliesKey=i,N.sharedToolbarColorPickerFactory=this.toolbarColorPicker??null}const s=N.sharedToolbar;if(!s)throw new Error("[mtext-input-box] Failed to create shared toolbar");return s}mountToolbar(e){if(!this.toolbarEnabled||!this.isActiveEditor())return;const t=this.ensureSharedToolbar(e);t.setTheme(this.toolbarTheme),t.setSession(this.createToolbarSessionOptions(e)),t.setVisible(!0),t.setFormat(this.currentFormat),this.updateToolbarStackState(),this.updateToolbarPosition()}updateToolbarPosition(){if(!this.toolbarEnabled||!this.isActiveEditor()||!this.imeTarget)return;const e=this.getActiveToolbar();if(!e)return;const t=this.getEditorScreenBounds();t&&e.setAnchor(t.minX,t.minY-this.toolbarOffsetY)}getEditorScreenBounds(){if(!this.imeTarget)return null;const e=this.imeTarget.getBoundingClientRect(),t=this.position.x+this.layoutContainer.x,i=t+this.layoutContainer.width,n=this.position.y+this.layoutContainer.y,s=n+this.layoutContainer.height,r=[new y.Vector3(t,n,this.position.z),new y.Vector3(i,n,this.position.z),new y.Vector3(t,s,this.position.z),new y.Vector3(i,s,this.position.z)];let a=Number.POSITIVE_INFINITY,c=Number.NEGATIVE_INFINITY,l=Number.POSITIVE_INFINITY,h=Number.NEGATIVE_INFINITY;for(const d of r){const p=d.clone().project(this.camera),m=e.left+(p.x+1)*.5*e.width,f=e.top+(1-p.y)*.5*e.height;a=Math.min(a,m),c=Math.max(c,m),l=Math.min(l,f),h=Math.max(h,f)}return!Number.isFinite(a)||!Number.isFinite(l)?null:{minX:a,maxX:c,minY:l,maxY:h}}pointerEventToEditorLocal(e){const t=this.pointerTarget??this.imeTarget;return this.pointerEventToEditorLocalByTarget(e,t)}pointerEventToEditorLocalByTarget(e,t){if(!t)return null;const i=t.getBoundingClientRect();if(i.width<=0||i.height<=0)return null;const n=(e.clientX-i.left)/i.width*2-1,s=-((e.clientY-i.top)/i.height)*2+1,r=new y.Vector3(n,s,-1).unproject(this.camera),c=new y.Vector3(n,s,1).unproject(this.camera).sub(r);if(Math.abs(c.z)<1e-8)return null;const l=(this.position.z-r.z)/c.z,h=r.add(c.multiplyScalar(l));return{x:h.x-this.position.x,y:h.y-this.position.y}}shouldReopenFromDoubleClick(e){return this.hitTestRenderedObject(e)}hitTestRenderedObject(e){if(!this.renderedObject||!this.reopenTarget)return!1;const t=this.reopenTarget.getBoundingClientRect();if(t.width<=0||t.height<=0)return!1;const i=(e.clientX-t.left)/t.width*2-1,n=-((e.clientY-t.top)/t.height)*2+1,s=new y.Raycaster;return s.setFromCamera(new y.Vector2(i,n),this.camera),s.intersectObject(this.renderedObject,!0).length>0}bindReopenDoubleClick(e){this.reopenTarget!==e&&(this.unbindReopenDoubleClick(),this.reopenTarget=e,e.addEventListener("dblclick",this.onReopenDoubleClick))}unbindReopenDoubleClick(){this.reopenTarget&&(this.reopenTarget.removeEventListener("dblclick",this.onReopenDoubleClick),this.reopenTarget=null)}isPointInContainer(e,t){const i=this.layoutContainer,n=i.x+i.width,s=i.y+i.height;return e>=i.x&&e<=n&&t>=i.y&&t<=s}async initializeRenderer(){try{await this.mtextRenderer.loadFonts([_i]),this.rendererReady=!0,this.ensureFontsLoaded(),this.relayout()}catch(e){console.error("[mtext-input-box] Failed to initialize mtext renderer fonts",e)}}relayout(){if(!this.rendererReady){this.mtextInsertionOffset.set(0,0,0);const e=this.createFallbackCharBoxes();this.layoutContainer=e.containerBox,this.updateCursorData(e.charBoxes,e.lineBreakIndices,e.lineLayouts),this.updateBoundingBoxGeometry();return}this.ensureFontsLoaded();try{const e=this.createMTextData(),t=this.createTextStyle(),i=this.resolveRenderColorSettings(),n=this.mtextRenderer.syncRenderMText(e,t,i);this.pruneExtraMTextLayoutRoots(n),this.replaceRenderedObject(n);const s=this.extractBoxesFromRenderedObject(n);this.mtextInsertionOffset.set(0,0,0),this.normalizeRenderedTopAlignment(n,s),this.layoutContainer=s.containerBox,this.updateCursorData(s.charBoxes,s.lineBreakIndices,s.lineLayouts),this.updateBoundingBoxGeometry()}catch(e){console.error("[mtext-input-box] Failed to sync render MTEXT",e),this.mtextInsertionOffset.set(0,0,0);const t=this.createFallbackCharBoxes();this.layoutContainer=t.containerBox,this.updateCursorData(t.charBoxes,t.lineBreakIndices,t.lineLayouts),this.updateBoundingBoxGeometry()}}ensureFontsLoaded(){if(this.pendingFontLoad)return;const e=this.collectFontNamesForText(),t=e.map(i=>i.toLowerCase()).sort().join("|");!t||t===this.lastFontKey||(this.lastFontKey=t,this.pendingFontLoad=this.mtextRenderer.loadFonts(e).then(()=>{}).catch(i=>{console.warn("[mtext-input-box] Failed to load fonts for MTEXT",i)}).finally(()=>{this.pendingFontLoad=null,this.rendererReady&&this.relayout()}))}collectFontNamesForText(){const e=new Set,t=i=>{if(!i)return;const n=i.trim();n&&e.add(n)};t(this.defaultTextStyle.font),t(this.defaultTextStyle.bigFont);try{const i=B.MText.getFonts(this.mtextString||"",!0);for(const n of i)t(n)}catch(i){console.warn("[mtext-input-box] Failed to parse fonts from MTEXT",i)}return e.size===0&&e.add(_i),[...e]}updateCursorData(e,t,i){this.latestCursorLayoutData={containerBox:{...this.layoutContainer},charBoxes:e.map(c=>({...c})),...t?{lineBreakIndices:[...t]}:{},...i?{lineLayouts:i.map(c=>({...c}))}:{}},this.cursorLogic.updateData(this.layoutContainer,e,t,i);const n=Math.min(this.cursorIndex,this.charCount()),s=Math.max(0,this.cursorLogic.getLineCount()-1),r=this.pendingCursorLineHint===null?null:Math.max(0,Math.min(this.pendingCursorLineHint,s));this.pendingCursorLineHint=null,this.cursorLogic.moveTo(n,r),this.selectionStart!==this.selectionEnd?this.cursorLogic.setSelection(this.selectionStart,this.selectionEnd):this.cursorLogic.clearSelection(),this.syncStateFromCursor();const a=this.unionLayoutContainerWithCursorLines(this.layoutContainer);(Math.abs(a.y-this.layoutContainer.y)>1e-6||Math.abs(a.height-this.layoutContainer.height)>1e-6)&&(this.layoutContainer=a,this.latestCursorLayoutData.containerBox={...this.layoutContainer},this.cursorLogic.updateData(this.layoutContainer,e,t,i),this.cursorLogic.moveTo(n,r),this.selectionStart!==this.selectionEnd?this.cursorLogic.setSelection(this.selectionStart,this.selectionEnd):this.cursorLogic.clearSelection(),this.syncStateFromCursor())}unionLayoutContainerWithCursorLines(e){const t=this.cursorLogic.getLines();if(t.length===0)return e;let i=e.y,n=e.y+e.height;for(const s of t){if(s.charCount!==0)continue;const r=s.y-s.height/2,a=s.y+s.height/2;Number.isFinite(r)&&(i=Math.min(i,r)),Number.isFinite(a)&&(n=Math.max(n,a))}return!Number.isFinite(i)||!Number.isFinite(n)||n<i?e:{...e,y:i,height:n-i}}computeEditorVerticalBounds(e,t,i){const n=()=>({minY:i.y-i.height/2,maxY:i.y+i.height/2}),s=(c,l,h,d)=>c<d+1e-4&&l>h-1e-4;if(e.length===0&&t.length===0)return n();if(e.length===0){let c=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const h of t)c=Math.min(c,h.y-h.height/2),l=Math.max(l,h.y+h.height/2);return Number.isFinite(c)&&Number.isFinite(l)&&l>=c?{minY:c,maxY:l}:n()}if(t.length===0){let c=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(const h of e){const d=h.y-h.height/2,p=h.y+h.height/2;c=Math.min(c,d),l=Math.max(l,p)}return Number.isFinite(c)&&Number.isFinite(l)&&l>=c?{minY:c,maxY:l}:n()}let r=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY;for(const c of e){const l=c.y-c.height/2,h=c.y+c.height/2,d=t.filter(p=>{const m=p.y-p.height/2,f=p.y+p.height/2;return s(m,f,l,h)});if(d.length===0)r=Math.min(r,l),a=Math.max(a,h);else for(const p of d)r=Math.min(r,p.y-p.height/2),a=Math.max(a,p.y+p.height/2)}for(const c of t){const l=c.y-c.height/2,h=c.y+c.height/2;e.some(p=>{const m=p.y-p.height/2,f=p.y+p.height/2;return s(l,h,m,f)})||(r=Math.min(r,l),a=Math.max(a,h))}return!Number.isFinite(r)||!Number.isFinite(a)||a<r?n():{minY:r,maxY:a}}extractBoxesFromRenderedObject(e){const t=e.createLayoutData(),i=[],n=((t==null?void 0:t.lines)??[]).filter(d=>Number.isFinite(d.y)&&Number.isFinite(d.height)).map(d=>({y:d.y-this.position.y,height:Math.max(1,d.height)}));for(const d of(t==null?void 0:t.chars)??[]){const p=d.box?this.toLocalBox(d.box):void 0;!p||!(Number.isFinite(p.x)&&Number.isFinite(p.y)&&Number.isFinite(p.width)&&Number.isFinite(p.height))||i.push(p)}const s=(t.lines??[]).map(d=>d.breakIndex).filter(d=>Number.isInteger(d)).filter(d=>d>=0&&d<=i.length),r=this.toLocalBox(e.box),{minY:a,maxY:c}=this.computeEditorVerticalBounds(n,i,r),l={x:Er(this.width,this.editorAttachmentPoint),y:a,width:Math.max(1,this.width),height:Math.max(0,c-a)},h=this.getFallbackLineAdvance();if(l.height<h){const d=h-l.height;l.y-=d,l.height=h}return{containerBox:l,charBoxes:i,...s.length>0?{lineBreakIndices:s}:{},...n.length>0?{lineLayouts:n}:{}}}normalizeRenderedTopAlignment(e,t){var s;const n=-(t.containerBox.y+t.containerBox.height);!Number.isFinite(n)||Math.abs(n)<1e-8||(this.mtextInsertionOffset.set(0,n,0),e.position.y+=n,e.updateMatrixWorld(!0),t.containerBox.y+=n,t.charBoxes.forEach(r=>{r.y+=n}),(s=t.lineLayouts)==null||s.forEach(r=>{r.y+=n}))}toLocalBox(e){const t=e.min.x-this.position.x,i=e.max.x-this.position.x,n=e.min.y-this.position.y,s=e.max.y-this.position.y,r=Math.max(0,i-t),a=Math.max(0,s-n);return{x:t,y:n+a/2,width:r,height:a}}createFallbackCharBoxes(){const e=this.getFallbackLineAdvance(),t=[],i=[],n=[];let s=0,r=0,a=-e;n.push({y:r-e/2,height:e});for(const c of this.getChars()){if(c===`
|
|
837
|
+
`){i.push(t.length),s=0,r-=e,a=Math.min(a,r-e),n.push({y:r-e/2,height:e});continue}const l=Math.max(1,this.currentFormat.fontSize*.6);this.enableWordWrap&&s>0&&s+l>this.width&&(i.push(t.length),s=0,r-=e,a=Math.min(a,r-e),n.push({y:r-e/2,height:e})),t.push({x:s,y:r-e/2,width:l,height:e}),s+=l}return{containerBox:{x:Er(this.width,this.editorAttachmentPoint),y:a,width:this.width,height:Math.max(1,-a)},charBoxes:t,lineBreakIndices:i,lineLayouts:n}}createBoundingBox(e,t){if(!e)return;const i=typeof(t==null?void 0:t.color)=="number"?t.color:new y.Color((t==null?void 0:t.color)??"#58a6ff");this.boundingBoxPadding=Math.max(0,(t==null?void 0:t.padding)??1),this.boundingBoxZOffset=(t==null?void 0:t.zOffset)??.01;const n=new y.LineBasicMaterial({color:i,transparent:!0,opacity:(t==null?void 0:t.opacity)??.9,depthTest:!1,depthWrite:!1}),s=new y.BufferGeometry;this.boundingBoxObject=new y.LineLoop(s,n),this.boundingBoxObject.position.z=this.boundingBoxZOffset,this.scene.add(this.boundingBoxObject)}updateBoundingBoxGeometry(){if(!this.boundingBoxObject)return;this.boundingBoxObject.geometry.dispose();const t=this.boundingBoxPadding,i=this.position.x+this.layoutContainer.x-t,n=this.position.y+this.layoutContainer.y-t,s=this.position.x+this.layoutContainer.x+this.layoutContainer.width+t,r=this.position.y+this.layoutContainer.y+this.layoutContainer.height+t,a=this.position.z;this.boundingBoxObject.geometry=new y.BufferGeometry().setFromPoints([new y.Vector3(i,n,a),new y.Vector3(s,n,a),new y.Vector3(s,r,a),new y.Vector3(i,r,a)])}disposeBoundingBox(){if(!this.boundingBoxObject)return;this.boundingBoxObject.removeFromParent(),this.boundingBoxObject.geometry.dispose();const e=Array.isArray(this.boundingBoxObject.material)?this.boundingBoxObject.material:[this.boundingBoxObject.material];for(const t of e)t.dispose();this.boundingBoxObject=null}replaceRenderedObject(e){this.disposeRenderedObject(this.renderedObject),this.removeStrayInputBoxSceneRootsExcept(e),this.forceVisibleMaterialState(e),e.userData[Ei]=this,this.renderedObject=e,this.scene.add(e)}removeStrayInputBoxSceneRootsExcept(e){const t=e;for(let i=this.scene.children.length-1;i>=0;i--){const n=this.scene.children[i];if(!n||n===t)continue;n.userData[Ei]===this&&(this.scene.remove(n),this.disposeMTextRootResources(n),delete n.userData[Ei])}}forceVisibleMaterialState(e){e.traverse(t=>{const i=t,n=i.material?Array.isArray(i.material)?i.material:[i.material]:[];for(const s of n){const r=s;typeof r.side<"u"&&(r.side=y.DoubleSide),typeof r.depthTest<"u"&&(r.depthTest=!1),typeof r.depthWrite<"u"&&(r.depthWrite=!1),typeof r.transparent<"u"&&typeof r.opacity<"u"&&(r.transparent=r.opacity<1),r.needsUpdate=!0}})}disposeDetachedThreeSubtree(e){e.traverse(t=>{const i=t;i.geometry&&i.geometry.dispose();const n=i.material?Array.isArray(i.material)?i.material:[i.material]:[];for(const s of n){const r=s;r.map&&r.map.dispose(),s.dispose()}})}pruneExtraMTextLayoutRoots(e){for(;e.children.length>1;){const t=e.children[0];if(!t)break;e.remove(t),this.disposeDetachedThreeSubtree(t)}}disposeMTextRootResources(e){const t=e;if(typeof t.dispose=="function"){t.dispose();return}this.disposeDetachedThreeSubtree(e)}disposeRenderedObject(e){e&&(e.removeFromParent(),delete e.userData[Ei],this.disposeMTextRootResources(e))}isExplicitAci(e){return e!==null&&Number.isInteger(e)&&e>0&&e<256}normalizeColorNumber(e){return Math.max(0,Math.min(16777215,Math.round(e)))}resolveAciColor(e){const t=B.getColorByIndex(e);return this.normalizeColorNumber(Number.isFinite(t)?t:16777215)}resolveBaseColor(){return this.isExplicitAci(this.baseFormat.aci)?this.resolveAciColor(this.baseFormat.aci):this.baseFormat.rgb!==null?this.normalizeColorNumber(this.baseFormat.rgb):16777215}resolveBaseFormatColor(e){const t=e.color;if(t.isRgb&&t.rgbValue!==null)return{aci:null,rgb:this.normalizeColorNumber(t.rgbValue)};if(t.isAci&&t.aci!==null){const i=t.aci;return Number.isInteger(i)&&i>=1&&i<=255?{aci:i,rgb:null}:i===0?{aci:null,rgb:this.normalizeColorNumber(e.byBlockColor)}:{aci:null,rgb:this.normalizeColorNumber(e.byLayerColor)}}return{aci:null,rgb:this.normalizeColorNumber(e.byLayerColor)}}createBaseFormatFromTextStyle(e,t){const i=wl();i.fontFamily=e.font||i.fontFamily,i.fontSize=Math.max(1,e.fixedTextHeight);const n=this.resolveBaseFormatColor(t);i.aci=n.aci,i.rgb=n.rgb;const s=e.widthFactor;i.widthFactor=typeof s=="number"&&Number.isFinite(s)?Math.max(.01,s):1;const r=e.obliqueAngle;return i.obliqueAngle=typeof r=="number"&&Number.isFinite(r)?r:0,i.tracking=1,i}createMTextData(){const e={text:this.mtextString,height:Math.max(1,this.defaultTextStyle.fixedTextHeight),width:this.width,position:{x:this.position.x,y:this.position.y,z:this.position.z},attachmentPoint:this.editorAttachmentPoint,drawingDirection:B.MTextFlowDirection.LEFT_TO_RIGHT,widthFactor:1,collectCharBoxes:!0};return this.editorLineSpaceFactor!=null&&Number.isFinite(this.editorLineSpaceFactor)&&(e.lineSpaceFactor=this.editorLineSpaceFactor),e}getLineSpacingFactor(){return this.editorLineSpaceFactor??N.DEFAULT_LINE_SPACE_FACTOR}setLineSpacingFactor(e){if(!Number.isFinite(e)||e<=0)return;const t=N.DEFAULT_LINE_SPACE_FACTOR,i=e>=1?Math.max(.01,t+(e-1)/B.LINE_SPACING_SCALE_FACTOR):e;this.editorLineSpaceFactor=i,this.relayout(),this.emit("change")}clearLineSpacing(){this.editorLineSpaceFactor=null,this.relayout(),this.emit("change")}getFallbackLineAdvance(){return Math.max(1,this.currentFormat.fontSize*N.FALLBACK_LINE_ADVANCE_RATIO)}createTextStyle(){return{...this.defaultTextStyle}}resolveRenderColorSettings(){if(this.colorSettings)return this.colorSettings;const e=this.toolbarTheme==="light"?0:16777215;return{byLayerColor:e,byBlockColor:e,color:new B.MTextColor(256)}}focusImeInput(){this.imeInput&&this.imeInput.focus({preventScroll:!0})}refocusImeInputSoon(){this.imeInput&&(this.imeFocusTimer!==null&&window.clearTimeout(this.imeFocusTimer),this.imeFocusTimer=window.setTimeout(()=>{this.focusImeInput(),this.imeFocusTimer=null},0))}updateImeAnchorPosition(){if(!this.imeInput||!this.imeTarget)return;const e=this.getCursorWorldPosition(),i=new y.Vector3(e.x,e.y,e.z).project(this.camera),n=this.imeTarget.getBoundingClientRect(),s=n.left+(i.x+1)*.5*n.width,r=n.top+(1-i.y)*.5*n.height;this.imeInput.style.left=`${Math.round(s)}px`,this.imeInput.style.top=`${Math.round(r)}px`}syncStateFromCursor(){this.cursorIndex=this.cursorLogic.getCurrentIndex();const e=this.cursorLogic.getSelection();e?(this.selectionStart=e.start,this.selectionEnd=e.end):(this.selectionStart=this.cursorIndex,this.selectionEnd=this.cursorIndex),this.syncDocumentFromUiState(),this.refreshCurrentFormatFromDocument()}consumeMove(e){return this.moveCursor(e),!0}consumeExtend(e){return this.extendSelection(e),!0}isMacPlatform(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}emit(e){for(const t of this.handlers[e])t()}findPrevWordStart(e){const t=this.getChars();let i=Math.max(0,e-1);for(;i>0&&/\s/.test(t[i]??"");)i-=1;for(;i>0&&!/\s/.test(t[i-1]??"");)i-=1;return i}findNextWordStart(e){const t=this.getChars();let i=Math.min(t.length,e);for(;i<t.length&&!/\s/.test(t[i]??"");)i+=1;for(;i<t.length&&/\s/.test(t[i]??"");)i+=1;return i}getChars(){const e=[];for(const t of this.document.ast.nodes){if(t.type==="char"){e.push(t.value);continue}if(t.type==="stack"){e.push("");continue}(t.type==="paragraphBreak"||t.type==="columnBreak"||t.type==="wrapAtDimLine")&&e.push(`
|
|
838
|
+
`)}return e}charCount(){return this.getChars().length}getActiveCursorRenderState(e,t){var a;const i=this.cursorLogic.getCharBoxes(),n=this.cursorLogic.getCurrentIndex(),s=this.cursorLogic.getCurrentLineInfo();if(i.length===0){const c=(a=this.latestCursorLayoutData.lineLayouts)==null?void 0:a[0];if(c&&Number.isFinite(c.y)&&Number.isFinite(c.height)){const h=Math.max(1,c.height);return{position:{x:e.x,y:c.y},height:h}}const l=Math.max(1,this.getFallbackLineAdvance());return{position:{x:e.x,y:this.layoutContainer.y+l/2},height:l}}if(n<=0||n===s.startIndex){if(!(s.charCount<=0||s.endIndex<s.startIndex)){const h=Math.max(0,Math.min(s.startIndex,i.length-1)),d=i[h];if(d)return{position:{x:e.x,y:d.y},height:Math.max(1,d.height)}}const l=s.height??t;return{position:{x:e.x,y:s.y??e.y},height:Math.max(1,l)}}const r=i[Math.min(n-1,i.length-1)];return r?{position:{x:r.x+r.width,y:r.y},height:Math.max(1,r.height)}:{position:e,height:Math.max(1,t)}}getNodeLogicalSpan(e){switch(e.type){case"char":return 1;case"stack":return 1;case"paragraphBreak":case"columnBreak":case"wrapAtDimLine":return 0;default:return 0}}toLogicalIndexFromDocumentIndex(e){const t=Math.max(0,Math.min(e,this.document.ast.nodes.length));let i=0;for(let n=0;n<t;n+=1){const s=this.document.ast.nodes[n];s&&(i+=this.getNodeLogicalSpan(s))}return i}toDocumentIndexFromLogicalIndex(e,t=!0,i){var h,d;const n=this.document.ast.nodes;if(n.length===0)return 0;const s=this.charCount(),r=Math.max(0,Math.min(e,s)),a=[];let c=0,l=0;for(let p=0;p<=n.length&&(c===r&&a.push({index:p,lineIndex:l}),p!==n.length);p+=1){const m=n[p];if(!m)continue;const f=this.getNodeLogicalSpan(m);f===0?l+=1:c+=f}if(a.length===0)return n.length;if(i!==void 0&&Number.isFinite(i)){const p=this,f=(typeof p.resolveCandidateByVisualLineHint=="function"?p.resolveCandidateByVisualLineHint:N.prototype.resolveCandidateByVisualLineHint).call(this,a,r,i);if(f!==void 0)return f;const w=((h=a[0])==null?void 0:h.lineIndex)??0,x=((d=a[a.length-1])==null?void 0:d.lineIndex)??0;if(i<w||i>x)return t?a[a.length-1].index:a[0].index;let b=a[0],v=Math.abs(b.lineIndex-i);for(let C=1;C<a.length;C+=1){const P=a[C],L=Math.abs(P.lineIndex-i);L<v&&(b=P,v=L)}return b.index}return t?a[a.length-1].index:a[0].index}resolveCandidateByVisualLineHint(e,t,i){if(e.length<=1||this.cursorLogic==null||typeof this.cursorLogic.getLines!="function")return;const n=this.cursorLogic.getLines();if(!Array.isArray(n)||n.length===0)return;const s=[];for(let c=0;c<n.length;c+=1){const l=n[c];l&&t>=l.startIndex&&t<=l.endIndex+1&&s.push(c)}if(s.length!==e.length)return;const r=s.indexOf(i);if(r<0)return;const a=e[r];return a==null?void 0:a.index}syncUiStateFromDocument(){this.mtextString=this.document.toMText();const e=this.charCount();this.cursorIndex=Math.min(this.toLogicalIndexFromDocumentIndex(this.document.cursor),e);const t=this.document.selection;t?(this.selectionStart=this.toLogicalIndexFromDocumentIndex(t.start),this.selectionEnd=this.toLogicalIndexFromDocumentIndex(t.end)):(this.selectionStart=this.cursorIndex,this.selectionEnd=this.cursorIndex),this.refreshCurrentFormatFromDocument()}syncDocumentFromUiState(){const e=this.getSelectionRange();if(!e.isCollapsed){const s=this.toDocumentIndexFromLogicalIndex(e.start,!0),r=this.toDocumentIndexFromLogicalIndex(e.end,!1);this.document.setSelection(s,r);return}this.document.clearSelection();const t=this.cursorLogic.getCursorState(),i=t.lineIndex,n=!(t.isAtLineEnd&&!t.isAtLineStart);this.document.cursor=this.toDocumentIndexFromLogicalIndex(this.cursorIndex,n,i>=0?i:void 0)}refreshCurrentFormatFromDocument(){var t,i;const e=this.inferCurrentFormatFromDocument();if(this.updateToolbarStackState(),!e){(t=this.getActiveToolbar())==null||t.setFormat(this.currentFormat);return}yr(this.currentFormat,e)||(this.currentFormat=e),(i=this.getActiveToolbar())==null||i.setFormat(this.currentFormat)}toggleStackSelection(){const e=this.getSelectionRange();e.isCollapsed||this.commitHistoryEdit(()=>{var l;this.syncDocumentFromUiState();const t=this.toDocumentIndexFromLogicalIndex(e.start,!0),i=this.toDocumentIndexFromLogicalIndex(e.end,!1);if(i<=t)return;const n=this.document.ast.nodes.slice(t,i);if(n.length===1&&((l=n[0])==null?void 0:l.type)==="stack"){const h=n[0],d=this.stackNodeToPlainText(h.numerator,h.denominator,h.divider),p=Array.from(d).map(m=>({type:"char",value:m,style:this.cloneDocumentStyle(h.style)}));if(p.length===0)return;this.document.transaction(m=>{m.ast.nodes.splice(t,1,...p),m.setSelection(t,t+p.length)}),this.syncUiStateFromDocument(),this.relayout();return}if(!n.every(h=>(h==null?void 0:h.type)==="char"))return;const s=n.map(h=>h.value).join(""),r=this.parseStackParts(s);if(!r)return;const a=n[0];if(!a)return;const c={type:"stack",numerator:r.numerator,denominator:r.denominator,divider:r.divider,style:this.cloneDocumentStyle(a.style)};this.document.transaction(h=>{h.ast.nodes.splice(t,i-t,c),h.setSelection(t,t+1)}),this.syncUiStateFromDocument(),this.relayout()})}toggleScriptSelection(e){const t=this.getSelectionRange();if(t.isCollapsed)return!1;let i=!1;return this.commitHistoryEdit(()=>{var d;this.syncDocumentFromUiState();const n=this.toDocumentIndexFromLogicalIndex(t.start,!0),s=this.toDocumentIndexFromLogicalIndex(t.end,!1);if(s<=n)return;const r=this.document.ast.nodes.slice(n,s);if(r.length===1&&((d=r[0])==null?void 0:d.type)==="stack"){const p=r[0],m=this.scriptStackToPlainText(p.numerator,p.denominator,p.divider);if(!m)return;const f=this.cloneDocumentStyle(p.style);f.script="normal",f.align=B.MTextLineAlignment.MIDDLE;const w=Array.from(m).map(x=>({type:"char",value:x,style:this.cloneDocumentStyle(f)}));if(w.length===0)return;this.document.transaction(x=>{x.ast.nodes.splice(n,1,...w),x.setSelection(n,n+w.length)}),this.syncUiStateFromDocument(),this.relayout(),i=!0;return}if(!r.every(p=>(p==null?void 0:p.type)==="char"))return;const a=r.map(p=>p.value).join("");if(a.length===0)return;const c=r[0];if(!c)return;const l=this.cloneDocumentStyle(c.style);l.script=e,l.align=e==="superscript"?B.MTextLineAlignment.TOP:B.MTextLineAlignment.BOTTOM;const h={type:"stack",numerator:e==="superscript"?a:"",denominator:e==="subscript"?a:"",divider:"^",style:this.cloneDocumentStyle(l)};this.document.transaction(p=>{p.ast.nodes.splice(n,s-n,h),p.setSelection(n,n+1)}),this.syncUiStateFromDocument(),this.relayout(),i=!0}),i}commitHistoryEdit(e){const t=this.createHistorySnapshot();e(),!this.isSameAsCurrent(t)&&(this.undoStack.push(t),this.undoStack.length>this.maxHistorySize&&this.undoStack.splice(0,this.undoStack.length-this.maxHistorySize),this.redoStack=[],this.emit("change"),this.emit("selectionChange"),this.emit("cursorMove"))}createHistorySnapshot(){return{ast:this.cloneAst(this.document.ast),cursor:this.document.cursor,selection:this.document.selection?{...this.document.selection}:null,currentFormat:{...this.currentFormat}}}restoreHistorySnapshot(e){this.document=new Q(this.cloneAst(e.ast)),e.selection?this.document.setSelection(e.selection.start,e.selection.end):(this.document.cursor=e.cursor,this.document.clearSelection()),this.uiAdapter=new En(this.document),this.currentFormat={...e.currentFormat},this.syncUiStateFromDocument(),this.relayout(),this.emit("change"),this.emit("selectionChange"),this.emit("cursorMove")}isSameAsCurrent(e){if(e.cursor!==this.document.cursor)return!1;const t=this.document.selection;return!!e.selection!=!!t||e.selection&&t&&(e.selection.start!==t.start||e.selection.end!==t.end)||!yr(e.currentFormat,this.currentFormat)?!1:this.document.toMText()===this.buildMTextFromAst(e.ast)}buildMTextFromAst(e){return new Q(this.cloneAst(e)).toMText()}clearHistory(){this.undoStack=[],this.redoStack=[]}cloneAst(e){return{nodes:e.nodes.map(t=>t.type==="char"?{...t,style:this.cloneDocumentStyle(t.style)}:t.type==="stack"?{...t,style:this.cloneDocumentStyle(t.style)}:{...t,style:this.cloneDocumentStyle(t.style)})}}stackNodeToPlainText(e,t,i){if(i==="^"){if(e.length===0&&t.length>0)return`^${t.trimStart()}`;if(e.length>0&&t.length===0)return`${e.trimEnd()}^`}return`${e}${i}${t}`}scriptStackToPlainText(e,t,i){if(i!=="^")return null;const n=e.trim().length>0,s=t.trim().length>0;return n===s?null:n?e.trim():t.trim()}parseStackParts(e){const t=[];for(let c=0;c<e.length;c+=1){const l=e[c];(l==="/"||l==="#"||l==="^")&&t.push({index:c,divider:l})}if(t.length!==1)return null;const i=t[0];if(!i)return null;const{index:n,divider:s}=i,r=e.slice(0,n),a=e.slice(n+1);if(s==="^"){const c=r.trim().length>0,l=a.trim().length>0;return!c&&!l?null:{numerator:r,denominator:a,divider:s}}return r.trim().length===0||a.trim().length===0?null:{numerator:r,denominator:a,divider:s}}updateToolbarStackState(){var a;const e=this.getActiveToolbar();if(!e)return;const t=this.getSelectionRange();if(t.isCollapsed){e.setStackActive(!1);return}const i=this.toDocumentIndexFromLogicalIndex(t.start,!0),n=this.toDocumentIndexFromLogicalIndex(t.end,!1),s=this.document.ast.nodes.slice(i,n),r=s.length===1&&((a=s[0])==null?void 0:a.type)==="stack"&&!this.isScriptOnlyStack(s[0]);e.setStackActive(r)}isScriptOnlyStack(e){if(e.divider!=="^")return!1;const t=e.numerator.trim().length>0,i=e.denominator.trim().length>0;return t!==i}inferCurrentFormatFromDocument(){if(this.document.ast.nodes.length===0||this.getChars().length===0)return null;const n=this.selectionStart!==this.selectionEnd?Math.min(this.selectionStart,this.selectionEnd):this.cursorIndex>0?this.cursorIndex-1:0,s=this.getNodeByLogicalCharIndex(n);if(!s)return null;if(s.type==="stack"&&this.isScriptOnlyStack(s)){const r=s.numerator.trim().length>0?"superscript":"subscript";return{...this.toCharFormat(s.style),script:r}}return this.toCharFormat(s.style)}getNodeByLogicalCharIndex(e){const t=this.document.ast.nodes;if(t.length===0)return null;let i=0;const n=Math.max(0,e);for(const s of t){const r=this.getNodeLogicalSpan(s);if(n<i+r)return s;i+=r}return t[t.length-1]??null}getNodesByLogicalRange(e,t){const i=this.document.ast.nodes;if(i.length===0)return[];const n=Math.max(0,Math.min(e,t)),s=Math.max(n,Math.max(e,t));if(n===s)return[];const r=[];let a=0;for(const c of i){const l=this.getNodeLogicalSpan(c),h=a,d=a+l;l>0&&h<s&&d>n&&r.push(c),a=d}return r}toCharFormat(e){var x,b;const t=Math.max(1,this.defaultTextStyle.fixedTextHeight),i=e.capHeight.isRelative?t*Math.max(0,e.capHeight.value):e.capHeight.value,n=this.defaultTextStyle.font||this.baseFormat.fontFamily,s=e.rgb?this.rgbArrayToColorNumber(e.rgb):this.isExplicitAci(e.aci)?this.resolveAciColor(e.aci):this.resolveBaseColor(),r=this.isExplicitAci(e.aci)?e.aci:this.isExplicitAci(this.baseFormat.aci)?this.baseFormat.aci:null,a=this.toScriptFromStyle(e,t,i),c=Math.max(1,t)*.9,l=i<=c,h=a==="normal"?i:l?i/.7:i,d=(x=e.widthFactor)==null?void 0:x.value,p=typeof d=="number"&&Number.isFinite(d)?Math.max(.01,d):1,m=(b=e.charTrackingFactor)==null?void 0:b.value,f=typeof m=="number"&&Number.isFinite(m)?Math.max(.01,m):1,w=typeof e.oblique=="number"&&Number.isFinite(e.oblique)?e.oblique:0;return{fontFamily:e.fontFace.family||n,fontSize:Math.max(1,h||t),bold:e.fontFace.weight>=700,italic:e.fontFace.style==="Italic",underline:e.underline,overline:e.overline,strike:e.strikeThrough,script:a,aci:r,rgb:s,obliqueAngle:w,widthFactor:p,tracking:f,paragraphAlignment:e.paragraph.align}}toScriptFromStyle(e,t,i){const n=Math.max(1,t)*.9,s=i<=n;return e.script&&e.script!=="normal"?s?e.script:"normal":s&&e.align===B.MTextLineAlignment.TOP?"superscript":s&&e.align===B.MTextLineAlignment.BOTTOM?"subscript":"normal"}createDefaultParseContext(){const e=new B.MTextContext;if(e.fontFace.family=this.defaultTextStyle.font||this.baseFormat.fontFamily,e.fontFace.style=this.baseFormat.italic?"Italic":"Regular",e.fontFace.weight=this.baseFormat.bold?700:400,e.capHeight={value:this.defaultTextStyle.fixedTextHeight,isRelative:!1},e.align=B.MTextLineAlignment.BOTTOM,e.widthFactor={value:this.defaultTextStyle.widthFactor??1,isRelative:!1},this.isExplicitAci(this.baseFormat.aci))e.aci=this.baseFormat.aci,e.rgb=null;else{const t=this.resolveBaseColor();e.rgb=this.colorNumberToRgbArray(t),e.aci=256}return e}createNormalizedDocument(e){const t=Q.fromMText(e,this.createDefaultParseContext()),i={nodes:[]};for(const n of t.ast.nodes)switch(n.type){case"char":i.nodes.push({type:"char",value:n.value,style:this.cloneDocumentStyle(n.style)});break;case"stack":i.nodes.push({type:"stack",numerator:n.numerator,denominator:n.denominator,divider:n.divider,style:this.cloneDocumentStyle(n.style)});break;case"paragraphBreak":i.nodes.push({type:"paragraphBreak",style:this.cloneDocumentStyle(n.style)});break;case"columnBreak":case"wrapAtDimLine":i.nodes.push({type:"paragraphBreak",style:this.cloneDocumentStyle(n.style)});break}return new Q(i)}computeAttachmentAnchorOnBounds(e,t,i,n,s){const r=(e+t)*.5,a=(i+n)*.5,c=this.position.z;switch(s){case B.MTextAttachmentPoint.TopLeft:return new y.Vector3(e,n,c);case B.MTextAttachmentPoint.TopCenter:return new y.Vector3(r,n,c);case B.MTextAttachmentPoint.TopRight:return new y.Vector3(t,n,c);case B.MTextAttachmentPoint.MiddleLeft:return new y.Vector3(e,a,c);case B.MTextAttachmentPoint.MiddleCenter:return new y.Vector3(r,a,c);case B.MTextAttachmentPoint.MiddleRight:return new y.Vector3(t,a,c);case B.MTextAttachmentPoint.BottomLeft:case B.MTextAttachmentPoint.BaselineLeft:return new y.Vector3(e,i,c);case B.MTextAttachmentPoint.BottomCenter:case B.MTextAttachmentPoint.BaselineCenter:return new y.Vector3(r,i,c);case B.MTextAttachmentPoint.BottomRight:case B.MTextAttachmentPoint.BaselineRight:return new y.Vector3(t,i,c);default:return new y.Vector3(e,n,c)}}mapRibbonParagraphAlignment(e){switch(e){case"default":return B.MTextParagraphAlignment.DEFAULT;case"left":return B.MTextParagraphAlignment.LEFT;case"center":return B.MTextParagraphAlignment.CENTER;case"right":return B.MTextParagraphAlignment.RIGHT;case"justified":return B.MTextParagraphAlignment.JUSTIFIED;case"distributed":return B.MTextParagraphAlignment.DISTRIBUTED;default:return}}mapRibbonAttachmentCode(e){switch(e.trim().toUpperCase()){case"TL":return B.MTextAttachmentPoint.TopLeft;case"TC":return B.MTextAttachmentPoint.TopCenter;case"TR":return B.MTextAttachmentPoint.TopRight;case"ML":return B.MTextAttachmentPoint.MiddleLeft;case"MC":return B.MTextAttachmentPoint.MiddleCenter;case"MR":return B.MTextAttachmentPoint.MiddleRight;case"BL":return B.MTextAttachmentPoint.BottomLeft;case"BC":return B.MTextAttachmentPoint.BottomCenter;case"BR":return B.MTextAttachmentPoint.BottomRight;default:return}}attachmentPointToRibbonCode(e){switch(e){case B.MTextAttachmentPoint.TopLeft:return"TL";case B.MTextAttachmentPoint.TopCenter:return"TC";case B.MTextAttachmentPoint.TopRight:return"TR";case B.MTextAttachmentPoint.MiddleLeft:return"ML";case B.MTextAttachmentPoint.MiddleCenter:return"MC";case B.MTextAttachmentPoint.MiddleRight:return"MR";case B.MTextAttachmentPoint.BottomLeft:case B.MTextAttachmentPoint.BaselineLeft:return"BL";case B.MTextAttachmentPoint.BottomCenter:case B.MTextAttachmentPoint.BaselineCenter:return"BC";case B.MTextAttachmentPoint.BottomRight:case B.MTextAttachmentPoint.BaselineRight:return"BR";default:return"TL"}}mergeCharFormat(e,t){const i={...e,...t};if(t.aci!==void 0)if(!this.isExplicitAci(t.aci))i.aci=null;else{const n=this.resolveAciColor(t.aci);i.aci=t.aci,i.rgb=n}return t.rgb!==void 0&&(t.rgb===null?i.rgb=null:(i.rgb=this.normalizeColorNumber(t.rgb),t.aci===void 0&&(i.aci=null))),t.paragraphAlignment!==void 0&&(i.paragraphAlignment=t.paragraphAlignment),i}cloneDocumentStyle(e){return{underline:e.underline,overline:e.overline,strikeThrough:e.strikeThrough,script:e.script,aci:e.aci,rgb:e.rgb?[...e.rgb]:null,align:e.align,fontFace:{...e.fontFace},capHeight:{...e.capHeight},widthFactor:{...e.widthFactor},charTrackingFactor:{...e.charTrackingFactor},oblique:e.oblique,paragraph:{indent:e.paragraph.indent,left:e.paragraph.left,right:e.paragraph.right,align:e.paragraph.align,tabs:[...e.paragraph.tabs]}}}toDocumentStyle(e,t){const i=this.isExplicitAci(e.aci)?e.aci:null,n=i!==null?null:this.colorNumberToRgbArray(e.rgb!==null?e.rgb:this.resolveBaseColor()),s=e.script!=="normal",r=Math.max(1,e.fontSize*(s?.7:1)),a=e.script==="superscript"?B.MTextLineAlignment.TOP:e.script==="subscript"?B.MTextLineAlignment.BOTTOM:B.MTextLineAlignment.MIDDLE,c=e.paragraphAlignment;return{underline:e.underline,overline:e.overline,strikeThrough:e.strike,script:e.script,aci:i,rgb:n,align:a,fontFace:{family:e.fontFamily,style:e.italic?"Italic":"Regular",weight:e.bold?700:400},capHeight:{value:r,isRelative:!1},widthFactor:{value:Math.max(.01,e.widthFactor),isRelative:!1},charTrackingFactor:{value:Math.max(.01,e.tracking),isRelative:!1},oblique:e.obliqueAngle,paragraph:{indent:(t==null?void 0:t.paragraph.indent)??0,left:(t==null?void 0:t.paragraph.left)??0,right:(t==null?void 0:t.paragraph.right)??0,align:c,tabs:t!=null&&t.paragraph.tabs?[...t.paragraph.tabs]:[]}}}colorNumberToRgbArray(e){const t=this.normalizeColorNumber(e);return[t>>16&255,t>>8&255,t&255]}rgbArrayToColorNumber(e){const t=Math.max(0,Math.min(255,Math.round(e[0]))),i=Math.max(0,Math.min(255,Math.round(e[1]))),n=Math.max(0,Math.min(255,Math.round(e[2])));return t<<16|i<<8|n}};I(N,"activeEditor",null),I(N,"sharedToolbar",null),I(N,"sharedToolbarContainer",null),I(N,"sharedToolbarFontFamiliesKey",""),I(N,"sharedToolbarColorPickerFactory",null),I(N,"instances",new Set),I(N,"FALLBACK_LINE_ADVANCE_RATIO",1.5),I(N,"DEFAULT_TEXT_STYLE",{name:"MTextInputBoxStyle",standardFlag:0,fixedTextHeight:24,widthFactor:1,obliqueAngle:0,textGenerationFlag:0,lastHeight:24,font:_i,bigFont:""}),I(N,"DEFAULT_LINE_SPACE_FACTOR",.3);let Bn=N;function Ul(o){if(o===void 0)return;const e=o;return e>=1&&e<=12?e:B.MTextAttachmentPoint.TopLeft}function Mu(o){return o}const ki="__mlightcadMTextFormatBridge",H=class H{static setDefaultColorPicker(e){H.defaultColorPicker=e}static setDefaultToolbarEnabled(e){H.defaultToolbarEnabled=e}static getActiveInputBox(){return H.activeInputBox}static addActiveInputBoxChangeListener(e){H.activeInputBoxChangeListeners.add(e)}static removeActiveInputBoxChangeListener(e){H.activeInputBoxChangeListeners.delete(e)}static setActiveInputBox(e){H.activeInputBox!==e&&(H.activeInputBox=e,H.activeInputBoxChangeListeners.forEach(t=>{t(e)}))}static createHiddenToolbarContainer(e){const t=e.ownerDocument.createElement("div");return t.setAttribute("aria-hidden","true"),Object.assign(t.style,{display:"none",pointerEvents:"none"}),e.appendChild(t),t}static attachFormatBridge(e){const t=e;if(t[ki])return;const i=new Set,n=[],s=()=>{i.forEach(a=>{a()})},r=a=>{const c=t[a];typeof c=="function"&&(t[a]=(...l)=>{const h=c.apply(t,l);return s(),h},n.push(()=>{t[a]=c}))};["setCurrentFormat","refreshCurrentFormatFromDocument","toggleCase","toggleStackSelection","toggleScriptSelection","setParagraphAlignment","setAttachmentPoint","setLineSpacingFactor","clearLineSpacing"].forEach(r),t.addCurrentFormatChangeListener=a=>{i.add(a)},t.removeCurrentFormatChangeListener=a=>{i.delete(a)},t.focusEditor=()=>{const a=t,c=a.focusImeInput;if(typeof c=="function"){c.call(t);return}const l=a.refocusImeInputSoon;typeof l=="function"&&l.call(t)},t.isStackSelectionActive=()=>{var C,P;const a=t,c=a.getSelectionRange,l=a.toDocumentIndexFromLogicalIndex,h=a.isScriptOnlyStack,d=a.document;if(typeof c!="function"||typeof l!="function")return!1;const p=c.call(t);if(!p||p.isCollapsed)return!1;const m=l.call(t,p.start,!0),f=l.call(t,p.end,!1),w=((P=(C=d==null?void 0:d.ast)==null?void 0:C.nodes)==null?void 0:P.slice(m,f))??[],x=w[0];if(w.length!==1||(x==null?void 0:x.type)!=="stack")return!1;if(typeof h=="function")return!h.call(t,x);if(x.divider!=="^")return!0;const b=(x.numerator??"").trim().length>0,v=(x.denominator??"").trim().length>0;return b===v},t[ki]={addCurrentFormatChangeListener:t.addCurrentFormatChangeListener,removeCurrentFormatChangeListener:t.removeCurrentFormatChangeListener,dispose:()=>{n.forEach(a=>{a()}),i.clear(),delete t.addCurrentFormatChangeListener,delete t.removeCurrentFormatChangeListener,delete t.focusEditor,delete t.isStackSelectionActive,delete t[ki]}}}static detachFormatBridge(e){var i;(i=e[ki])==null||i.dispose()}open(e){const{view:t,location:i,width:n,textHeight:s,initialText:r="",toolbarFontFamilies:a=[],toolbarColorPicker:c,toolbarEnabled:l=H.defaultToolbarEnabled,initialAttachmentPoint:h}=e,d=new y.Vector3(i.x,i.y,i.z??0),m=Lt(t.backgroundColor)?"#000000":"#ffffff",f=A.instance,w=f.curDocument.database,{layerColor:x}=f.resolveColors(),b=()=>{const F=u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.COLORTHEME,w);return F===0||F==="0"||F===!1||F==="dark"?"dark":"light"},v=Array.from(new Set(a.map(F=>F.trim()).filter(F=>F.length>0))),C=()=>{const F=w.tables.textStyleTable.getAt(w.textstyle);return F==null?void 0:F.textStyle},P=Math.max(1,s),L=C(),M=L?{...L,fixedTextHeight:P,lastHeight:P}:void 0,k=l?null:H.createHiddenToolbarContainer(t.container),E=Ul(h),T=new Bn({scene:t.internalScene,camera:t.internalCamera,width:n,position:d.clone(),initialText:r,...E!==void 0?{initialAttachmentPoint:E}:{},textStyle:M,cursorStyle:{color:m,glowColor:m},boundingBoxStyle:{padding:0},imeTarget:t.canvas,colorSettings:{layer:w.clayer,color:new B.MTextColor,byLayerColor:x,byBlockColor:x},toolbar:{enabled:!0,theme:b(),fontFamilies:v,container:k??t.container,offsetY:10,colorPicker:c??H.defaultColorPicker??void 0}});return H.attachFormatBridge(T),H.setActiveInputBox(T),new Promise(F=>{let O=!1;const z=()=>{O||(T.update(),t.isDirty=!0)},U=W=>{W.name.toLowerCase()===u.AcDbSystemVariables.COLORTHEME.toLowerCase()&&(T.setToolbarTheme(b()),t.isDirty=!0)},V=()=>{H.activeInputBox===T&&H.setActiveInputBox(null),H.detachFormatBridge(T),T.dispose(),k==null||k.remove(),t.events.renderFrame.removeEventListener(z),T.off("close",K),u.AcDbSysVarManager.instance().events.sysVarChanged.removeEventListener(U),t.isDirty=!0},G=W=>{O||(O=!0,V(),F(W))},K=()=>{var te;const W=T.getMTextInsertionPoint();G({contents:T.getText(),location:{x:W.x,y:W.y,z:W.z},width:n,height:P,lineSpacingFactor:((te=T.getLineSpacingFactor)==null?void 0:te.call(T))??H.defaultLineSpacingFactor,attachmentPoint:T.getMTextAttachmentPoint()})};T.on("close",K),t.events.renderFrame.addEventListener(z),u.AcDbSysVarManager.instance().events.sysVarChanged.addEventListener(U)})}};H.defaultLineSpacingFactor=.3,H.activeInputBox=null,H.activeInputBoxChangeListeners=new Set,H.defaultColorPicker=null,H.defaultToolbarEnabled=!0;let Ne=H;class kr{constructor(e){this.events={sysVarChanged:new u.AcCmEventManager,commandWillStart:new u.AcCmEventManager,commandEnded:new u.AcCmEventManager},this._view=e,this._cursorManager=new qs(e),this._inputManager=new Pi(e)}get isActive(){return this._inputManager.isActive}get isEntitySelectionActive(){return this._inputManager.isEntitySelectionActive}getInputModifiers(){return this._inputManager.modifiers}getInputToggles(){return this._inputManager.toggles}resetInputToggles(){this._inputManager.resetToggles()}enqueueScriptInputs(e){this._inputManager.enqueueScriptInputs(e)}clearScriptInputs(){this._inputManager.clearScriptInputs()}showMessage(e,t="info",i){this._inputManager.showMessage(e,t,i)}peekScriptInput(){return this._inputManager.peekScriptInput()}consumeScriptInput(){return this._inputManager.consumeScriptInput()}get currentCursor(){return this._currentCursor}restoreCursor(){this._previousCursor!=null&&this.setCursor(this._previousCursor)}setCursor(e){this._cursorManager.setCursor(e),this._previousCursor=this._currentCursor,this._currentCursor=e}async withCursor(e,t){const i=this._currentCursor;this.setCursor(e);try{return await Promise.resolve(t())}finally{i!==void 0?this.setCursor(i):this.restoreCursor()}}setCursorColor(e){this._cursorManager.setCursorColor(e)}syncCursorBackground(e){this._cursorManager.syncBackgroundColor(e)}async getPoint(e){return await this._inputManager.getPoint(e)}async getAngle(e){return await this._inputManager.getAngle(e)}async getDistance(e){return await this._inputManager.getDistance(e)}async getDouble(e){return await this._inputManager.getDouble(e)}async getInteger(e){return await this._inputManager.getInteger(e)}async getString(e){return await this._inputManager.getString(e)}async getKeywords(e){return await this._inputManager.getKeywords(e)}async getEntity(e){return await this._inputManager.getEntity(e)}async getSelection(e){return await this._inputManager.getSelection(e)}async getBox(e){return await this._inputManager.getBox(e)}selectAll(e){try{const t=A.instance.curDocument.database.tables.blockTable.modelSpace,i=[];for(const n of t.newIterator())(!e||e.matches(n))&&i.push(n.objectId);return new It(S.OK,new fi(i))}catch{return new It(S.Error)}}}class ${constructor(e){this.view=e}render(){this.entity&&this.view.addTransientEntity(this.entity)}end(){this.entity&&this.view.removeTransientEntity(this.entity.objectId)}}class Te{constructor(e){this.state=e}setState(e){this.state=e}async run(e){for(;this.state;)try{const t=this.state.buildPrompt(),i=await e(t);if(await this.state.handleResult(i)==="finish")break}catch{break}}}class $l{constructor(e=[]){this._typedValues=[...e]}get typedValues(){return[...this._typedValues]}matches(e){if(this._typedValues.length===0)return!0;let t="equals";for(const i of this._typedValues){if(i.code===u.AcDbDxfCode.Operator){t=this.parseOperator(i.value);continue}if(!this.matchTypedValue(e,i,t))return!1;t="equals"}return!0}parseOperator(e){switch(String(e??"").trim()){case"!=":case"<>":return"notEquals";case">":return"greaterThan";case">=":return"greaterThanOrEqual";case"<":return"lessThan";case"<=":return"lessThanOrEqual";case"=":case"==":default:return"equals"}}matchTypedValue(e,t,i){const n=this.resolveEntityValue(e,t.code);return n==null?!1:this.compare(n,t.value,i)}resolveEntityValue(e,t){var i;switch(t){case u.AcDbDxfCode.Start:return e.dxfTypeName||e.type;case u.AcDbDxfCode.LayerName:return e.layer;case u.AcDbDxfCode.ColorName:return(i=e.color)==null?void 0:i.toString();case u.AcDbDxfCode.LinetypeName:return e.lineType;case u.AcDbDxfCode.LineWeight:return Number(e.lineWeight);default:return}}compare(e,t,i){const n=Number(e),s=Number(t);if(Number.isFinite(n)&&Number.isFinite(s)&&`${e}`.trim()!==""&&`${t}`.trim()!=="")switch(i){case"equals":return n===s;case"notEquals":return n!==s;case"greaterThan":return n>s;case"greaterThanOrEqual":return n>=s;case"lessThan":return n<s;case"lessThanOrEqual":return n<=s}const a=String(e).toLowerCase(),c=String(t).toLowerCase();switch(i){case"equals":return a===c;case"notEquals":return a!==c;case"greaterThan":return a>c;case"greaterThanOrEqual":return a>=c;case"lessThan":return a<c;case"lessThanOrEqual":return a<=c}}}class Br{constructor(e,t,i,n=500,s=500){this.host=e,this.hoverEvent=t,this.unhoverEvent=i,this.hoverDelay=n,this.pauseDelay=s,this.hoverTimer=null,this.pauseTimer=null,this.hoveredId=null}handleMouseMove(e,t){if(this.clearHoverTimer(),this.hoveredId){this.hoverAt(e,t);return}this.hoverTimer=setTimeout(()=>{this.hoverAt(e,t)},this.hoverDelay)}clear(){this.setHoveredId(null),this.clearHoverTimer(),this.clearPauseTimer()}dispose(){this.clearHoverTimer(),this.clearPauseTimer()}hoverAt(e,t){const i=this.host.pick({x:e,y:t});i.length>0?this.setHoveredId(i[0].id):this.clear()}setHoveredId(e){this.hoveredId!==e&&(this.hoveredId&&(this.unhoverEvent.dispatch({id:this.hoveredId,x:this.host.curMousePos.x,y:this.host.curMousePos.y}),this.host.onUnhover(this.hoveredId)),this.hoveredId=e,e&&(this.startPauseTimer(e),this.host.onHover(e)))}startPauseTimer(e){this.clearPauseTimer(),this.pauseTimer=setTimeout(()=>{this.hoverEvent.dispatch({id:e,x:this.host.curMousePos.x,y:this.host.curMousePos.y})},this.pauseDelay)}clearHoverTimer(){this.hoverTimer&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}clearPauseTimer(){this.pauseTimer&&(clearTimeout(this.pauseTimer),this.pauseTimer=null)}}function Dn(o,e="replace"){return o.shiftKey?"remove":o.ctrlKey||o.metaKey?"add":e}function Dr(o){return Dn(o,"add")}var oe=(o=>(o[o.SELECTION=0]="SELECTION",o[o.PAN=1]="PAN",o))(oe||{});class Mr{constructor(e,t){this.events={mouseMove:new u.AcCmEventManager,viewResize:new u.AcCmEventManager,viewChanged:new u.AcCmEventManager,hover:new u.AcCmEventManager,unhover:new u.AcCmEventManager,renderFrame:new u.AcCmEventManager},this._container=t,this._canvas=e;const i=e.getBoundingClientRect();this._bbox=new u.AcGeBox3d,this._width=i.width,this._height=i.height,this._curPos=new u.AcGePoint2d,this._curMousePos=new u.AcGePoint2d,this._selectionSet=new fi,this._editor=new kr(this),this._canvas.addEventListener("mousemove",r=>this.onMouseMove(r)),this._canvas.addEventListener("mousedown",r=>{r.button===1&&this._editor.setCursor(be.Grab)}),this._canvas.addEventListener("mouseup",r=>{r.button===1&&this._editor.restoreCursor()});const n=Ke.debounce(()=>this.onWindowResize(),0,{leading:!1,trailing:!0});new ResizeObserver(n).observe(this._canvas.parentElement),this._selectionBoxSize=4,this._hoverController=new Br(this,this.events.hover,this.events.unhover)}get editor(){return this._editor}get selectionBoxSize(){return this._selectionBoxSize}set selectionBoxSize(e){this._selectionBoxSize=e}async withMode(e,t){const i=this.mode;this.mode=e;try{return await Promise.resolve(t())}finally{this.mode=i}}setCursor(e){this._editor.setCursor(e)}getSelectionMode(e,t){return t.x>=e.x?"window":"crossing"}getSelectionActionFromEvent(e,t="replace"){return Dn(e,t)}isSelectionClick(e,t,i=2){const n=t.x-e.x,s=t.y-e.y;return Math.hypot(n,s)<i}getSelectionPreviewStyle(e,t){return{borderStyle:e==="window"?"solid":"dashed",lineColor:t==="remove"?"var(--ml-ui-danger, #ff4d4f)":e==="window"?"var(--ml-ui-canvas-line, #00ff5a)":"var(--ml-ui-accent-alt, #00d1ff)",background:"var(--ml-ui-canvas-fill-mix, var(--ml-ui-canvas-fill, rgba(64, 158, 255, 0.12)))"}}applySelection(e,t){if(t==="replace"){this.selectionSet.clear();const i=e.filter(n=>!this.selectionSet.has(n));i.length>0&&this.selectionSet.add(i);return}if(e.length!==0)if(t==="add"){const i=e.filter(n=>!this.selectionSet.has(n));i.length>0&&this.selectionSet.add(i)}else{const i=e.filter(n=>this.selectionSet.has(n));i.length>0&&this.selectionSet.delete(i)}}selectByBoxWithMode(e,t,i="add"){const n=this.collectSelectionIdsByBox(e,t);this.applySelection(n,i)}collectSelectionIdsByBox(e,t){const i=this.search(e),n=[];return i.forEach(s=>{(t==="crossing"||s.minX>=e.min.x&&s.maxX<=e.max.x&&s.minY>=e.min.y&&s.maxY<=e.max.y)&&n.push(s.id)}),n}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 container(){return this._container}viewportToCanvas(e){const t=this._canvas.getBoundingClientRect();return new u.AcGePoint2d(e.x-t.left,e.y-t.top)}canvasToViewport(e){const t=this._canvas.getBoundingClientRect();return new u.AcGePoint2d(e.x+t.left,e.y+t.top)}canvasToContainer(e){const t=this._canvas.getBoundingClientRect(),i=this._container.getBoundingClientRect();return new u.AcGePoint2d(e.x+(t.left-i.left),e.y+(t.top-i.top))}viewportToContainer(e){const t=this._container.getBoundingClientRect();return new u.AcGePoint2d(e.x-t.left,e.y-t.top)}get aspect(){return this._width/this._height}get curPos(){return this._curPos}get curMousePos(){return this._curMousePos}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})}clearHover(){this._hoverController.clear()}onMouseMove(e){this._curMousePos=this.viewportToCanvas({x:e.clientX,y:e.clientY});const t=this.screenToWorld(this._curMousePos);this._curPos.copy(t),this.events.mouseMove.dispatch({x:t.x,y:t.y}),this.mode==0&&(this._editor.isActive||this._hoverController.handleMouseMove(t.x,t.y))}}var R=(o=>(o[o.Read=0]="Read",o[o.Review=4]="Review",o[o.Write=8]="Write",o))(R||{});class j{constructor(){this._mode=R.Read,this._globalName="",this._localName="",this._userData={}}get userData(){return this._userData}get globalName(){return this._globalName}set globalName(e){this._globalName=e}get localName(){return this._localName}set localName(e){this._localName=e}get mode(){return this._mode}set mode(e){this._mode=e}onCommandWillStart(e){}onCommandEnded(e){}async trigger(e){try{this.onCommandWillStart(e),e.view.editor.events.commandWillStart.dispatch({command:this}),await this.execute(e)}finally{e.view.editor.events.commandEnded.dispatch({command:this}),this.onCommandEnded(e)}}async execute(e){}}class Wl{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 wt=class wt{constructor(){this._commandsByGroup=[],this._systemCommandGroup={groupName:wt.SYSTEMT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._defaultCommandGroup={groupName:wt.DEFAUT_COMMAND_GROUP_NAME,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._commandsByGroup.push(this._systemCommandGroup),this._commandsByGroup.push(this._defaultCommandGroup)}addCommand(e,t,i,n,s){if(e=e.toUpperCase(),t=t.toUpperCase(),i=i.toUpperCase(),!t)throw new Error("[AcEdCommandStack] The global name of the command is required!");i||(i=t);let r=this._defaultCommandGroup;if(e){const c=this._commandsByGroup.find(l=>l.groupName==e);c?r=c:(r={groupName:e,commandsByGlobalName:new Map,commandsByLocalName:new Map,commandsByAlias:new Map,aliasesByCommand:new Map},this._commandsByGroup.push(r))}if(r.commandsByGlobalName.has(t))throw new Error(`[AcEdCommandStack] The command with global name '${t}' already exists!`);if(r.commandsByLocalName.has(i))throw new Error(`[AcEdCommandStack] The command with local name '${i}' already exists!`);const a=this.normalizeAliases(s,t,i);for(const c of a){if(r.commandsByAlias.has(c))throw new Error(`[AcEdCommandStack] The command alias '${c}' already exists!`);if(r.commandsByGlobalName.has(c)||r.commandsByLocalName.has(c))throw new Error(`[AcEdCommandStack] The command alias '${c}' conflicts with existing command name!`)}r.commandsByGlobalName.set(t,n),r.commandsByLocalName.set(i,n),a.forEach(c=>{r.commandsByAlias.set(c,n)}),r.aliasesByCommand.set(n,new Set(a)),n.globalName=t,n.localName=i}iterator(){return new Wl(this._commandsByGroup)}searchCommandsByPrefix(e,t){e=e.toUpperCase();const i=[],n=this.iterator();let s=n.next();for(;!s.done;){const{command:r}=s.value;(r.globalName.startsWith(e)||r.localName.startsWith(e)||this.commandAliasStartsWith(s.value.commandGroup,r,e))&&(t===void 0||this.isModeCompatible(t,r.mode))&&i.push(s.value),s=n.next()}return i}lookupGlobalCmd(e,t){e=e.toUpperCase();let i;for(const n of this._commandsByGroup)if(i=n.commandsByGlobalName.get(e),i||(i=n.commandsByAlias.get(e)),i){if(t===void 0||this.isModeCompatible(t,i.mode))break;i=void 0}return i}lookupLocalCmd(e,t){e=e.toUpperCase();let i;for(const n of this._commandsByGroup)if(i=n.commandsByLocalName.get(e),i||(i=n.commandsByAlias.get(e)),i){if(t===void 0||this.isModeCompatible(t,i.mode))break;i=void 0}return i}removeCmd(e,t){e=e.toUpperCase(),t=t.toUpperCase();for(const i of this._commandsByGroup)if(i.groupName==e){const n=i.commandsByGlobalName.get(t);if(!n)return!1;i.commandsByGlobalName.delete(t),i.commandsByLocalName.delete(n.localName);const s=i.aliasesByCommand.get(n);return s==null||s.forEach(r=>{i.commandsByAlias.delete(r)}),i.aliasesByCommand.delete(n),!0}return!1}removeGroup(e){e=e.toUpperCase();const t=this._commandsByGroup.findIndex(i=>i.groupName===e);return t>=0?(this._commandsByGroup.splice(t,1),!0):!1}removeAll(){this._defaultCommandGroup.commandsByGlobalName.clear(),this._defaultCommandGroup.commandsByLocalName.clear(),this._defaultCommandGroup.commandsByAlias.clear(),this._defaultCommandGroup.aliasesByCommand.clear(),this._systemCommandGroup.commandsByGlobalName.clear(),this._systemCommandGroup.commandsByLocalName.clear(),this._systemCommandGroup.commandsByAlias.clear(),this._systemCommandGroup.aliasesByCommand.clear(),this._commandsByGroup=[this._systemCommandGroup,this._defaultCommandGroup]}getCommandAliases(e,t){const i=t==null?void 0:t.trim().toUpperCase(),n=i?this._commandsByGroup.filter(s=>s.groupName===i):this._commandsByGroup;for(const s of n){const r=s.aliasesByCommand.get(e);if(r)return[...r]}return[]}commandAliasStartsWith(e,t,i){const n=this._commandsByGroup.find(r=>r.groupName===e);if(!n)return!1;const s=n.aliasesByCommand.get(t);if(!s)return!1;for(const r of s)if(r.startsWith(i))return!0;return!1}normalizeAliases(e,t,i){const n=Array.isArray(e)?e:e?[e]:[],s=new Set;return n.forEach(r=>{const a=r.trim().toUpperCase();a&&a!==t&&a!==i&&s.add(a)}),[...s]}isModeCompatible(e,t){return e>=t}};wt.SYSTEMT_COMMAND_GROUP_NAME="ACAD",wt.DEFAUT_COMMAND_GROUP_NAME="USER";let he=wt;function Hl(o){return{all:o=o||new Map,on:function(e,t){var i=o.get(e);i?i.push(t):o.set(e,[t])},off:function(e,t){var i=o.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):o.set(e,[]))},emit:function(e,t){var i=o.get(e);i&&i.slice().map(function(n){n(t)}),(i=o.get("*"))&&i.slice().map(function(n){n(e,t)})}}}const ee=Hl();function Yl(o){ee.emit("message",{message:o,type:"warning"})}class Mn{constructor(e,t,i=1e3,n=0){this.condition=e,this.action=t,this.checkInterval=i,this.timeout=n,this.timerId=null,this.timeoutId=null}start(){this.timerId===null&&(this.timerId=window.setInterval(()=>{this.condition()&&this.executeAndStop()},this.checkInterval),this.timeout>0&&(this.timeoutId=window.setTimeout(()=>{u.log.warn("AcEdConditionWaiter: Timeout reached."),this.executeAndStop()},this.timeout)))}stop(){this.timerId!==null&&(clearInterval(this.timerId),this.timerId=null),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}executeAndStop(){this.stop(),this.action()}isRunning(){return this.timerId!==null}}const Xl={light:{"--ml-ui-text":"var(--el-text-color-primary, #303133)","--ml-ui-text-muted":"var(--el-text-color-regular, #606266)","--ml-ui-bg":"var(--el-bg-color-overlay, #ffffff)","--ml-ui-border":"var(--el-border-color, #dcdfe6)","--ml-ui-shadow":"var(--el-box-shadow, 0 2px 6px rgba(0, 0, 0, 0.12))","--ml-ui-overlay":"var(--el-overlay-color-lighter, rgba(0, 0, 0, 0.18))","--ml-ui-accent":"var(--el-color-primary, #409eff)","--ml-ui-accent-alt":"var(--el-color-info, #909399)","--ml-ui-danger":"var(--el-color-danger, #f56c6c)","--ml-ui-canvas-line":"var(--el-color-primary, #409eff)","--ml-ui-canvas-fill":"rgba(64, 158, 255, 0.2)","--ml-ui-canvas-fill-mix":"color-mix(in srgb, var(--el-color-primary, #409eff) 20%, transparent)"},dark:{"--ml-ui-text":"var(--el-text-color-primary, #e5eaf3)","--ml-ui-text-muted":"var(--el-text-color-regular, #cfd3dc)","--ml-ui-bg":"var(--el-bg-color-overlay, #1d1e1f)","--ml-ui-border":"var(--el-border-color, #4c4d4f)","--ml-ui-shadow":"var(--el-box-shadow, 0 6px 18px rgba(0, 0, 0, 0.35))","--ml-ui-overlay":"var(--el-overlay-color-lighter, rgba(0, 0, 0, 0.5))","--ml-ui-accent":"var(--el-color-primary, #409eff)","--ml-ui-accent-alt":"var(--el-color-info, #909399)","--ml-ui-danger":"var(--el-color-danger, #f56c6c)","--ml-ui-canvas-line":"var(--el-color-primary, #409eff)","--ml-ui-canvas-fill":"rgba(64, 158, 255, 0.2)","--ml-ui-canvas-fill-mix":"color-mix(in srgb, var(--el-color-primary, #409eff) 20%, transparent)"}};function ql(o,e=document.documentElement){const t=Xl[o];Object.keys(t).forEach(i=>{e.style.setProperty(i,t[i])}),e.setAttribute("data-ml-ui-theme",o)}class Or{constructor(){this._fileName="",this._docTitle="",this._openMode=R.Write,this._database=new u.AcDbDatabase,this.docTitle="Untitled",this._openMode=R.Write}async openUri(e,t){this._uri=e,this._openMode=(t==null?void 0:t.mode)??R.Read,this._fileName=this.getFileNameFromUri(e);let i=!0;try{const n={...t,readOnly:this._openMode===R.Read};await this._database.openUri(e,n),this.docTitle=this._fileName}catch{i=!1,ee.emit("failed-to-open-file",{fileName:e})}return i}async openDocument(e,t,i){var s;let n=!0;this._fileName=e,this._openMode=(i==null?void 0:i.mode)??R.Read;try{const r=(s=e.split(".").pop())==null?void 0:s.toLocaleLowerCase(),a={...i,readOnly:this._openMode===R.Read};await this._database.read(t,a,r=="dwg"?u.AcDbFileType.DWG:u.AcDbFileType.DXF),this.docTitle=this._fileName}catch{n=!1,ee.emit("failed-to-open-file",{fileName:e})}return n}get uri(){return this._uri}get database(){return this._database}get fileName(){return this._fileName}get docTitle(){return this._docTitle}set docTitle(e){this._docTitle=e}get openMode(){return this._openMode}getFileNameFromUri(e){try{const i=new URL(e).pathname.split("/");return i[i.length-1]||""}catch(t){return u.log.error("Invalid URI:",t),""}}}var ne=function(){return ne=Object.assign||function(o){for(var e,t=1,i=arguments.length;t<i;t++){e=arguments[t];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(o[n]=e[n])}return o},ne.apply(this,arguments)},Bi=function(o){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&o[e],i=0;if(t)return t.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Fr=function(){function o(){}return o.prototype.convert=function(e){var t=this.createEntity(e);return t&&this.processCommonAttrs(e,t),t},o.prototype.createEntity=function(e){return e.type=="3DFACE"?this.convertFace(e):e.type=="ARC"?this.convertArc(e):e.type=="ATTDEF"?this.convertAttributeDefinition(e):e.type=="ATTRIB"?this.convertAttribute(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=="MLINE"?this.convertMLine(e):e.type=="MTEXT"?this.convertMText(e):e.type=="MULTILEADER"||e.type=="MLEADER"?this.convertMLeader(e):e.type=="POINT"?this.convertPoint(e):e.type=="POLYLINE2D"?this.convertPolyline2d(e):e.type=="POLYLINE3D"?this.convertPolyline3d(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},o.prototype.convertFace=function(e){var t=new u.AcDbFace;return e.corner1&&t.setVertexAt(0,e.corner1),e.corner2&&t.setVertexAt(1,e.corner2),e.corner3&&t.setVertexAt(2,e.corner3),e.corner4&&t.setVertexAt(3,e.corner4),t.setEdgeInvisibilities(e.flag),t},o.prototype.convertArc=function(e){var t,i=(t=e.extrusionDirection)!==null&&t!==void 0?t:u.AcGeVector3d.Z_AXIS,n=new u.AcDbArc(u.transformOcsPointToWcs(e.center,i),e.radius,e.startAngle,e.endAngle,i);return n},o.prototype.convertCirle=function(e){var t,i=(t=e.extrusionDirection)!==null&&t!==void 0?t:u.AcGeVector3d.Z_AXIS,n=new u.AcDbCircle(u.transformOcsPointToWcs(e.center,i),e.radius,i);return n},o.prototype.convertEllipse=function(e){var t,i=new u.AcGeVector3d(e.majorAxisEndPoint),n=i.length(),s=new u.AcDbEllipse(e.center,(t=e.extrusionDirection)!==null&&t!==void 0?t:u.AcGeVector3d.Z_AXIS,i,n,n*e.axisRatio,e.startAngle,e.endAngle);return s},o.prototype.convertLine=function(e){var t=e.startPoint,i=e.endPoint,n=new u.AcDbLine(new u.AcGePoint3d(t.x,t.y,t.z),new u.AcGePoint3d(i.x,i.y,i.z));return n},o.prototype.convertSpline=function(e){try{if(e.numberOfControlPoints>0&&e.numberOfKnots>0)return new u.AcDbSpline(e.controlPoints,e.knots,e.weights,e.degree,!!(e.flag&1));if(e.numberOfFitPoints>0)return new u.AcDbSpline(e.fitPoints,"Uniform",e.degree,!!(e.flag&1))}catch(t){console.log("Failed to convert spline with error: ".concat(t))}return null},o.prototype.convertPoint=function(e){var t=new u.AcDbPoint;return t.position=e.position,t},o.prototype.convertSolid=function(e){var t=new u.AcDbTrace;return t.setPointAt(0,ne(ne({},e.corner1),{z:0})),t.setPointAt(1,ne(ne({},e.corner2),{z:0})),t.setPointAt(2,ne(ne({},e.corner3),{z:0})),t.setPointAt(3,e.corner4?ne(ne({},e.corner4),{z:0}):ne(ne({},e.corner3),{z:0})),t.thickness=e.thickness,t},o.prototype.convertLWPolyline=function(e){var t,i=new u.AcDbPolyline;i.closed=!!(e.flag&512);var n=(t=e.constantWidth)!==null&&t!==void 0?t:-1;return e.vertices.forEach(function(s,r){var a,c;i.addVertexAt(r,new u.AcGePoint2d(s.x,s.y),s.bulge,(a=s.startWidth)!==null&&a!==void 0?a:n,(c=s.endWidth)!==null&&c!==void 0?c:n)}),i},o.prototype.convertPolyline2d=function(e){var t,i,n=!!(e.flag&1),s=!!(e.flag&16),r=!!(e.flag&64),a=!!(e.flag&32),c=[],l=[],h=[];if(e.vertices.map(function(f){var w,x;if(!(f.flag&16))if(r&&f.flag&128)if(f.flag&64)c.push({x:f.x,y:f.y,z:f.z}),l.push((w=f.bulge)!==null&&w!==void 0?w:0);else{var b=[];f.polyfaceIndex0!=null&&f.polyfaceIndex0!=0&&b.push(Math.abs(f.polyfaceIndex0)-1),f.polyfaceIndex1!=null&&f.polyfaceIndex1!=0&&b.push(Math.abs(f.polyfaceIndex1)-1),f.polyfaceIndex2!=null&&f.polyfaceIndex2!=0&&b.push(Math.abs(f.polyfaceIndex2)-1),f.polyfaceIndex3!=null&&f.polyfaceIndex3!=0&&b.push(Math.abs(f.polyfaceIndex3)-1),b.length>=3&&h.push(b)}else c.push({x:f.x,y:f.y,z:f.z}),l.push((x=f.bulge)!==null&&x!==void 0?x:0)}),s){var d=(t=e.meshMVertexCount)!==null&&t!==void 0?t:2,p=(i=e.meshNVertexCount)!==null&&i!==void 0?i:2;return new u.AcDbPolygonMesh(d,p,c,n,a)}else{if(r)return new u.AcDbPolyFaceMesh(c,h);var m=u.AcDbPoly2dType.SimplePoly;return e.flag&2?m=u.AcDbPoly2dType.FitCurvePoly:e.flag&4&&(e.smoothType==6?m=u.AcDbPoly2dType.CubicSplinePoly:e.smoothType==5&&(m=u.AcDbPoly2dType.QuadSplinePoly)),new u.AcDb2dPolyline(m,c,0,n,e.startWidth,e.endWidth,l)}},o.prototype.convertPolyline3d=function(e){var t=!!(e.flag&1),i=[];e.vertices.map(function(s){s.flag&16||i.push({x:s.x,y:s.y,z:s.z})});var n=u.AcDbPoly3dType.SimplePoly;return e.flag&4&&(e.smoothType==6?n=u.AcDbPoly3dType.CubicSplinePoly:e.smoothType==5&&(n=u.AcDbPoly3dType.QuadSplinePoly)),new u.AcDb3dPolyline(n,i,t)},o.prototype.convertHatch=function(e){var t,i,n,s,r=new u.AcDbHatch;(t=e.definitionLines)===null||t===void 0||t.forEach(function(h){r.definitionLines.push({angle:h.angle,base:h.base,offset:h.offset,dashLengths:h.numberOfDashLengths>0?h.dashLengths:[]})}),r.isSolidFill=e.solidFill==1,r.hatchStyle=e.hatchStyle,r.patternName=e.patternName,r.patternType=e.patternType,r.patternAngle=e.patternAngle==null?0:e.patternAngle,r.patternScale=e.patternScale==null?0:e.patternScale;var a=e.boundaryPaths;if(a.forEach(function(h){var d=h.boundaryPathTypeFlag;if(d&2){var p=h,m=new u.AcGePolyline2d;m.closed=p.isClosed,p.vertices.forEach(function(b,v){m.addVertexAt(v,{x:b.x,y:b.y,bulge:b.bulge})}),r.add(m)}else{var f=h,w=[];f.edges.forEach(function(b){if(b!=null){if(b.type==1){var v=b;w.push(new u.AcGeLine2d(v.start,v.end))}else if(b.type==2){var C=b;w.push(new u.AcGeCircArc2d(C.center,C.radius,C.startAngle,C.endAngle,!C.isCCW))}else if(b.type==3){var P=b,L=new u.AcGeVector2d;L.subVectors(P.end,P.center);var M=Math.sqrt(Math.pow(P.end.x,2)+Math.pow(P.end.y,2)),k=M*P.lengthOfMinorAxis,E=P.startAngle,T=P.endAngle,F=Math.atan2(P.end.y,P.end.x);P.isCCW||(E=Math.PI*2-E,T=Math.PI*2-T),w.push(new u.AcGeEllipseArc2d(ne(ne({},P.center),{z:0}),M,k,E,T,!P.isCCW,F))}else if(b.type==4){var O=b;if(O.numberOfControlPoints>0&&O.numberOfKnots>0){var z=O.controlPoints.map(function(K){return{x:K.x,y:K.y,z:0}}),U=!0,V=O.controlPoints.map(function(K){return K.weight==null&&(U=!1),K.weight||1});w.push(new u.AcGeSpline3d(z,O.knots,U?V:void 0))}else if(O.numberOfFitData>0){var G=O.fitDatum.map(function(K){return{x:K.x,y:K.y,z:0}});w.push(new u.AcGeSpline3d(G,"Uniform"))}}}});var x=u.AcGeLoop2d.buildFromEdges(w);x.length==0&&w.length>0?r.add(new u.AcGeLoop2d(w)):x.forEach(function(b){return r.add(b)})}}),e.gradientFlag){var c=e;if(r.hatchObjectType=u.AcDbHatchObjectType.GradientObject,r.gradientName=c.gradientName,r.gradientAngle=(i=c.gradientRotation)!==null&&i!==void 0?i:0,r.gradientShift=(n=c.gradientDefinition)!==null&&n!==void 0?n:0,r.gradientOneColorMode=c.gradientColorFlag==1,r.shadeTintValue=(s=c.colorTint)!==null&&s!==void 0?s:0,c.gradientColors){var l=c.gradientColors.length;l>1?(r.gradientStartColor=c.gradientColors[0].rgb,r.gradientEndColor=c.gradientColors[1].rgb):l>0&&(r.gradientStartColor=c.gradientColors[0].rgb)}}return r},o.prototype.convertTable=function(e){var t=new u.AcDbTable(e.name,e.rowCount,e.columnCount);return t.tableStyleId=e.tableStyleId,t.owningBlockRecordId=e.blockRecordHandle,e.directionVector&&(t.horizontalDirection=new u.AcGeVector3d(e.directionVector)),t.attachmentPoint=e.attachmentPoint,t.position.copy(e.startPoint),t.tableValueFlag=e.tableValue,t.tableOverrideFlag=e.overrideFlag,t.borderColorOverrideFlag=e.borderColorOverrideFlag,t.borderLineweightOverrideFlag=e.borderLineWeightOverrideFlag,t.borderVisibilityOverrideFlag=e.borderVisibilityOverrideFlag,e.columnWidthArr.forEach(function(i,n){return t.setColumnWidth(n,i)}),e.rowHeightArr.forEach(function(i,n){return t.setRowHeight(n,i)}),e.cells.forEach(function(i,n){t.setCell(n,i)}),t},o.prototype.convertText=function(e){var t,i,n,s=new u.AcDbText;s.textString=e.text,s.styleName=e.styleName,s.height=e.textHeight,s.position.copy(e.startPoint);var r=!e.endPoint||e.endPoint.x===0&&e.endPoint.y===0&&((t=e.endPoint.z)!==null&&t!==void 0?t:0)===0;return e.endPoint&&!r?s.alignmentPoint.copy(e.endPoint):s.alignmentPoint.copy(e.startPoint),s.rotation=e.rotation,s.oblique=(i=e.obliqueAngle)!==null&&i!==void 0?i:0,s.thickness=e.thickness,s.horizontalMode=e.halign,s.verticalMode=e.valign,s.widthFactor=(n=e.xScale)!==null&&n!==void 0?n:1,s},o.prototype.convertMText=function(e){var t=new u.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 u.AcGeVector3d(e.direction)),t.drawingDirection=e.drawingDirection,t},o.prototype.convertLeader=function(e){var t=new u.AcDbLeader;return e.vertices.forEach(function(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},o.prototype.convertMLine=function(e){var t,i,n,s=new u.AcDbMLine;return s.styleName=e.mlineStyle||"STANDARD",s.scale=e.scale,s.flags=e.flags,s.justification=e.justification,s.startPosition=e.startPoint,s.normal=(t=e.extrusionDirection)!==null&&t!==void 0?t:u.AcGeVector3d.Z_AXIS,s.styleCount=(i=e.numberOfLines)!==null&&i!==void 0?i:0,s.segments=((n=e.vertices)!==null&&n!==void 0?n:[]).map(function(r){var a;return{position:r.vertex,direction:r.vertexDirection,miterDirection:r.miterDirection,elements:((a=r.lines)!==null&&a!==void 0?a:[]).map(function(c){var l,h;return{parameterCount:c.numberOfSegmentParams,parameters:(l=c.segmentParams)!==null&&l!==void 0?l:[],fillCount:c.numberOfAreaFillParams,fillParameters:(h=c.areaFillParams)!==null&&h!==void 0?h:[]}})}}),s},o.prototype.convertMLeader=function(e){var t,i,n,s,r,a,c,l,h,d,p,m,f,w,x=new u.AcDbMLeader,b=e;x.leaderLineType=(t=this.readNumber(b,["multileaderType","leaderLineType","leaderType"]))!==null&&t!==void 0?t:u.AcDbMLeaderLineType.StraightLeader;var v=(i=this.readNumber(b,["contentType"]))!==null&&i!==void 0?i:e.textContent?u.AcDbMLeaderContentType.MTextContent:e.blockContent?u.AcDbMLeaderContentType.BlockContent:u.AcDbMLeaderContentType.NoneContent;x.contentType=v,x.doglegEnabled=(n=this.readBoolean(b,["doglegEnabled","enableDogleg"]))!==null&&n!==void 0?n:!1,x.doglegLength=(s=this.readNumber(b,["doglegLength"]))!==null&&s!==void 0?s:0,e.landingPoint&&(x.landingPoint=e.landingPoint),e.doglegVector&&(x.doglegVector=e.doglegVector);var C=this.readString(b,["mleaderStyleId","mLeaderStyleId","mleaderStyleHandle","styleHandle","styleName"]);C&&(x.mleaderStyleId=C);var P=this.readPoint(b,["normal","extrusionDirection"]);P&&(x.normal=P);var L=e.textContent,M=(r=this.readString(L??{},["styleName","textStyleName"]))!==null&&r!==void 0?r:this.readString(b,["textStyleName","textStyle","styleName"]);M&&(x.textStyleName=M),x.textHeight=(c=(a=this.readNumber(L??{},["textHeight","height"]))!==null&&a!==void 0?a:this.readNumber(b,["textHeight","mtextHeight","textContentHeight"]))!==null&&c!==void 0?c:x.textHeight,x.textWidth=(h=(l=this.readNumber(L??{},["textWidth","width"]))!==null&&l!==void 0?l:this.readNumber(b,["textWidth","mtextWidth","textContentWidth"]))!==null&&h!==void 0?h:x.textWidth;var k=(d=this.readNumber(L??{},["textRotation","rotation"]))!==null&&d!==void 0?d:this.readNumber(b,["textRotation","mtextRotation","textContentRotation"]);k!=null&&(x.textRotation=k);var E=this.readPoint(b,["textDirection","mtextDirection","textDirectionVector"]);E&&(x.textDirection=E);var T=this.readNumber(b,["textAttachmentPoint","attachmentPoint"]);T!=null&&(x.textAttachmentPoint=T);var F=this.readNumber(b,["textDrawingDirection","drawingDirection"]);if(F!=null&&(x.textDrawingDirection=F),((p=e.textContent)===null||p===void 0?void 0:p.text)!=null&&e.textContent.anchorPoint)x.mtextContent={text:e.textContent.text,anchorPoint:e.textContent.anchorPoint};else{var O=this.readString(b,["text","contents","mtext"]),z=this.readPoint(b,["textLocation","textPosition","textAnchorPoint"]);O!=null&&z&&(x.mtextContent={text:O,anchorPoint:z})}if(!((m=e.blockContent)===null||m===void 0)&&m.blockHandle&&e.blockContent.position)x.blockContent={blockHandle:e.blockContent.blockHandle,position:e.blockContent.position};else{var U=this.readString(b,["blockHandle","blockContentHandle","blockId"]),V=this.readPoint(b,["blockPosition","blockContentPosition"]);U&&V&&(x.blockContent={blockHandle:U,position:V})}return(f=e.leaders)===null||f===void 0||f.forEach(function(G){var K,W,te,Ae,bt=x.addLeader({landingPoint:(K=G.landingPoint)!==null&&K!==void 0?K:e.landingPoint,doglegVector:(W=G.doglegVector)!==null&&W!==void 0?W:e.doglegVector,doglegLength:(te=G.doglegLength)!==null&&te!==void 0?te:e.doglegLength});(Ae=G.leaderLines)===null||Ae===void 0||Ae.forEach(function(Ge){var vt,Qt,gs=x.addLeaderLine(bt,(vt=Ge.vertices)!==null&&vt!==void 0?vt:[]);(Qt=Ge.breaks)===null||Qt===void 0||Qt.forEach(function(cn){x.addBreak(bt,gs,cn.start,cn.end)})})}),x.numberOfLeaders===0&&((w=this.readLeaderLineArray(b))===null||w===void 0||w.forEach(function(G){var K=x.addLeader({landingPoint:e.landingPoint,doglegVector:e.doglegVector,doglegLength:e.doglegLength});x.addLeaderLine(K,G)})),x},o.prototype.convertDimension=function(e){if(e.subclassMarker=="AcDbAlignedDimension"){var t=e,i=new u.AcDbAlignedDimension(t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return t.insertionPoint&&(i.dimBlockPosition={x:t.insertionPoint.x,y:t.insertionPoint.y,z:0}),i.rotation=t.rotationAngle,this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbRotatedDimension"){var t=e,i=new u.AcDbRotatedDimension(t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return t.insertionPoint&&(i.dimBlockPosition={x:t.insertionPoint.x,y:t.insertionPoint.y,z:0}),i.rotation=t.rotationAngle,this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDb3PointAngularDimension"){var t=e,i=new u.AcDb3PointAngularDimension(t.centerPoint,t.subDefinitionPoint1,t.subDefinitionPoint2,t.definitionPoint);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbOrdinateDimension"){var t=e,i=new u.AcDbOrdinateDimension(t.subDefinitionPoint1,t.subDefinitionPoint2);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbRadialDimension"){var t=e,i=new u.AcDbRadialDimension(t.definitionPoint,t.centerPoint,t.leaderLength);return this.processDimensionCommonAttrs(e,i),i}else if(e.subclassMarker=="AcDbDiametricDimension"){var t=e,i=new u.AcDbDiametricDimension(t.definitionPoint,t.centerPoint,t.leaderLength);return this.processDimensionCommonAttrs(e,i),i}return null},o.prototype.processImage=function(e,t){t.position.copy(e.position),t.brightness=e.brightness,t.contrast=e.contrast,t.fade=e.fade,t.imageSize.copy(e.imageSize),t.imageDefId=e.imageDefHandle,t.isClipped=e.clipping>0,t.isShownClipped=(e.flags|4)>0,t.isImageShown=(e.flags|3)>0,t.isImageTransparent=(e.flags|8)>0,e.clippingBoundaryPath.forEach(function(i){t.clipBoundary.push(new u.AcGePoint2d(i))}),t.clipBoundaryType=e.clippingBoundaryType,t.width=Math.sqrt(Math.pow(e.uPixel.x,2)+Math.pow(e.uPixel.y,2)+Math.pow(e.uPixel.z,2))*e.imageSize.x,t.height=Math.sqrt(Math.pow(e.vPixel.x,2)+Math.pow(e.vPixel.y,2)+Math.pow(e.vPixel.z,2))*e.imageSize.y,t.rotation=Math.atan2(e.uPixel.y,e.uPixel.x)},o.prototype.convertImage=function(e){var t=new u.AcDbRasterImage;return this.processImage(e,t),t},o.prototype.convertWipeout=function(e){var t=new u.AcDbWipeout;return this.processImage(e,t),t},o.prototype.convertViewport=function(e){var t=new u.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},o.prototype.convertRay=function(e){var t=new u.AcDbRay;return t.basePoint.copy(e.firstPoint),t.unitDir.copy(e.unitDirection),t},o.prototype.convertXline=function(e){var t=new u.AcDbXline;return t.basePoint.copy(e.firstPoint),t.unitDir.copy(e.unitDirection),t},o.prototype.convertAttributeCommon=function(e,t){var i,n,s,r,a=e.text;t.textString=a.text,t.styleName=a.styleName,t.height=a.textHeight,t.position.copy(a.startPoint);var c=(i=e.alignmentPoint)!==null&&i!==void 0?i:a.endPoint,l=!c||c.x===0&&c.y===0&&((n=c.z)!==null&&n!==void 0?n:0)===0;c&&!l?t.alignmentPoint.copy(c):t.alignmentPoint.copy(a.startPoint),t.rotation=a.rotation,t.oblique=(s=a.obliqueAngle)!==null&&s!==void 0?s:0,t.thickness=a.thickness,t.horizontalMode=a.halign,t.verticalMode=a.valign,t.widthFactor=(r=a.xScale)!==null&&r!==void 0?r:1,t.tag=e.tag,t.fieldLength=e.fieldLength,t.isInvisible=(e.flags&u.AcDbAttributeFlags.Invisible)!==0,t.isConst=(e.flags&u.AcDbAttributeFlags.Const)!==0,t.isVerifiable=(e.flags&u.AcDbAttributeFlags.Verifiable)!==0,t.isPreset=(e.flags&u.AcDbAttributeFlags.Preset)!==0,t.lockPositionInBlock=e.lockPositionFlag,t.isReallyLocked=e.isReallyLocked,t.isMTextAttribute=(e.mtextFlag&u.AcDbAttributeMTextFlag.MultiLine)!==0,t.isConstMTextAttribute=(e.mtextFlag&u.AcDbAttributeMTextFlag.ConstMultiLine)!==0},o.prototype.convertAttribute=function(e){var t=new u.AcDbAttribute;return this.convertAttributeCommon(e,t),t},o.prototype.convertAttributeDefinition=function(e){var t=new u.AcDbAttributeDefinition;return this.convertAttributeCommon(e,t),t.prompt=e.prompt,t},o.prototype.convertBlockReference=function(e){var t=this,i=new u.AcDbBlockReference(e.name);return e.insertionPoint&&i.position.copy(e.insertionPoint),i.scaleFactors.x=e.xScale,i.scaleFactors.y=e.yScale,i.scaleFactors.z=e.zScale,i.rotation=e.rotation,i.normal.copy(e.extrusionDirection),e.handle!=null&&(i.objectId=e.handle),e.attribs&&e.attribs.forEach(function(n){var s=t.convert(n);s instanceof u.AcDbAttribute&&i.appendAttributes(s)}),i},o.prototype.processDimensionCommonAttrs=function(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},o.prototype.processCommonAttrs=function(e,t){if(t.layer=e.layer||"0",t.objectId=e.handle,e.ownerBlockRecordSoftId!=null&&(t.ownerId=e.ownerBlockRecordSoftId),e.lineType!=null&&(t.lineType=e.lineType),e.lineweight!=null&&(t.lineWeight=e.lineweight),e.lineTypeScale!=null&&(t.linetypeScale=e.lineTypeScale),e.color!=null||e.colorIndex!=null||e.colorName){var i=new u.AcCmColor;e.color!=null&&i.setRGBValue(e.color),e.colorIndex!=null&&(e.color==null||e.colorIndex===7)&&(i.colorIndex=e.colorIndex),e.colorName&&(i.colorName=e.colorName),t.color=i}if(e.isVisible!=null&&(t.visibility=e.isVisible),e.transparency!=null){var n=new u.AcCmTransparency;n.method=e.transparencyType,(n.isByBlock||n.isByBlock)&&(n.alpha=e.transparency),t.transparency=n}},o.prototype.readNumber=function(e,t){var i,n;try{for(var s=Bi(t),r=s.next();!r.done;r=s.next()){var a=r.value,c=e[a];if(typeof c=="number"&&Number.isFinite(c))return c}}catch(l){i={error:l}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}},o.prototype.readString=function(e,t){var i,n;try{for(var s=Bi(t),r=s.next();!r.done;r=s.next()){var a=r.value,c=e[a];if(typeof c=="string")return c}}catch(l){i={error:l}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}},o.prototype.readBoolean=function(e,t){var i,n;try{for(var s=Bi(t),r=s.next();!r.done;r=s.next()){var a=r.value,c=e[a];if(typeof c=="boolean")return c;if(typeof c=="number")return c!==0}}catch(l){i={error:l}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}},o.prototype.readPoint=function(e,t){var i,n,s;try{for(var r=Bi(t),a=r.next();!a.done;a=r.next()){var c=a.value,l=e[c];if(this.isPointLike(l))return l;if(Array.isArray(l)&&typeof l[0]=="number"&&typeof l[1]=="number")return{x:l[0],y:l[1],z:(s=l[2])!==null&&s!==void 0?s:0}}}catch(h){i={error:h}}finally{try{a&&!a.done&&(n=r.return)&&n.call(r)}finally{if(i)throw i.error}}},o.prototype.readLeaderLineArray=function(e){var t=this,i=e.leaderLines;if(Array.isArray(i))return i.map(function(r){if(!(!r||typeof r!="object")){var a=r.vertices;return Array.isArray(a)?a.filter(function(c){return t.isPointLike(c)}):void 0}}).filter(function(r){return!!r&&r.length>0});var n=e.vertices;if(Array.isArray(n)){var s=n.filter(function(r){return t.isPointLike(r)});return s.length>0?[s]:void 0}},o.prototype.isPointLike=function(e){return!!e&&typeof e=="object"&&typeof e.x=="number"&&typeof e.y=="number"},o}(),Zl=function(){var o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,n){i.__proto__=n}||function(i,n){for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[s]=n[s])},o(e,t)};return function(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");o(e,t);function i(){this.constructor=e}e.prototype=t===null?Object.create(t):(i.prototype=t.prototype,new i)}}(),Di=function(o,e,t,i){function n(s){return s instanceof t?s:new t(function(r){r(s)})}return new(t||(t=Promise))(function(s,r){function a(h){try{l(i.next(h))}catch(d){r(d)}}function c(h){try{l(i.throw(h))}catch(d){r(d)}}function l(h){h.done?s(h.value):n(h.value).then(a,c)}l((i=i.apply(o,e||[])).next())})},Mi=function(o,e){var t={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,n,s,r;return r={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(r[Symbol.iterator]=function(){return this}),r;function a(l){return function(h){return c([l,h])}}function c(l){if(i)throw new TypeError("Generator is already executing.");for(;r&&(r=0,l[0]&&(t=0)),t;)try{if(i=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return t.label++,{value:l[1],done:!1};case 5:t.label++,n=l[1],l=[0];continue;case 7:l=t.ops.pop(),t.trys.pop();continue;default:if(s=t.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){t=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){t.label=l[1];break}if(l[0]===6&&t.label<s[1]){t.label=s[1],s=l;break}if(s&&t.label<s[2]){t.label=s[2],t.ops.push(l);break}s[2]&&t.ops.pop(),t.trys.pop();continue}l=e.call(o,t)}catch(h){l=[6,h],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},Rr=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var i=t.call(o),n,s=[],r;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){r={error:a}}finally{try{n&&!n.done&&(t=i.return)&&t.call(i)}finally{if(r)throw r.error}}return s},jr=function(o,e,t){if(t||arguments.length===2)for(var i=0,n=e.length,s;i<n;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return o.concat(s||Array.prototype.slice.call(e))},Nr=function(o){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&o[e],i=0;if(t)return t.call(o);if(o&&typeof o.length=="number")return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Jl="*MODEL_SPACE",Ql=function(o){Zl(e,o);function e(t){t===void 0&&(t={});var i=o.call(this,t)||this;return t.useWorker=!0,t.parserWorkerUrl||(t.parserWorkerUrl="/assets/libredwg-parser-worker.js"),i}return e.prototype.parse=function(t,i){return Di(this,void 0,void 0,function(){var n,s,r,a;return Mi(this,function(c){switch(c.label){case 0:return n=this.config,s=this.getParserWorkerTimeout(t,i),n.useWorker&&n.parserWorkerUrl?(r=u.createWorkerApi({workerUrl:n.parserWorkerUrl,timeout:s,maxConcurrentWorkers:1}),[4,r.execute(t)]):[3,2];case 1:if(a=c.sent(),r.destroy(),a.success)return[2,a.data];throw new Error("Failed to parse drawing due to error: '".concat(a.error,"'"));case 2:throw new Error("dwg converter can run in web worker only!");case 3:return[2]}})})},e.prototype.getFonts=function(t){var i=new Map;t.tables.BLOCK_RECORD.entries.forEach(function(a){i.set(a.name,a)});var n=new Map,s=function(a){if(a){var c=a.lastIndexOf(".");return c>=0?a.substring(0,c).toLowerCase():a.toLowerCase()}};t.tables.STYLE.entries.forEach(function(a){var c=[],l=s(a.font);l&&c.push(l),l=s(a.bigFont),l&&c.push(l),n.set(a.name,c)});var r=new Set;return this.getFontsInBlock(t.entities,i,n,r),Array.from(r)},e.prototype.getFontsInBlock=function(t,i,n,s){var r=this,a=/\\f(.*?)\|/g;t.forEach(function(c){if(c.type=="MTEXT"){var l=c;jr([],Rr(l.text.matchAll(a)),!1).forEach(function(b){s.add(b[1].toLowerCase())});var h=n.get(l.styleName);h==null||h.forEach(function(b){return s.add(b)})}else if(c.type=="TEXT"){var d=c,h=n.get(d.styleName);h==null||h.forEach(function(v){return s.add(v)})}else if(c.type=="MULTILEADER"||c.type=="MLEADER"){var p=c,m=p.textContent,d=typeof(m==null?void 0:m.text)=="string"?m.text:"";jr([],Rr(d.matchAll(a)),!1).forEach(function(C){s.add(C[1].toLowerCase())});var f=typeof(m==null?void 0:m.styleName)=="string"?m.styleName:typeof p.textStyleName=="string"?p.textStyleName:typeof p.styleName=="string"?p.styleName:void 0,h=f?n.get(f):void 0;h==null||h.forEach(function(C){return s.add(C)})}else if(c.type=="INSERT"){var w=c,x=i.get(w.name);x&&r.getFontsInBlock(x.entities,i,n,s)}})},e.prototype.processLineTypes=function(t,i){var n=this,s=t.tables.LTYPE.entries;s.forEach(function(r){var a={name:r.name,description:r.description,standardFlag:r.standardFlag,totalPatternLength:r.totalPatternLength,pattern:r.pattern},c=new u.AcDbLinetypeTableRecord(a);n.processCommonTableEntryAttrs(r,c),c.name=r.name,i.tables.linetypeTable.add(c)})},e.prototype.processTextStyles=function(t,i){var n=this,s=t.tables.STYLE.entries;s.forEach(function(r){var a=new u.AcDbTextStyleTableRecord(r);n.processCommonTableEntryAttrs(r,a),i.tables.textStyleTable.add(a)}),i.ensureTextStyleDefaults()},e.prototype.processDimStyles=function(t,i){var n=this,s=t.tables.DIMSTYLE.entries;s.forEach(function(r){var a={name:r.name,ownerId:r.ownerHandle,dimpost:r.DIMPOST||"",dimapost:r.DIMAPOST||"",dimscale:r.DIMSCALE,dimasz:r.DIMASZ,dimexo:r.DIMEXO,dimdli:r.DIMDLI,dimexe:r.DIMEXE,dimrnd:r.DIMRND,dimdle:r.DIMDLE,dimtp:r.DIMTP,dimtm:r.DIMTM,dimtxt:r.DIMTXT,dimcen:r.DIMCEN,dimtsz:r.DIMTSZ,dimaltf:r.DIMALTF,dimlfac:r.DIMLFAC,dimtvp:r.DIMTVP,dimtfac:r.DIMTFAC,dimgap:r.DIMGAP,dimaltrnd:r.DIMALTRND,dimtol:r.DIMTOL==null||r.DIMTOL==0?0:1,dimlim:r.DIMLIM==null||r.DIMLIM==0?0:1,dimtih:r.DIMTIH==null||r.DIMTIH==0?0:1,dimtoh:r.DIMTOH==null||r.DIMTOH==0?0:1,dimse1:r.DIMSE1==null||r.DIMSE1==0?0:1,dimse2:r.DIMSE2==null||r.DIMSE2==0?0:1,dimtad:r.DIMTAD,dimzin:r.DIMZIN,dimazin:r.DIMAZIN,dimalt:r.DIMALT,dimaltd:r.DIMALTD,dimtofl:r.DIMTOFL,dimsah:r.DIMSAH,dimtix:r.DIMTIX,dimsoxd:r.DIMSOXD,dimclrd:r.DIMCLRD,dimclre:r.DIMCLRE,dimclrt:r.DIMCLRT,dimadec:r.DIMADEC||0,dimunit:r.DIMUNIT||2,dimdec:r.DIMDEC,dimtdec:r.DIMTDEC,dimaltu:r.DIMALTU,dimalttd:r.DIMALTTD,dimaunit:r.DIMAUNIT,dimfrac:r.DIMFRAC,dimlunit:r.DIMLUNIT,dimdsep:r.DIMDSEP||".",dimtmove:r.DIMTMOVE||0,dimjust:r.DIMJUST,dimsd1:r.DIMSD1,dimsd2:r.DIMSD2,dimtolj:r.DIMTOLJ,dimtzin:r.DIMTZIN,dimaltz:r.DIMALTZ,dimalttz:r.DIMALTTZ,dimfit:r.DIMFIT||0,dimupt:r.DIMUPT,dimatfit:r.DIMATFIT,dimtxsty:u.DEFAULT_TEXT_STYLE,dimldrblk:"",dimblk:r.DIMBLK||"",dimblk1:r.DIMBLK1||"",dimblk2:r.DIMBLK2||"",dimlwd:r.DIMLWD,dimlwe:r.DIMLWE},c=new u.AcDbDimStyleTableRecord(a);n.processCommonTableEntryAttrs(r,c),i.tables.dimStyleTable.add(c)})},e.prototype.processLayers=function(t,i){var n=this,s=t.tables.LAYER.entries;s.forEach(function(r){var a=new u.AcCmColor;a.colorIndex=r.colorIndex;var c=new u.AcDbLayerTableRecord({name:r.name,standardFlags:r.standardFlag,linetype:r.lineType,lineWeight:r.lineweight,isOff:r.off,color:a,isPlottable:r.plotFlag!=0});n.processCommonTableEntryAttrs(r,c),i.tables.layerTable.add(c)})},e.prototype.processViewports=function(t,i){var n=this,s=t.tables.VPORT.entries;s.forEach(function(r){var a,c,l,h,d,p,m=new u.AcDbViewportTableRecord;n.processCommonTableEntryAttrs(r,m),r.circleSides&&(m.circleSides=r.circleSides),m.standardFlag=r.standardFlag,m.center.copy((a=r.center)!==null&&a!==void 0?a:u.VPORT_FALLBACK_CENTER_2D),m.lowerLeftCorner.copy((c=r.lowerLeftCorner)!==null&&c!==void 0?c:u.VPORT_FALLBACK_LLC),m.upperRightCorner.copy((l=r.upperRightCorner)!==null&&l!==void 0?l:u.VPORT_FALLBACK_URC),r.snapBasePoint&&m.snapBase.copy(r.snapBasePoint),r.snapRotationAngle&&(m.snapAngle=r.snapRotationAngle),r.snapSpacing&&m.snapIncrements.copy(r.snapSpacing),r.majorGridLines&&(m.gridMajor=r.majorGridLines),r.gridSpacing&&m.gridIncrements.copy(r.gridSpacing),r.backgroundObjectId&&(m.backgroundObjectId=r.backgroundObjectId),m.gsView.center.copy((h=r.center)!==null&&h!==void 0?h:u.VPORT_FALLBACK_CENTER_2D),m.gsView.viewDirectionFromTarget.copy((d=r.viewDirectionFromTarget)!==null&&d!==void 0?d:u.VPORT_FALLBACK_VIEW_DIR),m.gsView.viewTarget.copy((p=r.viewTarget)!==null&&p!==void 0?p:u.VPORT_FALLBACK_VIEW_TARGET),r.lensLength&&(m.gsView.lensLength=r.lensLength),r.frontClippingPlane&&(m.gsView.frontClippingPlane=r.frontClippingPlane),r.backClippingPlane&&(m.gsView.backClippingPlane=r.backClippingPlane),r.viewHeight&&(m.gsView.viewHeight=r.viewHeight),r.viewTwistAngle&&(m.gsView.viewTwistAngle=r.viewTwistAngle),r.frozenLayers&&(m.gsView.frozenLayers=r.frozenLayers),r.styleSheet&&(m.gsView.styleSheet=r.styleSheet),r.renderMode&&(m.gsView.renderMode=r.renderMode),r.viewMode&&(m.gsView.viewMode=r.viewMode),r.ucsIconSetting&&(m.gsView.ucsIconSetting=r.ucsIconSetting),r.ucsOrigin&&m.gsView.ucsOrigin.copy(r.ucsOrigin),r.ucsXAxis&&m.gsView.ucsXAxis.copy(r.ucsXAxis),r.ucsYAxis&&m.gsView.ucsYAxis.copy(r.ucsYAxis),r.orthographicType&&(m.gsView.orthographicType=r.orthographicType),r.shadePlotSetting&&(m.gsView.shadePlotSetting=r.shadePlotSetting),r.shadePlotObjectId&&(m.gsView.shadePlotObjectId=r.shadePlotObjectId),r.visualStyleObjectId&&(m.gsView.visualStyleObjectId=r.visualStyleObjectId),r.isDefaultLightingOn&&(m.gsView.isDefaultLightingOn=r.isDefaultLightingOn),r.defaultLightingType&&(m.gsView.defaultLightingType=r.defaultLightingType),r.brightness&&(m.gsView.brightness=r.brightness),r.contrast&&(m.gsView.contrast=r.contrast),r.ambientColor&&(m.gsView.ambientColor=r.ambientColor),i.tables.viewportTable.add(m)})},e.prototype.processBlockTables=function(t,i){var n=this,s=t.tables.BLOCK_RECORD.entries;s.forEach(function(r){var a=i.tables.blockTable.getAt(r.name);a||(a=new u.AcDbBlockTableRecord,a.objectId=r.handle,a.name=r.name,a.ownerId=r.ownerHandle,a.origin.copy(r.basePoint),a.layoutId=r.layout,a.blockInsertUnits=r.insertionUnits,a.explodability=r.explodability,a.blockScaling=r.scalability,r.bmpPreview&&(a.bmpPreview=r.bmpPreview),i.tables.blockTable.add(a)),!a.isModelSapce&&r.entities&&r.entities.length>0&&n.processEntitiesInBlock(r.entities,a)})},e.prototype.processBlocks=function(t,i){},e.prototype.processEntitiesInBlock=function(t,i){return Di(this,void 0,void 0,function(){var n,s,r,a,c,l;return Mi(this,function(h){for(n=new Fr,s=t.length,r=[],a=0;a<s;a++)c=t[a],l=n.convert(c),l&&r.push(l);return i.appendEntity(r),[2]})})},e.prototype.processEntities=function(t,i,n,s,r){return Di(this,void 0,void 0,function(){var a,c,l,h,d,p=this;return Mi(this,function(m){switch(m.label){case 0:return a=new Fr,c=[],t.tables.BLOCK_RECORD.entries.forEach(function(f){p.isModelSpace(f.name)&&(c=f.entities)}),l=c.length,h=new u.AcDbBatchProcessing(l,100-s.value,n),this.config.convertByEntityType&&(c=this.groupAndFlattenByType(c)),d=i.tables.blockTable.modelSpace,[4,h.processChunk(function(f,w){return Di(p,void 0,void 0,function(){var x,b,v,C,P;return Mi(this,function(L){switch(L.label){case 0:for(x=[],b=f;b<w;b++)v=c[b],C=a.convert(v),C&&x.push(C);return d.appendEntity(x),r?(P=s.value+w/l*(100-s.value),P>100&&(P=100),[4,r(P,"ENTITY","IN-PROGRESS")]):[3,2];case 1:L.sent(),L.label=2;case 2:return[2]}})})})];case 1:return m.sent(),[2]}})})},e.prototype.processHeader=function(t,i){var n,s,r,a,c,l,h,d,p,m,f=t.header;f.CECOLOR&&(f.CECOLOR.index>=0&&f.CECOLOR.index<=256?i.cecolor.colorIndex=f.CECOLOR.index:i.cecolor.setRGBValue(f.CECOLOR.rgb)),i.angbase=(n=f.ANGBASE)!==null&&n!==void 0?n:0,i.angdir=(s=f.ANGDIR)!==null&&s!==void 0?s:0,i.aunits=(r=f.AUNITS)!==null&&r!==void 0?r:0,f.AUPREC!=null&&(i.auprec=f.AUPREC),f.LUNITS!=null&&(i.lunits=f.LUNITS),f.LUPREC!=null&&(i.luprec=f.LUPREC),f.UNITMODE!=null&&(i.unitmode=f.UNITMODE),f.MEASUREMENT!=null&&(i.measurement=f.MEASUREMENT),i.celtype=(a=f.CELTYPE)!==null&&a!==void 0?a:u.ByLayer,i.celtscale=(c=f.CELTSCALE)!==null&&c!==void 0?c:1,i.ltscale=(l=f.LTSCALE)!==null&&l!==void 0?l:1,f.EXTMAX&&(i.extmax=f.EXTMAX),f.EXTMIN&&(i.extmin=f.EXTMIN),i.insunits=(h=f.INSUNITS)!==null&&h!==void 0?h:1,i.pdmode=(d=f.PDMODE)!==null&&d!==void 0?d:0,i.pdsize=(p=f.PDSIZE)!==null&&p!==void 0?p:0,i.textstyle=(m=f.TEXTSTYLE)!==null&&m!==void 0?m:u.DEFAULT_TEXT_STYLE},e.prototype.processCommonTableEntryAttrs=function(t,i){i.name=t.name,i.objectId=t.handle,t.ownerHandle!=null&&(i.ownerId=t.ownerHandle)},e.prototype.processObjects=function(t,i){this.processLayouts(t,i),this.processImageDefs(t,i)},e.prototype.processLayouts=function(t,i){var n=this,s=i.objects.layout,r=t.objects.LAYOUT;r.forEach(function(a){var c,l,h=new u.AcDbLayout;h.layoutName=a.layoutName,h.tabOrder=a.tabOrder;var d=i.tables.blockTable.newIterator();h.objectId=a.handle;try{for(var p=Nr(d),m=p.next();!m.done;m=p.next()){var f=m.value;if(f.layoutId===h.objectId){h.blockTableRecordId=f.objectId;break}}}catch(w){c={error:w}}finally{try{m&&!m.done&&(l=p.return)&&l.call(p)}finally{if(c)throw c.error}}h.blockTableRecordId||a.layoutName==="Model"&&(h.blockTableRecordId=i.tables.blockTable.modelSpace.objectId),h.limits.min.copy(a.minLimit),h.limits.max.copy(a.maxLimit),h.extents.min.copy(a.minExtent),h.extents.max.copy(a.maxExtent),a.viewportId&&h.viewportArray.push(a.viewportId),n.processCommonObjectAttrs(a,h),s.setAt(h.layoutName,h)})},e.prototype.processImageDefs=function(t,i){var n=this,s=i.objects.imageDefinition,r=t.objects.IMAGEDEF;r.forEach(function(a){var c=new u.AcDbRasterImageDef;c.sourceFileName=a.fileName,n.processCommonObjectAttrs(a,c),s.setAt(c.objectId,c)})},e.prototype.processCommonObjectAttrs=function(t,i){i.objectId=t.handle,t.ownerHandle!=null&&(i.ownerId=t.ownerHandle)},e.prototype.groupAndFlattenByType=function(t){var i,n,s={},r=[];try{for(var a=Nr(t),c=a.next();!c.done;c=a.next()){var l=c.value;s[l.type]||(s[l.type]=[],r.push(l.type)),s[l.type].push(l)}}catch(h){i={error:h}}finally{try{c&&!c.done&&(n=a.return)&&n.call(a)}finally{if(i)throw i.error}}return r.flatMap(function(h){return s[h]})},e.prototype.isModelSpace=function(t){return t&&t.toUpperCase()==Jl},e}(u.AcDbDatabaseConverter);class zr{convert(){const e=A.instance.curDocument,t=e.database.dxfOut(void 0,6),i=this.getBaseName(e.fileName||e.docTitle);this.createFileAndDownloadIt(t,`${i}.dxf`)}createFileAndDownloadIt(e,t){const i=new Blob([e],{type:"application/dxf;charset=utf-8"}),n=URL.createObjectURL(i),s=document.createElement("a");s.href=n,s.download=t,document.body.appendChild(s),s.click(),document.body.removeChild(s),URL.revokeObjectURL(n)}getBaseName(e){return((e==null?void 0:e.trim())||"drawing").replace(/\.[^.]+$/,"")||"drawing"}}class Vr extends j{async execute(e){new zr().convert()}}class Gr{convert(e,t){const i=A.instance.curView,n=i.renderer.internalRenderer,s=i.internalScene,r=i.internalCamera;if(!s||!r){console.error("[PNGOUT] Scene or camera not available");return}const a=i.width/Math.max(i.height,1),c=e?this.getBoundsAspect(e):a;let l=Math.max(1,Math.round(i.width)),h=Math.max(1,Math.round(i.height));if(t&&t>0){const k=this.resolveOutputSize(t,c);l=k.width,h=k.height}const d=this.resolveRenderSizeForCenterCrop(l,h,a),p=d.width,m=d.height,f=p!==l||m!==h,w=r.zoom,x=r.position.clone();if(e){const k=new u.AcGeVector2d;e.getSize(k);const E=new u.AcGeVector2d;e.getCenter(E);const T=Math.max(Math.abs(k.x),Number.EPSILON),F=Math.max(Math.abs(k.y),Number.EPSILON),O=i.width/T,z=i.height/F,U=Math.min(O,z);r.position.set(E.x,E.y,r.position.z),r.zoom=U,r.updateProjectionMatrix()}const b=new y.WebGLRenderTarget(p,m,{minFilter:y.LinearFilter,magFilter:y.LinearFilter,format:y.RGBAFormat,type:y.UnsignedByteType}),v=n.getRenderTarget();n.setRenderTarget(b),n.render(s,r);const C=new Uint8Array(p*m*4);n.readRenderTargetPixels(b,0,0,p,m,C),n.setRenderTarget(v),b.dispose(),r.zoom=w,r.position.copy(x),r.updateProjectionMatrix();const P=this.flipPixelsVertically(C,p,m),L=f?this.cropPixelsCentered(P,p,m,l,h):P,M=this.createCanvasFromPixels(L,l,h);this.createFileAndDownloadIt(M)}resolveOutputSize(e,t){const i=Math.max(1,Math.round(e)),n=Number.isFinite(t)&&t>Number.EPSILON?t:1;return n>=1?{width:i,height:Math.max(1,Math.round(i/n))}:{width:Math.max(1,Math.round(i*n)),height:i}}resolveRenderSizeForCenterCrop(e,t,i){const n=Number.isFinite(i)&&i>Number.EPSILON?i:1,s=e/Math.max(t,1);return Math.abs(s-n)<1e-6?{width:e,height:t}:n>s?{width:Math.max(e,Math.ceil(t*n)),height:t}:{width:e,height:Math.max(t,Math.ceil(e/n))}}cropPixelsCentered(e,t,i,n,s){if(t===n&&i===s)return e;const r=Math.floor((t-n)/2),a=Math.floor((i-s)/2),c=new Uint8Array(n*s*4);for(let l=0;l<s;l++){const h=((l+a)*t+r)*4,d=h+n*4,p=l*n*4;c.set(e.subarray(h,d),p)}return c}getBoundsAspect(e){const t=new u.AcGeVector2d;e.getSize(t);const i=Math.max(Math.abs(t.x),Number.EPSILON),n=Math.max(Math.abs(t.y),Number.EPSILON);return i/n}flipPixelsVertically(e,t,i){const n=new Uint8Array(t*i*4);for(let s=0;s<i;s++){const r=(i-1-s)*t*4,a=s*t*4;for(let c=0;c<t*4;c++)n[a+c]=e[r+c]}return n}createCanvasFromPixels(e,t,i){const n=document.createElement("canvas");n.width=t,n.height=i;const s=n.getContext("2d"),r=s.createImageData(t,i);return r.data.set(e),s.putImageData(r,0,0),n}createFileAndDownloadIt(e){const t=e.toDataURL("image/png"),i=document.createElement("a");i.href=t,i.download=`cad-export-${Date.now()}.png`,document.body.appendChild(i),i.click(),document.body.removeChild(i)}}const On=1024;class Kr extends j{async execute(e){const t=new Gr,i=A.instance.curView;this.syncActiveLayoutViewSize(i);const n=new yi(g.t("jig.pngout.boundsFirstCorner"),g.t("jig.pngout.boundsSecondCorner"));n.disableOSnap=!0;const s=await A.instance.editor.getBox(n);let r;if(s.status===S.OK&&s.value)r=this.expandBoundsToEntityExtents(s.value,i).bounds;else if(s.status===S.None)r=this.getCurrentDrawingBounds();else return;const a=new q(`${g.t("jig.pngout.longSidePrompt")} <${On}>`);a.allowNone=!0,a.allowNegative=!1,a.allowZero=!1,a.defaultValue=On,a.useDefaultValue=!0;const c=await A.instance.editor.getDouble(a);if(c.status===S.Cancel||c.status===S.Error)return;const l=c.status===S.OK&&c.value!==void 0?c.value:On;t.convert(r,l)}getCurrentDrawingBounds(){const t=A.instance.curDocument.database.extents;return new u.AcGeBox2d(new u.AcGePoint2d(t.min.x,t.min.y),new u.AcGePoint2d(t.max.x,t.max.y))}expandBoundsToEntityExtents(e,t){const i=t.search(e),n=new u.AcGeBox2d;let s=!1;const r=l=>{var h;n.expandByPoint(new u.AcGePoint2d(l.minX,l.minY)),n.expandByPoint(new u.AcGePoint2d(l.maxX,l.maxY)),s=!0,(h=l.children)==null||h.forEach(d=>{n.expandByPoint(new u.AcGePoint2d(d.minX,d.minY)),n.expandByPoint(new u.AcGePoint2d(d.maxX,d.maxY))})};if(i.forEach(l=>r(l)),!s||n.isEmpty())return{bounds:e,expanded:!1};const a=new u.AcGeBox2d().expandByPoint(e.min).expandByPoint(e.max).expandByPoint(n.min).expandByPoint(n.max),c=a.min.x!==e.min.x||a.min.y!==e.min.y||a.max.x!==e.max.x||a.max.y!==e.max.y;return{bounds:a,expanded:c}}syncActiveLayoutViewSize(e){const t=e.activeLayoutView;t&&t.resize(e.width,e.height)}}class Ur extends j{constructor(){super(),this._history=[],this.mode=R.Write}async execute(e){for(this._history=[];;){const t=await this.promptMainAction();if(!t)return;if(t.type==="keyword"){t.keyword==="Name"?await this.runNameBranch(e):this.runUndo(e);continue}this.deleteLayerByEntity(e,t.objectId)}}notify(e,t="info"){A.instance.editor.showMessage(e,t)}addKeyword(e,t){e.keywords.add(g.t(`jig.laydel.keywords.${t}.display`),g.t(`jig.laydel.keywords.${t}.global`),g.t(`jig.laydel.keywords.${t}.local`))}async promptMainAction(){const e=new Le(g.t("jig.laydel.selectPrompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(g.t("jig.laydel.invalidSelection")),this.addKeyword(e,"name"),this.addKeyword(e,"undo");const t=await A.instance.editor.getEntity(e);if(t.status===S.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===S.Keyword&&(t.stringResult==="Name"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runNameBranch(e){for(;;){const t=await this.promptLayerNameAction();if(!t)return;if(t.type==="keyword"){t.keyword==="?"?this.listLayers(e):this.runUndo(e);continue}this.deleteLayerByName(e,t.layerName)}}async promptLayerNameAction(){const e=new le(g.t("jig.laydel.namePrompt"));e.allowSpaces=!0,e.allowEmpty=!0,this.addKeyword(e,"list"),this.addKeyword(e,"undo");const t=await A.instance.editor.getString(e);if(t.status===S.Keyword&&(t.stringResult==="?"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult};if(t.status!==S.OK)return;const i=(t.stringResult??"").trim();if(i)return{type:"name",layerName:i}}listLayers(e){const t=e.doc.database,i=[...t.tables.layerTable.newIterator()].map(n=>({name:n.name,current:t.clayer===n.name?"*":"",on:n.isOff?"No":"Yes",frozen:n.isFrozen?"Yes":"No",locked:n.isLocked?"Yes":"No"}));console.table(i),this.notify(g.t("jig.laydel.layerListSummary"),"info")}deleteLayerByEntity(e,t){var s;const i=e.doc.database.tables.blockTable.getEntityById(t),n=(s=i==null?void 0:i.layer)==null?void 0:s.trim();if(!n){this.notify(g.t("jig.laydel.invalidSelection"),"warning");return}this.deleteLayerByName(e,n)}deleteLayerByName(e,t){const i=e.doc.database,n=i.tables.layerTable.getAt(t);if(!n){this.notify(`${g.t("jig.laydel.layerNotFound")}: ${t}`);return}if(n.name==="0"){this.notify(g.t("jig.laydel.cannotDeleteZeroLayer"),"warning");return}if(n.name===i.clayer){this.notify(g.t("jig.laydel.cannotDeleteCurrent"),"warning");return}const s=this.collectLayerEntities(e,n.name);this.removeLayerEntities(e,s);const r=n.clone();i.tables.layerTable.remove(n.name),i.events.layerErased.dispatch({database:i,layer:n}),this._history.push({layer:r,entities:s}),e.view.selectionSet.clear(),A.instance.regen(),this.notify(`${g.t("jig.laydel.deleted")}: ${n.name}`,"success")}collectLayerEntities(e,t){const i=[];for(const n of e.doc.database.tables.blockTable.newIterator())for(const s of n.newIterator())s.layer===t&&i.push({ownerId:n.objectId,objectId:s.objectId,entity:s.clone()});return i}removeLayerEntities(e,t){const i=new Map;t.forEach(({ownerId:n,objectId:s})=>{const r=i.get(n)??[];r.push(s),i.set(n,r)}),i.forEach((n,s)=>{var r;(r=e.doc.database.tables.blockTable.getIdAt(s))==null||r.removeEntity(n)})}runUndo(e){const t=this._history.pop();if(!t){this.notify(g.t("jig.laydel.nothingToUndo"),"warning");return}const i=e.doc.database;i.tables.layerTable.has(t.layer.name)||i.tables.layerTable.add(t.layer.clone());const n=new Map;t.entities.forEach(({ownerId:s,entity:r})=>{const a=n.get(s)??[];a.push(r.clone()),n.set(s,a)}),n.forEach((s,r)=>{(i.tables.blockTable.getIdAt(r)??i.tables.blockTable.modelSpace).appendEntity(s)}),e.view.selectionSet.clear(),A.instance.regen(),this.notify(`${g.t("jig.laydel.restored")}: ${t.layer.name}`,"success")}}class $r extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=e.view.selectionSet,i=t.count>0?t.ids:await this.promptSelection();!i||i.length===0||this.moveObjectsToCurrentLayer(e,i)}async promptSelection(){var i;const e=new Re(g.t("jig.laycur.prompt")),t=await A.instance.editor.getSelection(e);if(t.status===S.OK)return((i=t.value)==null?void 0:i.ids)??[]}moveObjectsToCurrentLayer(e,t){var l;const i=e.doc.database,n=(l=i.clayer)==null?void 0:l.trim(),s=n?i.tables.layerTable.getAt(n):void 0;if(!s){this.notify(g.t("jig.laycur.currentLayerNotFound"),"warning");return}const r=[];let a=0,c=0;if(new Set(t).forEach(h=>{const d=i.tables.blockTable.getEntityById(h);if(!d){c++;return}if(d.layer===s.name){a++;return}d.layer=s.name,r.push(d)}),r.length===0){this.notify(a>0?g.t("jig.laycur.alreadyCurrent"):g.t("jig.laycur.noObjects"),a>0&&c===0?"info":"warning");return}r.forEach(h=>h.triggerModifiedEvent()),e.view.selectionSet.clear(),A.instance.regen(),this.notify(`${g.t("jig.laycur.changed")}: ${r.length} (${s.name})`,"success")}notify(e,t="info"){A.instance.editor.showMessage(e,t)}}const eh={viewportMode:"Freeze",blockSelectionMode:"None"},xe=class xe extends j{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=R.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=xe._settings.viewportMode!=="Vpfreeze";;){const t=await this.promptSelection();if(!t)return;if(t.type==="keyword"){t.keyword==="Settings"?await this.runSettings():this.runUndo(e);continue}this.freezeEntityLayer(e,t.objectId)}}notify(e,t="info"){A.instance.editor.showMessage(e,t)}addKeyword(e,t){e.keywords.add(g.t(`jig.layfrz.keywords.${t}.display`),g.t(`jig.layfrz.keywords.${t}.global`),g.t(`jig.layfrz.keywords.${t}.local`))}async promptSelection(){const e=new Le(g.t("jig.layfrz.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(g.t("jig.layfrz.invalidSelection")),this.addKeyword(e,"settings"),this.addKeyword(e,"undo");const t=await A.instance.editor.getEntity(e);if(t.status===S.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===S.Keyword&&(t.stringResult==="Settings"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runSettings(){for(;;){const e=new X(g.t("jig.layfrz.settingsPrompt"));e.allowNone=!0,this.addKeyword(e,"viewports"),this.addKeyword(e,"blockSelection");const t=await A.instance.editor.getKeywords(e);if(t.status!==S.OK)return;const i=t.stringResult;if(!i)return;i==="Viewports"?await this.promptViewportMode():await this.promptBlockSelectionMode()}}async promptViewportMode(){const e=new X(g.t("jig.layfrz.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(g.t("jig.layfrz.keywords.freeze.display"),g.t("jig.layfrz.keywords.freeze.global"),g.t("jig.layfrz.keywords.freeze.local")),i=e.keywords.add(g.t("jig.layfrz.keywords.vpfreeze.display"),g.t("jig.layfrz.keywords.vpfreeze.global"),g.t("jig.layfrz.keywords.vpfreeze.local"));e.keywords.default=xe._settings.viewportMode==="Vpfreeze"?i:t;const n=await A.instance.editor.getKeywords(e);if(n.status!==S.OK)return;const s=n.stringResult;s&&(xe._settings.viewportMode=s,s==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.notify(g.t("jig.layfrz.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new X(g.t("jig.layfrz.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(g.t("jig.layfrz.keywords.block.display"),g.t("jig.layfrz.keywords.block.global"),g.t("jig.layfrz.keywords.block.local")),i=e.keywords.add(g.t("jig.layfrz.keywords.entity.display"),g.t("jig.layfrz.keywords.entity.global"),g.t("jig.layfrz.keywords.entity.local")),n=e.keywords.add(g.t("jig.layfrz.keywords.none.display"),g.t("jig.layfrz.keywords.none.global"),g.t("jig.layfrz.keywords.none.local"));e.keywords.default=xe._settings.blockSelectionMode==="Block"?t:xe._settings.blockSelectionMode==="Entity"?i:n;const s=await A.instance.editor.getKeywords(e);if(s.status!==S.OK)return;const r=s.stringResult;r&&(xe._settings.blockSelectionMode=r,this.notify(g.t("jig.layfrz.nestedSelectionLimited")))}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}freezeEntityLayer(e,t){var a;const i=e.doc.database,n=i.tables.blockTable.getEntityById(t),s=(a=n==null?void 0:n.layer)==null?void 0:a.trim();if(!s){this.notify(g.t("jig.layfrz.invalidSelection"),"warning");return}const r=i.tables.layerTable.getAt(s);if(!r){this.notify(`${g.t("jig.layfrz.layerNotFound")}: ${s}`,"warning");return}if(r.name===i.clayer){this.notify(g.t("jig.layfrz.cannotFreezeCurrent"),"warning");return}if(r.isFrozen){this.notify(`${g.t("jig.layfrz.alreadyFrozen")}: ${r.name}`,"info");return}xe._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.notify(g.t("jig.layfrz.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:r.name,wasFrozen:r.isFrozen}),this.setLayerFrozen(r,!0),e.view.selectionSet.clear(),this.notify(`${g.t("jig.layfrz.frozen")}: ${r.name}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.notify(g.t("jig.layfrz.nothingToUndo"),"warning");return}const i=e.doc.database.tables.layerTable.getAt(t.layerName);if(!i){this.notify(`${g.t("jig.layfrz.layerNotFound")}: ${t.layerName}`,"warning");return}this.setLayerFrozen(i,t.wasFrozen),e.view.selectionSet.clear(),this.notify(`${g.t("jig.layfrz.restored")}: ${i.name}`,"success")}};xe._settings={...eh};let Oi=xe;class Wr{static set(e){this._snapshot=e}static consume(){const e=this._snapshot;return this._snapshot=void 0,e}}function Hr(o){return{isOff:o.isOff,isFrozen:o.isFrozen,isLocked:o.isLocked}}function th(o,e){return o.isOff===e.isOff&&o.isFrozen===e.isFrozen&&o.isLocked===e.isLocked}const ih={isolationMode:"Off",offMode:"Off"},ae=class ae extends j{constructor(){super(),this._vpfreezeHintShown=!1,this._lockFadeHintShown=!1,this.mode=R.Write}async execute(e){this._vpfreezeHintShown=ae._settings.offMode!=="Vpfreeze",this._lockFadeHintShown=ae._settings.isolationMode!=="LockAndFade";const t=e.view.selectionSet.ids;if(t.length>0){this.isolateSelectedObjectLayers(e,t);return}for(;;){const i=await this.promptSelection();if(!i)return;if(i.type==="keyword"){await this.runSettings();continue}this.isolateSelectedObjectLayers(e,i.objectIds);return}}notify(e,t="info"){A.instance.editor.showMessage(e,t)}addKeyword(e,t){e.keywords.add(g.t(`jig.layiso.keywords.${t}.display`),g.t(`jig.layiso.keywords.${t}.global`),g.t(`jig.layiso.keywords.${t}.local`))}async promptSelection(){var i;const e=new Re(g.t("jig.layiso.prompt"));this.addKeyword(e,"settings");const t=await A.instance.editor.getSelection(e);if(t.status===S.OK)return{type:"selection",objectIds:((i=t.value)==null?void 0:i.ids)??[]};if(t.status===S.Keyword&&t.stringResult==="Settings")return{type:"keyword",keyword:t.stringResult}}async runSettings(){const e=new X(g.t("jig.layiso.settingsPrompt"));e.allowNone=!0;const t=e.keywords.add(g.t("jig.layiso.keywords.off.display"),g.t("jig.layiso.keywords.off.global"),g.t("jig.layiso.keywords.off.local")),i=e.keywords.add(g.t("jig.layiso.keywords.lockAndFade.display"),g.t("jig.layiso.keywords.lockAndFade.global"),g.t("jig.layiso.keywords.lockAndFade.local"));e.keywords.default=ae._settings.isolationMode==="LockAndFade"?i:t;const n=await A.instance.editor.getKeywords(e);if(n.status!==S.OK)return;const s=n.stringResult;if(s){if(ae._settings.isolationMode=s,s==="Off"){await this.promptOffMode();return}this._lockFadeHintShown=!0,this.notify(g.t("jig.layiso.lockFadeFallback"))}}async promptOffMode(){const e=new X(g.t("jig.layiso.offModePrompt"));e.allowNone=!0;const t=e.keywords.add(g.t("jig.layiso.keywords.off.display"),g.t("jig.layiso.keywords.off.global"),g.t("jig.layiso.keywords.off.local")),i=e.keywords.add(g.t("jig.layiso.keywords.vpfreeze.display"),g.t("jig.layiso.keywords.vpfreeze.global"),g.t("jig.layiso.keywords.vpfreeze.local"));e.keywords.default=ae._settings.offMode==="Vpfreeze"?i:t;const n=await A.instance.editor.getKeywords(e);if(n.status!==S.OK)return;const s=n.stringResult;s&&(ae._settings.offMode=s,s==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.notify(g.t("jig.layiso.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}isolateSelectedObjectLayers(e,t){const i=this.collectSelectedLayerNames(e,t);if(i.length===0){this.notify(g.t("jig.layiso.noLayers"),"warning");return}const n=e.doc.database,s=n.tables.layerTable,r=new Set(i),a=s.getAt(i[0]),c=n.clayer,l=new Map;for(const p of s.newIterator())l.set(p.name,Hr(p));a&&(n.clayer=a.name);const h=new Set;for(const p of s.newIterator()){if(r.has(p.name)){p.isOff&&(p.isOff=!1,h.add(p.name)),p.isFrozen&&(this.setLayerFrozen(p,!1),h.add(p.name)),p.isLocked&&(this.setLayerLocked(p,!1),h.add(p.name));continue}if(ae._settings.isolationMode==="Off"){p.isOff||(p.isOff=!0,h.add(p.name));continue}p.isLocked||(this.setLayerLocked(p,!0),h.add(p.name))}const d=[];for(const p of s.newIterator()){const m=l.get(p.name);if(!m)continue;const f=Hr(p);th(m,f)||d.push({name:p.name,before:m,isolated:f})}Wr.set({currentLayerBefore:c,currentLayerAfter:n.clayer,layers:d}),ae._settings.isolationMode==="Off"&&ae._settings.offMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.notify(g.t("jig.layiso.vpfreezeFallback")),this._vpfreezeHintShown=!0),ae._settings.isolationMode==="LockAndFade"&&!this._lockFadeHintShown&&(this.notify(g.t("jig.layiso.lockFadeFallback")),this._lockFadeHintShown=!0),e.view.selectionSet.clear(),this.notify(`${g.t("jig.layiso.isolated")}: ${i.join(", ")} (${g.t("jig.layiso.affectedLayers")}: ${h.size})`,"success")}collectSelectedLayerNames(e,t){const i=e.doc.database,n=new Set,s=new Set;return t.forEach(r=>{var h;const a=i.tables.blockTable.getEntityById(r),c=(h=a==null?void 0:a.layer)==null?void 0:h.trim();if(!c)return;const l=i.tables.layerTable.getAt(c);l?n.add(l.name):s.add(c)}),s.size>0&&this.notify(`${g.t("jig.layiso.layerNotFound")}: ${[...s].join(", ")}`,"warning"),[...n]}};ae._settings={...ih};let Fi=ae;class Yr extends j{constructor(){super(),this.mode=R.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.lockEntityLayer(e,t)}}async promptSelection(){const e=new Le(g.t("jig.laylck.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(g.t("jig.laylck.invalidSelection"));const t=await A.instance.editor.getEntity(e);if(t.status===S.OK&&t.objectId)return t.objectId}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}lockEntityLayer(e,t){var a;const i=e.doc.database,n=i.tables.blockTable.getEntityById(t),s=(a=n==null?void 0:n.layer)==null?void 0:a.trim();if(!s){this.notify(g.t("jig.laylck.invalidSelection"),"warning");return}const r=i.tables.layerTable.getAt(s);if(!r){this.notify(`${g.t("jig.laylck.layerNotFound")}: ${s}`,"warning");return}if(r.isLocked){this.notify(`${g.t("jig.laylck.alreadyLocked")}: ${r.name}`,"info");return}this.setLayerLocked(r,!0),e.view.selectionSet.clear(),this.notify(`${g.t("jig.laylck.locked")}: ${r.name}`,"success")}notify(e,t="info"){A.instance.editor.showMessage(e,t)}}class Xr extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=[...e.doc.database.tables.layerTable.newIterator()];let i=0;if(t.forEach(n=>{n.isOff&&(n.isOff=!1,i++)}),e.view.selectionSet.clear(),i===0){this.notify(g.t("jig.layon.alreadyOn"));return}this.notify(`${g.t("jig.layon.turnedOn")}: ${i}`,"success")}notify(e,t="info"){A.instance.editor.showMessage(e,t)}}const nh={viewportMode:"Off",blockSelectionMode:"None"},Se=class Se extends j{constructor(){super(),this._history=[],this._vpfreezeHintShown=!1,this.mode=R.Write}async execute(e){for(this._history=[],this._vpfreezeHintShown=Se._settings.viewportMode!=="Vpfreeze";;){const t=await this.promptSelection();if(!t)return;if(t.type==="keyword"){t.keyword==="Settings"?await this.runSettings():this.runUndo(e);continue}this.turnOffEntityLayer(e,t.objectId)}}notify(e,t="info"){A.instance.editor.showMessage(e,t)}addKeyword(e,t){e.keywords.add(g.t(`jig.layoff.keywords.${t}.display`),g.t(`jig.layoff.keywords.${t}.global`),g.t(`jig.layoff.keywords.${t}.local`))}async promptSelection(){const e=new Le(g.t("jig.layoff.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(g.t("jig.layoff.invalidSelection")),this.addKeyword(e,"settings"),this.addKeyword(e,"undo");const t=await A.instance.editor.getEntity(e);if(t.status===S.OK&&t.objectId)return{type:"entity",objectId:t.objectId};if(t.status===S.Keyword&&(t.stringResult==="Settings"||t.stringResult==="Undo"))return{type:"keyword",keyword:t.stringResult}}async runSettings(){for(;;){const e=new X(g.t("jig.layoff.settingsPrompt"));e.allowNone=!0,this.addKeyword(e,"viewports"),this.addKeyword(e,"blockSelection");const t=await A.instance.editor.getKeywords(e);if(t.status!==S.OK)return;const i=t.stringResult;if(!i)return;i==="Viewports"?await this.promptViewportMode():await this.promptBlockSelectionMode()}}async promptViewportMode(){const e=new X(g.t("jig.layoff.viewportPrompt"));e.allowNone=!0;const t=e.keywords.add(g.t("jig.layoff.keywords.off.display"),g.t("jig.layoff.keywords.off.global"),g.t("jig.layoff.keywords.off.local")),i=e.keywords.add(g.t("jig.layoff.keywords.vpfreeze.display"),g.t("jig.layoff.keywords.vpfreeze.global"),g.t("jig.layoff.keywords.vpfreeze.local"));e.keywords.default=Se._settings.viewportMode==="Vpfreeze"?i:t;const n=await A.instance.editor.getKeywords(e);if(n.status!==S.OK)return;const s=n.stringResult;s&&(Se._settings.viewportMode=s,s==="Vpfreeze"?(this._vpfreezeHintShown=!0,this.notify(g.t("jig.layoff.vpfreezeFallback"))):this._vpfreezeHintShown=!1)}async promptBlockSelectionMode(){const e=new X(g.t("jig.layoff.blockSelectionPrompt"));e.allowNone=!0;const t=e.keywords.add(g.t("jig.layoff.keywords.block.display"),g.t("jig.layoff.keywords.block.global"),g.t("jig.layoff.keywords.block.local")),i=e.keywords.add(g.t("jig.layoff.keywords.entity.display"),g.t("jig.layoff.keywords.entity.global"),g.t("jig.layoff.keywords.entity.local")),n=e.keywords.add(g.t("jig.layoff.keywords.none.display"),g.t("jig.layoff.keywords.none.global"),g.t("jig.layoff.keywords.none.local"));e.keywords.default=Se._settings.blockSelectionMode==="Block"?t:Se._settings.blockSelectionMode==="Entity"?i:n;const s=await A.instance.editor.getKeywords(e);if(s.status!==S.OK)return;const r=s.stringResult;r&&(Se._settings.blockSelectionMode=r,this.notify(g.t("jig.layoff.nestedSelectionLimited")))}turnOffEntityLayer(e,t){var a;const i=e.doc.database,n=i.tables.blockTable.getEntityById(t),s=(a=n==null?void 0:n.layer)==null?void 0:a.trim();if(!s){this.notify(g.t("jig.layoff.invalidSelection"),"warning");return}const r=i.tables.layerTable.getAt(s);if(!r){this.notify(`${g.t("jig.layoff.layerNotFound")}: ${s}`,"warning");return}if(r.name===i.clayer){this.notify(g.t("jig.layoff.cannotTurnOffCurrent"),"warning");return}if(r.isOff){this.notify(`${g.t("jig.layoff.alreadyOff")}: ${r.name}`,"info");return}Se._settings.viewportMode==="Vpfreeze"&&!this._vpfreezeHintShown&&(this.notify(g.t("jig.layoff.vpfreezeFallback")),this._vpfreezeHintShown=!0),this._history.push({layerName:r.name,wasOff:r.isOff}),r.isOff=!0,e.view.selectionSet.clear(),this.notify(`${g.t("jig.layoff.turnedOff")}: ${r.name}`,"success")}runUndo(e){const t=this._history.pop();if(!t){this.notify(g.t("jig.layoff.nothingToUndo"),"warning");return}const i=e.doc.database.tables.layerTable.getAt(t.layerName);if(!i){this.notify(`${g.t("jig.layoff.layerNotFound")}: ${t.layerName}`,"warning");return}i.isOff=t.wasOff,e.view.selectionSet.clear(),this.notify(`${g.t("jig.layoff.restored")}: ${i.name}`,"success")}};Se._settings={...nh};let Ri=Se;class sh{constructor(){this.previousSnapshot=null}captureState(e){const t=e.doc.database;this.previousSnapshot={clayer:t.clayer,states:[...t.tables.layerTable.newIterator()].map(i=>({name:i.name,isOn:!i.isOff,isFrozen:i.isFrozen,isLocked:this.isLayerLocked(i)}))}}restorePreviousState(e){if(!this.previousSnapshot)return!1;const t=e.doc.database,i=this.previousSnapshot;i.states.forEach(s=>{const r=t.tables.layerTable.getAt(s.name);r&&(r.isOff=!s.isOn,this.setLayerFrozen(r,s.isFrozen),this.setLayerLocked(r,s.isLocked))});const n=t.tables.layerTable.getAt(i.clayer);return n?(n.isOff=!1,this.setLayerFrozen(n,!1),t.clayer=n.name,!0):!1}clearPreviousState(){this.previousSnapshot=null}isLayerLocked(e){return((e.standardFlags??0)&4)!==0}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}}const Fn=new sh;function rh(){return Fn}class qr extends j{constructor(){super(),this.mode=R.Write}async execute(e){Fn.restorePreviousState(e)?this.notify(g.t("jig.layerp.restored"),"success"):this.notify(g.t("jig.layerp.noPreviousState")),e.view.selectionSet.clear()}notify(e,t="info"){A.instance.editor.showMessage(e,t)}}function oh(o){Fn.captureState(o)}class Zr extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=[...e.doc.database.tables.layerTable.newIterator()];let i=0;if(t.forEach(n=>{n.isFrozen&&(this.setLayerFrozen(n,!1),i++)}),e.view.selectionSet.clear(),i===0){this.notify(g.t("jig.laythw.alreadyThawed"));return}this.notify(`${g.t("jig.laythw.thawed")}: ${i}`,"success")}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}notify(e,t="info"){A.instance.editor.showMessage(e,t)}}class Jr extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=Wr.consume();if(!t){this.notify(g.t("jig.layuniso.noPrevious"),"warning");return}const i=e.doc.database,n=i.tables.layerTable;let s=0;for(const r of t.layers){const a=n.getAt(r.name);if(!a){this.notify(`${g.t("jig.layuniso.layerNotFound")}: ${r.name}`,"warning");continue}this.restoreLayerIfUnchanged(a,r)&&s++}if(i.clayer===t.currentLayerAfter&&t.currentLayerBefore!==t.currentLayerAfter&&n.getAt(t.currentLayerBefore)&&(i.clayer=t.currentLayerBefore),e.view.selectionSet.clear(),s===0){this.notify(g.t("jig.layuniso.nothingRestored"));return}this.notify(`${g.t("jig.layuniso.restored")}: ${s}`,"success")}restoreLayerIfUnchanged(e,t){let i=!1;return e.isOff===t.isolated.isOff&&e.isOff!==t.before.isOff&&(e.isOff=t.before.isOff,i=!0),e.isFrozen===t.isolated.isFrozen&&e.isFrozen!==t.before.isFrozen&&(this.setLayerFrozen(e,t.before.isFrozen),i=!0),e.isLocked===t.isolated.isLocked&&e.isLocked!==t.before.isLocked&&(this.setLayerLocked(e,t.before.isLocked),i=!0),i}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}notify(e,t="info"){A.instance.editor.showMessage(e,t)}}class Qr extends j{constructor(){super(),this.mode=R.Write}async execute(e){for(;;){const t=await this.promptSelection();if(!t)return;this.unlockEntityLayer(e,t)}}async promptSelection(){const e=new Le(g.t("jig.layulk.prompt"));e.allowNone=!0,e.allowObjectOnLockedLayer=!0,e.setRejectMessage(g.t("jig.layulk.invalidSelection"));const t=await A.instance.editor.getEntity(e);if(t.status===S.OK&&t.objectId)return t.objectId}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}unlockEntityLayer(e,t){var a;const i=e.doc.database,n=i.tables.blockTable.getEntityById(t),s=(a=n==null?void 0:n.layer)==null?void 0:a.trim();if(!s){this.notify(g.t("jig.layulk.invalidSelection"),"warning");return}const r=i.tables.layerTable.getAt(s);if(!r){this.notify(`${g.t("jig.layulk.layerNotFound")}: ${s}`,"warning");return}if(!r.isLocked){this.notify(`${g.t("jig.layulk.alreadyUnlocked")}: ${r.name}`,"info");return}this.setLayerLocked(r,!1),e.view.selectionSet.clear(),this.notify(`${g.t("jig.layulk.unlocked")}: ${r.name}`,"success")}notify(e,t="info"){A.instance.editor.showMessage(e,t)}}class eo extends j{async execute(e){ee.emit("close-layer-manager",{})}}class to extends j{constructor(){super(),this.mode=R.Write}async execute(e){for(;;){const t=await this.promptMainKeyword();if(!t)return;switch(t){case"?":this.listLayers(e);break;case"Make":await this.runMake(e);break;case"Set":await this.runSet(e);break;case"New":await this.runNew(e);break;case"On":await this.runOnOff(e,!1);break;case"Off":await this.runOnOff(e,!0);break;case"Color":await this.runColor(e);break;case"Freeze":await this.runFreeze(e,!0);break;case"Thaw":await this.runFreeze(e,!1);break;case"Lock":await this.runLock(e,!0);break;case"Unlock":await this.runLock(e,!1);break;case"Description":await this.runDescription(e);break}}}async promptMainKeyword(){const e=new X(g.t("jig.layer.main"));e.allowNone=!0,this.addKeyword(e,"list"),this.addKeyword(e,"make"),this.addKeyword(e,"set"),this.addKeyword(e,"new"),this.addKeyword(e,"on"),this.addKeyword(e,"off"),this.addKeyword(e,"color"),this.addKeyword(e,"freeze"),this.addKeyword(e,"thaw"),this.addKeyword(e,"lock"),this.addKeyword(e,"unlock"),this.addKeyword(e,"description");const t=await A.instance.editor.getKeywords(e);return t.status!==S.OK?void 0:t.stringResult}addKeyword(e,t){e.keywords.add(g.t(`jig.layer.keywords.${t}.display`),g.t(`jig.layer.keywords.${t}.global`),g.t(`jig.layer.keywords.${t}.local`))}notify(e,t="info"){A.instance.editor.showMessage(e,t)}listLayers(e){const t=e.doc.database,n=[...t.tables.layerTable.newIterator()].map(s=>({name:s.name,current:t.clayer===s.name?"*":"",on:s.isOff?"No":"Yes",frozen:s.isFrozen?"Yes":"No",locked:s.isLocked?"Yes":"No",color:s.color.toString()}));console.table(n),this.notify(`${g.t("jig.layer.listSummary")} (${n.length})`,"info")}parseLayerNameInput(e,t){const i=e.trim();if(!i)return[];if(i==="*")return[...t];const n=i.split(",").map(s=>s.trim()).filter(Boolean);return[...new Set(n)]}resolveLayers(e,t){const i=e.doc.database.tables.layerTable,n=[],s=[];return t.forEach(r=>{const a=i.getAt(r);a?n.push(a):s.push(r)}),{layers:n,missing:s}}setLayerFrozen(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|1:i&-2}setLayerLocked(e,t){const i=e.standardFlags??0;e.standardFlags=t?i|4:i&-5}async promptLayerNames(e,t){const i=new le(e);i.allowSpaces=!1;const n=await A.instance.editor.getString(i);if(n.status!==S.OK)return;const s=[...t.doc.database.tables.layerTable.newIterator()].map(a=>a.name),r=this.parseLayerNameInput(n.stringResult??"",s);if(!r.length){this.notify(g.t("jig.layer.emptyInput"),"warning");return}return r}async promptSingleLayerName(e){const t=new le(e);t.allowSpaces=!0;const i=await A.instance.editor.getString(t);return i.status!==S.OK?void 0:(i.stringResult??"").trim()||void 0}async runNew(e){const t=await this.promptLayerNames(g.t("jig.layer.newPrompt"),e);if(!t)return;const i=e.doc.database.tables.layerTable;let n=0;const s=[];t.forEach(r=>{if(i.has(r)){s.push(r);return}i.add(new u.AcDbLayerTableRecord({name:r,isOff:!1,isPlottable:!0,color:new u.AcCmColor(u.AcCmColorMethod.ByACI,7),linetype:"Continuous"})),n++}),n>0&&this.notify(`${g.t("jig.layer.created")}: ${n}`,"success"),s.length>0&&this.notify(`${g.t("jig.layer.alreadyExists")}: ${s.join(", ")}`,"warning")}async runSet(e){const t=await this.promptSingleLayerName(g.t("jig.layer.setPrompt"));if(!t)return;const i=e.doc.database.tables.layerTable.getAt(t);if(!i){this.notify(`${g.t("jig.layer.notFound")}: ${t}`,"warning");return}i.isOff=!1,this.setLayerFrozen(i,!1),e.doc.database.clayer=i.name}async runMake(e){const t=await this.promptSingleLayerName(g.t("jig.layer.makePrompt"));if(!t)return;const i=e.doc.database.tables.layerTable;let n=i.getAt(t);n||(n=new u.AcDbLayerTableRecord({name:t,isOff:!1,isPlottable:!0,color:new u.AcCmColor(u.AcCmColorMethod.ByACI,7),linetype:"Continuous"}),i.add(n)),n.isOff=!1,this.setLayerFrozen(n,!1),e.doc.database.clayer=n.name}async runOnOff(e,t){const i=await this.promptLayerNames(t?g.t("jig.layer.offPrompt"):g.t("jig.layer.onPrompt"),e);if(!i)return;const n=e.doc.database,{layers:s,missing:r}=this.resolveLayers(e,i);r.length>0&&this.notify(`${g.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const a=[];s.forEach(c=>{if(t&&c.name===n.clayer){a.push(c.name);return}c.isOff=t}),a.length>0&&this.notify(g.t("jig.layer.cannotChangeCurrent"),"warning")}async runFreeze(e,t){const i=await this.promptLayerNames(t?g.t("jig.layer.freezePrompt"):g.t("jig.layer.thawPrompt"),e);if(!i)return;const n=e.doc.database,{layers:s,missing:r}=this.resolveLayers(e,i);r.length>0&&this.notify(`${g.t("jig.layer.notFound")}: ${r.join(", ")}`,"warning");const a=[];s.forEach(c=>{if(t&&c.name===n.clayer){a.push(c.name);return}this.setLayerFrozen(c,t)}),a.length>0&&this.notify(g.t("jig.layer.cannotChangeCurrent"),"warning")}async runLock(e,t){const i=await this.promptLayerNames(t?g.t("jig.layer.lockPrompt"):g.t("jig.layer.unlockPrompt"),e);if(!i)return;const{layers:n,missing:s}=this.resolveLayers(e,i);s.length>0&&this.notify(`${g.t("jig.layer.notFound")}: ${s.join(", ")}`,"warning"),n.forEach(r=>this.setLayerLocked(r,t))}parseColorInput(e){const t=e.trim();if(!t)return;if(/^\d+$/.test(t)){const n=Number(t);return n>=1&&n<=255?new u.AcCmColor(u.AcCmColorMethod.ByACI,n):void 0}const i=u.AcCmColor.fromString(t);if(i){if(i.isByACI){const n=i.colorIndex;if(n==null||n<1||n>255)return}if(!(i.isByLayer||i.isByBlock))return i}}async runColor(e){const t=await this.promptLayerNames(g.t("jig.layer.colorLayerPrompt"),e);if(!t)return;const{layers:i,missing:n}=this.resolveLayers(e,t);if(n.length>0&&this.notify(`${g.t("jig.layer.notFound")}: ${n.join(", ")}`,"warning"),i.length===0)return;const s=new le(g.t("jig.layer.colorValuePrompt"));s.allowSpaces=!1;const r=await A.instance.editor.getString(s);if(r.status!==S.OK)return;const a=this.parseColorInput(r.stringResult??"");if(!a){this.notify(g.t("jig.layer.invalidColor"),"warning");return}i.forEach(c=>{c.color=a.clone()})}async runDescription(e){const t=await this.promptSingleLayerName(g.t("jig.layer.descriptionLayerPrompt"));if(!t)return;const i=e.doc.database.tables.layerTable.getAt(t);if(!i){this.notify(`${g.t("jig.layer.notFound")}: ${t}`,"warning");return}const n=new le(g.t("jig.layer.descriptionValuePrompt"));n.allowSpaces=!0,n.allowEmpty=!0;const s=await A.instance.editor.getString(n);s.status===S.OK&&(i.description=s.stringResult??"")}}const ah={x:0,y:0,z:1},ch={x:0,y:0,z:-1};function ji(o){const e=o%u.TAU;return e>=0?e:e+u.TAU}function ze(o,e){return Math.hypot(e.x-o.x,e.y-o.y)}function Rn(o,e){return Math.atan2(e.y-o.y,e.x-o.x)*180/Math.PI}function de(o,e,t){const i=e.x-o.x,n=e.y-o.y,s=t===1?Math.atan2(n,i):Math.atan2(n,-i);return ji(s)}function io(o){return o===1?ah:ch}function no(o){return o.normal.z>=0?1:-1}function Ot(o){return new u.AcDbArc(o.center,o.radius,o.startAngle,o.endAngle,io(o.normalSign))}function so(o,e){o.center=e.center,o.radius=e.radius,o.startAngle=e.startAngle,o.endAngle=e.endAngle,o.normal=io(e.normalSign)}function ge(o){return{center:{x:o.x,y:o.y,z:0},radius:1e-6,startAngle:0,endAngle:Math.PI/2,normalSign:1}}function lh(o,e,t){const i=t.x-o.x,n=t.y-o.y,s=Math.hypot(i,n);if(u.AcGeTol.isNonPositive(s))return;const r=e/s;return{x:o.x+i*r,y:o.y+n*r,z:0}}function ro(o,e,t){const i=ji(t-o);return ji(e-o)<=i+1e-7}function hh(o,e,t,i){const n=de(o,e,1),s=de(o,t,1),r=de(o,i,1),a=ro(n,s,r),c=de(o,e,-1),l=de(o,t,-1),h=de(o,i,-1),d=ro(c,l,h);return a&&!d?1:!a&&d?-1:(t.x-e.x)*(i.y-e.y)-(t.y-e.y)*(i.x-e.x)>=0?1:-1}function oo(o,e,t,i=!1){const n=o.x,s=o.y,r=e.x,a=e.y,c=t.x,l=t.y,h=2*(n*(a-l)+r*(l-s)+c*(s-a));if(u.AcGeTol.equalToZero(h))return;const d=((n*n+s*s)*(a-l)+(r*r+a*a)*(l-s)+(c*c+l*l)*(s-a))/h,p=((n*n+s*s)*(c-r)+(r*r+a*a)*(n-c)+(c*c+l*l)*(r-n))/h,m={x:d,y:p,z:0},f=ze(m,o);if(!Number.isFinite(f)||u.AcGeTol.isNonPositive(f))return;const w=hh(m,o,e,t),x=i?-w:w;return{center:m,radius:f,startAngle:de(m,o,x),endAngle:de(m,t,x),normalSign:x}}function ct(o,e,t,i){const n=ze(o,e),s=ze(o,t);if(u.AcGeTol.isNonPositive(n)||u.AcGeTol.isNonPositive(s))return;const r=Math.max(u.FLOAT_TOL,n*u.FLOAT_TOL);if(!(Math.abs(n-s)>r))return{center:{x:o.x,y:o.y,z:0},radius:n,startAngle:de(o,e,i),endAngle:de(o,t,i),normalSign:i}}function Ni(o,e,t,i){const n=ze(o,e);if(u.AcGeTol.isNonPositive(n))return;const s=lh(o,n,t);if(s)return ct(o,e,s,i)}function lt(o,e,t){const i=ze(o,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||!u.AcGeTol.great(u.TAU-n,0))return;const s=t>=0?1:-1,r=de(o,e,s),a=ji(r+n);return{center:{x:o.x,y:o.y,z:0},radius:i,startAngle:r,endAngle:a,normalSign:s}}function Ft(o,e,t){const i=ze(o,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||u.AcGeTol.great(n,2*i))return;const s=Math.max(-1,Math.min(1,n/(2*i))),r=2*Math.asin(s),a=t>=0?r:-r;return lt(o,e,a)}function jn(o,e,t){const i=ze(o,e),n=Math.abs(t);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||!u.AcGeTol.great(u.TAU-n,0))return;const s=Math.sin(n/2);if(u.AcGeTol.equalToZero(s))return;const r=i/(2*s),a=r*r-i*i/4;if(u.AcGeTol.less(a,0))return;const c=Math.sqrt(Math.max(0,a)),l=(o.x+e.x)/2,h=(o.y+e.y)/2,d=e.x-o.x,m=-(e.y-o.y)/i,f=d/i,w=t>=0,b=w&&n<=Math.PI||!w&&n>Math.PI?1:-1,v={x:l+m*c*b,y:h+f*c*b};return ct(v,o,e,w?1:-1)}function Nn(o,e,t){const i=Math.cos(t),n=Math.sin(t),s=e.x-o.x,r=e.y-o.y,a=-n,c=i,l=2*(s*a+r*c);if(u.AcGeTol.equalToZero(l))return;const h=(s*s+r*r)/l;if(!Number.isFinite(h))return;const d={x:o.x+a*h,y:o.y+c*h},p=o.x-d.x,m=o.y-d.y,f=p*n-m*i;if(u.AcGeTol.equalToZero(f))return;const w=f>=0?1:-1;return ct(d,o,e,w)}function zn(o,e,t){const i=Math.abs(t),n=ze(o,e);if(u.AcGeTol.isNonPositive(i)||u.AcGeTol.isNonPositive(n)||u.AcGeTol.great(n,2*i))return;const s=(o.x+e.x)/2,r=(o.y+e.y)/2,a=e.x-o.x,l=-(e.y-o.y)/n,h=a/n,d=Math.sqrt(Math.max(0,i*i-n*n/4)),p=t>=0?1:-1,m={x:s+l*d*p,y:r+h*d*p},f=t>=0?1:-1;return ct(m,o,e,f)}class Rt extends ${constructor(e,t,i){super(e),this._builder=t,this._arc=Ot(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==no(this._arc)){this.end(),this._arc=Ot(t);return}so(this._arc,t)}}}class ht extends ${constructor(e,t,i){super(e),this._builder=t,this._arc=Ot(i)}get entity(){return this._arc}update(e){const t=this._builder(e);if(t){if(t.normalSign!==no(this._arc)){this.end(),this._arc=Ot(t);return}so(this._arc,t)}}}const uh={"3p":"threePoint","3point":"threePoint",threepoint:"threePoint",startcenter:"startCenter",sc:"startCenter",startcenterend:"startCenterEnd",sce:"startCenterEnd",startcenterangle:"startCenterAngle",sca:"startCenterAngle",startcenterlength:"startCenterLength",startcenterchordlength:"startCenterLength",scl:"startCenterLength",startend:"startEnd",se:"startEnd",startendangle:"startEndAngle",sea:"startEndAngle",startenddirection:"startEndDirection",sed:"startEndDirection",startendradius:"startEndRadius",ser:"startEndRadius",center:"centerStart",c:"centerStart",centerstart:"centerStart",cs:"centerStart",centerstartend:"centerStartEnd",cse:"centerStartEnd",centerstartangle:"centerStartAngle",csa:"centerStartAngle",centerstartlength:"centerStartLength",centerstartchordlength:"centerStartLength",csl:"centerStartLength"};class ao extends j{constructor(){super(),this.mode=R.Write}async execute(e){A.instance.editor.resetInputToggles();const t=this.consumeEntryMode();if(t!=="default"){await this.executeEntryMode(e,t);return}const i=new D(g.t("jig.arc.startPointOrCenter"));this.addKeyword(i,"center");const n=await A.instance.editor.getPoint(i);if(n.status===S.Keyword){n.stringResult==="Center"&&await this.runCenterStartFlow(e);return}n.status===S.OK&&await this.runStartFlow(e,n.value)}async executeEntryMode(e,t){switch(t){case"threePoint":await this.runExactThreePointFlow(e);return;case"startCenter":await this.runStartCenterFlowFromEntry(e);return;case"startCenterEnd":await this.runExactStartCenterFlow(e,"end");return;case"startCenterAngle":await this.runExactStartCenterFlow(e,"angle");return;case"startCenterLength":await this.runExactStartCenterFlow(e,"chordLength");return;case"startEnd":await this.runStartEndFlowFromEntry(e);return;case"startEndAngle":await this.runExactStartEndFlow(e,"angle");return;case"startEndDirection":await this.runExactStartEndFlow(e,"direction");return;case"startEndRadius":await this.runExactStartEndFlow(e,"radius");return;case"centerStart":await this.runCenterStartFlow(e);return;case"centerStartEnd":await this.runExactCenterStartFlow(e,"end");return;case"centerStartAngle":await this.runExactCenterStartFlow(e,"angle");return;case"centerStartLength":await this.runExactCenterStartFlow(e,"chordLength");return}}consumeEntryMode(){const e=A.instance.editor.peekScriptInput();if(e==null)return"default";const t=e.trim().toLowerCase().replace(/[^a-z0-9]+/g,""),i=uh[t];return i?(A.instance.editor.consumeScriptInput(),i):"default"}addKeyword(e,t){e.keywords.add(g.t(`jig.arc.keywords.${t}.display`),g.t(`jig.arc.keywords.${t}.global`),g.t(`jig.arc.keywords.${t}.local`))}appendArc(e,t){e.doc.database.tables.blockTable.modelSpace.appendEntity(Ot(t))}warnInvalidGeometry(e){ee.emit("message",{message:g.t(`jig.arc.invalid.${e}`),type:"warning"})}async promptStartPoint(){const e=new D(g.t("jig.arc.startPoint")),t=await A.instance.editor.getPoint(e);return t.status===S.OK?t.value:void 0}async promptCenterPoint(e){const t=new D(g.t("jig.arc.centerPoint"));e&&(t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e));const i=await A.instance.editor.getPoint(t);return i.status===S.OK?i.value:void 0}async promptEndPoint(e){const t=new D(g.t("jig.arc.endPoint"));e&&(t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e));const i=await A.instance.editor.getPoint(t);return i.status===S.OK?i.value:void 0}async promptSecondPoint(e){const t=new D(g.t("jig.arc.secondPoint"));t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e);const i=await A.instance.editor.getPoint(t);return i.status===S.OK?i.value:void 0}async runExactThreePointFlow(e){const t=await this.promptStartPoint();if(!t)return;const i=await this.promptSecondPoint(t);i&&await this.finishThreePointArc(e,t,i)}async runStartCenterFlowFromEntry(e){const t=await this.promptStartPoint();t&&await this.runStartCenterFlow(e,t)}async runExactStartCenterFlow(e,t){const i=await this.promptStartPoint();if(!i)return;const n=await this.promptCenterPoint(i);if(!n)return;if(t==="end"){await this.finishExactCenterStartEnd(e,n,i);return}if(t==="angle"){const l=new ve(g.t("jig.arc.includedAngle"));l.allowNegative=!0,l.allowZero=!1,l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(n),l.baseAngle=Rn(n,i),l.jig=new ht(e.view,m=>lt(n,i,this.applyCtrlDirectionValue(this.degToRad(m))),ge(i));const h=await A.instance.editor.getAngle(l),d=h.status===S.OK?h.value:void 0;if(d==null)return;const p=lt(n,i,this.applyCtrlDirectionValue(this.degToRad(d)));p?this.appendArc(e,p):this.warnInvalidGeometry("angle");return}const s=new ue(g.t("jig.arc.chordLength"));s.allowNegative=!0,s.allowZero=!1,s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(i),s.jig=new ht(e.view,l=>Ft(n,i,this.applyCtrlDirectionValue(l)),ge(i));const r=await A.instance.editor.getDistance(s),a=r.status===S.OK?r.value:void 0;if(a==null)return;const c=Ft(n,i,this.applyCtrlDirectionValue(a));c?this.appendArc(e,c):this.warnInvalidGeometry("chordLength")}async runExactCenterStartFlow(e,t){const i=await this.promptCenterPoint();if(!i)return;const n=await this.promptStartPointFromCenter(i);if(!n)return;if(t==="end"){await this.finishExactCenterStartEnd(e,i,n);return}if(t==="angle"){const l=new ve(g.t("jig.arc.includedAngle"));l.allowNegative=!0,l.allowZero=!1,l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(i),l.baseAngle=Rn(i,n),l.jig=new ht(e.view,m=>lt(i,n,this.applyCtrlDirectionValue(this.degToRad(m))),ge(n));const h=await A.instance.editor.getAngle(l),d=h.status===S.OK?h.value:void 0;if(d==null)return;const p=lt(i,n,this.applyCtrlDirectionValue(this.degToRad(d)));p?this.appendArc(e,p):this.warnInvalidGeometry("angle");return}const s=new ue(g.t("jig.arc.chordLength"));s.allowNegative=!0,s.allowZero=!1,s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(n),s.jig=new ht(e.view,l=>Ft(i,n,this.applyCtrlDirectionValue(l)),ge(n));const r=await A.instance.editor.getDistance(s),a=r.status===S.OK?r.value:void 0;if(a==null)return;const c=Ft(i,n,this.applyCtrlDirectionValue(a));c?this.appendArc(e,c):this.warnInvalidGeometry("chordLength")}async runExactStartEndFlow(e,t){const i=await this.promptStartPoint();if(!i)return;const n=await this.promptEndPoint(i);if(!n)return;if(t==="angle"){const l=new ve(g.t("jig.arc.includedAngle"));l.allowNegative=!0,l.allowZero=!1,l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(i),l.baseAngle=Rn(i,n),l.jig=new ht(e.view,m=>jn(i,n,this.applyCtrlDirectionValue(this.degToRad(m))),ge(i));const h=await A.instance.editor.getAngle(l),d=h.status===S.OK?h.value:void 0;if(d==null)return;const p=jn(i,n,this.applyCtrlDirectionValue(this.degToRad(d)));p?this.appendArc(e,p):this.warnInvalidGeometry("angle");return}if(t==="direction"){const l=new D(g.t("jig.arc.tangentDirection"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=new u.AcGePoint3d(i),l.jig=new Rt(e.view,f=>Nn(i,n,Math.atan2(f.y-i.y,f.x-i.x)),ge(i));const h=await A.instance.editor.getPoint(l),d=h.status===S.OK?h.value:void 0;if(!d)return;const p=Math.atan2(d.y-i.y,d.x-i.x),m=Nn(i,n,p);m?this.appendArc(e,m):this.warnInvalidGeometry("direction");return}const s=new ue(g.t("jig.arc.radius"));s.allowNegative=!0,s.allowZero=!1,s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(i),s.jig=new ht(e.view,l=>zn(i,n,this.applyCtrlDirectionValue(l)),ge(i));const r=await A.instance.editor.getDistance(s),a=r.status===S.OK?r.value:void 0;if(a==null)return;const c=zn(i,n,this.applyCtrlDirectionValue(a));c?this.appendArc(e,c):this.warnInvalidGeometry("radius")}async runStartEndFlowFromEntry(e){const t=await this.promptStartPoint();t&&await this.runStartEndFlow(e,t)}async promptStartPointFromCenter(e){const t=new D(g.t("jig.arc.startPoint"));t.useBasePoint=!0,t.useDashedLine=!0,t.basePoint=new u.AcGePoint3d(e);const i=await A.instance.editor.getPoint(t);return i.status===S.OK?i.value:void 0}async finishExactCenterStartEnd(e,t,i){const n=new D(g.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(i),n.jig=new Rt(e.view,a=>Ni(t,i,a,this.applyCtrlDirectionSign(1)),ge(i));const s=await A.instance.editor.getPoint(n);if(s.status!==S.OK)return;const r=Ni(t,i,s.value,this.applyCtrlDirectionSign(1));r?this.appendArc(e,r):this.warnInvalidGeometry("center")}getArcDirectionFactor(){return A.instance.editor.getInputToggles().ctrlArcFlip?-1:1}applyCtrlDirectionSign(e){return e*this.getArcDirectionFactor()}applyCtrlDirectionValue(e){return e*this.getArcDirectionFactor()}isCtrlDirectionFlipped(){return A.instance.editor.getInputToggles().ctrlArcFlip}async runStartFlow(e,t){const i=new D(g.t("jig.arc.secondPointOrOptions"));this.addKeyword(i,"center"),this.addKeyword(i,"end"),i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await A.instance.editor.getPoint(i);if(n.status===S.OK){await this.finishThreePointArc(e,t,n.value);return}if(n.status===S.Keyword){if(n.stringResult==="Center"){await this.runStartCenterFlow(e,t);return}n.stringResult==="End"&&await this.runStartEndFlow(e,t)}}async finishThreePointArc(e,t,i){const n=new D(g.t("jig.arc.endPoint"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t),n.jig=new Rt(e.view,a=>oo(t,i,a,this.isCtrlDirectionFlipped()),ge(t));const s=await A.instance.editor.getPoint(n);if(s.status!==S.OK)return;const r=oo(t,i,s.value,this.isCtrlDirectionFlipped());r?this.appendArc(e,r):this.warnInvalidGeometry("threePoint")}async runCenterStartFlow(e){const t=new D(g.t("jig.arc.centerPoint")),i=await A.instance.editor.getPoint(t);if(i.status!==S.OK)return;const n=i.value,s=new D(g.t("jig.arc.startPoint"));s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(n);const r=await A.instance.editor.getPoint(s);r.status===S.OK&&await this.finishCenterStartFlow(e,n,r.value)}async runStartCenterFlow(e,t){const i=new D(g.t("jig.arc.centerPoint"));i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await A.instance.editor.getPoint(i);n.status===S.OK&&await this.finishCenterStartFlow(e,n.value,t)}async finishCenterStartFlow(e,t,i){const n=new D(g.t("jig.arc.endPointOrOptions"));this.addKeyword(n,"angle"),this.addKeyword(n,"chordLength"),n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(i),n.jig=new Rt(e.view,r=>Ni(t,i,r,this.applyCtrlDirectionSign(1)),ge(i));const s=await A.instance.editor.getPoint(n);if(s.status===S.OK){const r=Ni(t,i,s.value,this.applyCtrlDirectionSign(1));r?this.appendArc(e,r):this.warnInvalidGeometry("center");return}if(s.status===S.Keyword){if(s.stringResult==="Angle"){const r=new q(g.t("jig.arc.includedAngle"));r.allowZero=!1,r.allowNegative=!0;const a=await A.instance.editor.getDouble(r);if(a.status!==S.OK)return;const c=lt(t,i,this.applyCtrlDirectionValue(this.degToRad(a.value)));c?this.appendArc(e,c):this.warnInvalidGeometry("angle");return}if(s.stringResult==="ChordLength"){const r=new ue(g.t("jig.arc.chordLength"));r.allowZero=!1,r.allowNegative=!0,r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new u.AcGePoint3d(i);const a=await A.instance.editor.getDistance(r);if(a.status!==S.OK)return;const c=Ft(t,i,this.applyCtrlDirectionValue(a.value));c?this.appendArc(e,c):this.warnInvalidGeometry("chordLength")}}}async runStartEndFlow(e,t){const i=new D(g.t("jig.arc.endPoint"));i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t);const n=await A.instance.editor.getPoint(i);if(n.status!==S.OK)return;const s=n.value,r=new D(g.t("jig.arc.centerPointOrOptions"));this.addKeyword(r,"angle"),this.addKeyword(r,"direction"),this.addKeyword(r,"radius"),r.useBasePoint=!0,r.useDashedLine=!0,r.basePoint=new u.AcGePoint3d(t),r.jig=new Rt(e.view,c=>ct(c,t,s,this.applyCtrlDirectionSign(1)),ge(t));const a=await A.instance.editor.getPoint(r);if(a.status===S.OK){const c=ct(a.value,t,s,this.applyCtrlDirectionSign(1));c?this.appendArc(e,c):this.warnInvalidGeometry("center");return}if(a.status===S.Keyword){if(a.stringResult==="Angle"){const c=new q(g.t("jig.arc.includedAngle"));c.allowZero=!1,c.allowNegative=!0;const l=await A.instance.editor.getDouble(c);if(l.status!==S.OK)return;const h=jn(t,s,this.applyCtrlDirectionValue(this.degToRad(l.value)));h?this.appendArc(e,h):this.warnInvalidGeometry("angle");return}if(a.stringResult==="Direction"){const c=new D(g.t("jig.arc.tangentDirection"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(t);const l=await A.instance.editor.getPoint(c);if(l.status!==S.OK)return;const h=l.value,d=Math.atan2(h.y-t.y,h.x-t.x),p=Nn(t,s,d);p?this.appendArc(e,p):this.warnInvalidGeometry("direction");return}if(a.stringResult==="Radius"){const c=new ue(g.t("jig.arc.radius"));c.allowZero=!1,c.allowNegative=!0,c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(t);const l=await A.instance.editor.getDistance(c);if(l.status!==S.OK)return;const h=zn(t,s,this.applyCtrlDirectionValue(l.value));h?this.appendArc(e,h):this.warnInvalidGeometry("radius")}}}degToRad(e){return e*Math.PI/180}}function co(o){return{center:{x:o.x,y:o.y,z:0},radius:1e-6}}function Vn(o,e){o.keywords.add(g.t(`jig.circle.keywords.${e}.display`),g.t(`jig.circle.keywords.${e}.global`),g.t(`jig.circle.keywords.${e}.local`))}function dh(o,e){o.center=e.center,o.radius=e.radius}function lo(o,e){if(!(!Number.isFinite(e)||u.AcGeTol.isNonPositive(e)))return{center:{x:o.x,y:o.y,z:0},radius:e}}function ho(o,e){const t=e.x-o.x,i=e.y-o.y,n=Math.hypot(t,i);if(!u.AcGeTol.isNonPositive(n))return{center:{x:(o.x+e.x)/2,y:(o.y+e.y)/2,z:0},radius:n/2}}function uo(o,e,t){const i=o.x,n=o.y,s=e.x,r=e.y,a=t.x,c=t.y,l=2*(i*(r-c)+s*(c-n)+a*(n-r));if(u.AcGeTol.equalToZero(l))return;const h=((i*i+n*n)*(r-c)+(s*s+r*r)*(c-n)+(a*a+c*c)*(n-r))/l,d=((i*i+n*n)*(a-s)+(s*s+r*r)*(i-a)+(a*a+c*c)*(s-i))/l,p=Math.hypot(h-i,d-n);if(!(!Number.isFinite(p)||u.AcGeTol.isNonPositive(p)))return{center:{x:h,y:d,z:0},radius:p}}class zi extends ${constructor(e,t){super(e),this._circle=new u.AcDbCircle(t,0)}get entity(){return this._circle}update(e){this._circle.radius=e}}class go extends ${constructor(e,t,i){super(e),this._circle=new u.AcDbCircle(i.center,i.radius),this._builder=t}get entity(){return this._circle}update(e){const t=this._builder(e);t&&dh(this._circle,t)}}class po extends j{constructor(){super(),this.mode=R.Write}async execute(e){let t;class i{constructor(d,p){this.cmd=d,this.machine=p}buildPrompt(){const d=new D(g.t("jig.circle.centerOrOptions"));return Vn(d,"threeP"),Vn(d,"twoP"),d}async handleResult(d){if(d.status===S.OK)return t=await this.cmd.runCenterFlow(e,d.value),"finish";if(d.status!==S.Keyword)return"finish";const p=d.stringResult??"";return p==="3P"?(this.machine.setState(new r(this.cmd,this.machine)),"continue"):p==="2P"?(this.machine.setState(new n(this.cmd,this.machine)),"continue"):"finish"}}class n{constructor(d,p){this.cmd=d,this.machine=p}buildPrompt(){return new D(g.t("jig.circle.twoPointFirst"))}async handleResult(d){return d.status!==S.OK?"finish":(this.machine.setState(new s(this.cmd,d.value)),"continue")}}class s{constructor(d,p){this.cmd=d,this.firstPoint=p}buildPrompt(){const d=new D(g.t("jig.circle.twoPointSecond"));return d.useBasePoint=!0,d.useDashedLine=!0,d.basePoint=new u.AcGePoint3d(this.firstPoint),d.jig=new go(e.view,p=>ho(this.firstPoint,p),co(this.firstPoint)),d}async handleResult(d){return d.status===S.OK&&(t=this.cmd.createFromTwoPoints(this.firstPoint,d.value)),"finish"}}class r{constructor(d,p){this.cmd=d,this.machine=p}buildPrompt(){return new D(g.t("jig.circle.threePointFirst"))}async handleResult(d){return d.status!==S.OK?"finish":(this.machine.setState(new a(this.cmd,this.machine,d.value)),"continue")}}class a{constructor(d,p,m){this.cmd=d,this.machine=p,this.firstPoint=m}buildPrompt(){const d=new D(g.t("jig.circle.threePointSecond"));return d.useBasePoint=!0,d.useDashedLine=!0,d.basePoint=new u.AcGePoint3d(this.firstPoint),d}async handleResult(d){return d.status!==S.OK?"finish":(this.machine.setState(new c(this.cmd,this.firstPoint,d.value)),"continue")}}class c{constructor(d,p,m){this.cmd=d,this.firstPoint=p,this.secondPoint=m}buildPrompt(){const d=new D(g.t("jig.circle.threePointThird"));return d.useBasePoint=!0,d.useDashedLine=!0,d.basePoint=new u.AcGePoint3d(this.secondPoint),d.jig=new go(e.view,p=>uo(this.firstPoint,this.secondPoint,p),co(this.firstPoint)),d}async handleResult(d){return d.status===S.OK&&(t=this.cmd.createFromThreePoints(this.firstPoint,this.secondPoint,d.value)),"finish"}}const l=new Te;l.setState(new i(this,l)),await l.run(h=>A.instance.editor.getPoint(h)),t&&e.doc.database.tables.blockTable.modelSpace.appendEntity(new u.AcDbCircle(t.center,t.radius))}async runCenterFlow(e,t){const i=new ue(g.t("jig.circle.radiusOrDiameter"));Vn(i,"diameter"),i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t),i.jig=new zi(e.view,t);const n=await A.instance.editor.getDistance(i);if(n.status===S.OK)return lo(t,n.value??0);if(n.status===S.Keyword&&n.stringResult==="Diameter")return await this.promptDiameterCircle(e,t)}async promptDiameterCircle(e,t){const i=new ue(g.t("jig.circle.diameter"));i.allowZero=!1,i.useBasePoint=!0,i.useDashedLine=!0,i.basePoint=new u.AcGePoint3d(t),i.jig=new zi(e.view,t);const n=await A.instance.editor.getDistance(i);if(n.status!==S.OK)return;const s=(n.value??0)/2;return lo(t,s)}createFromTwoPoints(e,t){return ho(e,t)}createFromThreePoints(e,t,i){return uo(e,t,i)}}class mo extends ${constructor(e,t,i,n){super(e),this._dimBlockName="*UDIM",this._db=t,new u.AcDbDataGenerator(t).createArrowBlock(),this._dim=new u.AcDbAlignedDimension(i,n,i),this._dim.rotation=0}get entity(){return this._dim}update(e){this._dim.dimLinePoint=e,this._dim.rotation=this.calculateAngle(this._dim.xLine1Point,this._dim.xLine2Point),this._dim.dimensionText=this._dim.xLine1Point.distanceTo(this._dim.xLine2Point).toFixed(3);const t=this._dimBlockName;this._db.tables.blockTable.remove(t),this._db.tables.blockTable.add(this._dim.createDimBlock(t)),this._dim.dimBlockId=t}end(){super.end(),this._db.tables.blockTable.remove(this._dimBlockName)}calculateAngle(e,t){const i=t.x-e.x,n=t.y-e.y;return Math.atan2(n,i)}}class fo extends j{constructor(){super(),this.mode=R.Review}async execute(e){const t=new D(g.t("jig.dimlinear.xLine1Point")),i=await A.instance.editor.getPoint(t);if(i.status!==S.OK)return;const n=i.value,s=new D(g.t("jig.dimlinear.xLine2Point"));s.useBasePoint=!0;const r=await A.instance.editor.getPoint(s);if(r.status!==S.OK)return;const a=r.value,c=new D(g.t("jig.dimlinear.dimLinePoint"));c.jig=new mo(e.view,e.doc.database,n,a);const l=await A.instance.editor.getPoint(c);if(l.status!==S.OK)return;const h=l.value,d=e.doc.database,p=new u.AcDbAlignedDimension(n,a,h),m=this.getAvaiableDimBlockName(d);d.tables.blockTable.add(p.createDimBlock(m)),p.dimBlockId=m,d.tables.blockTable.modelSpace.appendEntity(p)}getAvaiableDimBlockName(e){const t=e.tables.blockTable.newIterator();let i=0;for(const n of t){const s=n.name;if(!s.startsWith("*D"))continue;const r=Number(s.slice(2));Number.isInteger(r)&&r>i&&(i=r)}return`*D${i+1}`}}class Vi extends ${constructor(e,t){super(e),this._line=new u.AcDbLine(t,t)}get entity(){return this._line}update(e){this._line.endPoint=e}}class Ze extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=e.doc.database,i=[],n=[],s=()=>!!Ze._lastEndpoint,r=()=>Ze._lastEndpoint?new u.AcGePoint3d(Ze._lastEndpoint):void 0,a=()=>{const b=l();b&&(Ze._lastEndpoint=new u.AcGePoint3d(b))},c=b=>{i.push(new u.AcGePoint3d(b))},l=()=>i[i.length-1],h=b=>{const v=l();if(!v)return;const C=new u.AcDbLine(new u.AcGePoint3d(v),b);t.tables.blockTable.modelSpace.appendEntity(C),n.push(C),c(b)},d=()=>{var b;n.length<=0||i.length<=1||((b=n.pop())==null||b.erase(),i.pop())},p=()=>{if(i.length<=1)return;const b=i[0],v=l();if(!v)return;b.x===v.x&&b.y===v.y&&b.z===v.z||h(b)},m=new D(s()?g.t("jig.line.firstPointOrContinue"):g.t("jig.line.firstPoint"));s()&&m.keywords.add(g.t("jig.line.keywords.continue.display"),g.t("jig.line.keywords.continue.global"),g.t("jig.line.keywords.continue.local"));const f=await A.instance.editor.getPoint(m);if(f.status===S.OK)c(f.value);else if(f.status===S.Keyword&&f.stringResult==="Continue"&&s())c(r());else return;class w{buildPrompt(){const v=new D(g.t("jig.line.nextPointWithOptions"));v.keywords.add(g.t("jig.line.keywords.undo.display"),g.t("jig.line.keywords.undo.global"),g.t("jig.line.keywords.undo.local")),i.length>1&&v.keywords.add(g.t("jig.line.keywords.close.display"),g.t("jig.line.keywords.close.global"),g.t("jig.line.keywords.close.local"));const C=l();return C&&(v.useDashedLine=!0,v.useBasePoint=!0,v.basePoint=new u.AcGePoint3d(C),v.jig=new Vi(e.view,C)),v}async handleResult(v){if(v.status===S.OK)return h(v.value),"continue";if(v.status===S.Keyword){const C=v.stringResult??"";return C==="Undo"?(d(),"continue"):C==="Close"&&i.length>1?(p(),"finish"):"continue"}return"finish"}}const x=new Te;x.setState(new w),await x.run(b=>A.instance.editor.getPoint(b)),a()}}const Gn={x:0,y:0,z:1};function Gi(o,e){return Math.hypot(e.x-o.x,e.y-o.y)}function gh(o,e){return{x:(o.x+e.x)/2,y:(o.y+e.y)/2,z:0}}function yo(o,e){const t=Math.hypot(o,e);if(!(!Number.isFinite(t)||u.AcGeTol.isNonPositive(t)))return{x:o/t,y:e/t,z:0}}function ph(o){return{x:-o.y,y:o.x,z:0}}function Kn(o){return o*Math.PI/180}function mh(o){return o*180/Math.PI}function fh(o){return mh(Math.atan2(o.y,o.x))}function Ki(o,e,t){const i=Kn(o);return Math.atan2(e*Math.sin(i),t*Math.cos(i))}function yh(o,e){return yo(e.x-o.x,e.y-o.y)}function Ui(o,e,t,i,n=0,s=u.TAU){if(!(!Number.isFinite(t)||!Number.isFinite(i)||u.AcGeTol.isNonPositive(t)||u.AcGeTol.isNonPositive(i)))return t>=i?{center:{x:o.x,y:o.y,z:0},majorAxis:e,majorRadius:t,minorRadius:i,startAngle:n,endAngle:s}:{center:{x:o.x,y:o.y,z:0},majorAxis:ph(e),majorRadius:i,minorRadius:t,startAngle:n,endAngle:s}}function wo(o){return new u.AcDbEllipse(o,Gn,{x:1,y:0,z:0},1e-6,1e-6,0,u.TAU)}function bo(o,e){o.center=e.center,o.normal=Gn,o.majorAxisRadius=e.majorRadius,o.minorAxisRadius=e.minorRadius,o.startAngle=e.startAngle,o.endAngle=e.endAngle;const t=o;t._geo&&(t._geo.majorAxis=e.majorAxis)}class wh extends ${constructor(e,t,i){super(e),this._builder=t,this._ellipse=wo(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&bo(this._ellipse,t)}}class Un extends ${constructor(e,t,i){super(e),this._builder=t,this._ellipse=wo(i)}get entity(){return this._ellipse}update(e){const t=this._builder(e);t&&bo(this._ellipse,t)}}class vo extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=new D(g.t("jig.ellipse.axisEndpointOrOptions"));this.addKeyword(t,"arc"),this.addKeyword(t,"center");const i=await A.instance.editor.getPoint(t);if(i.status===S.Keyword){const n=i.stringResult??"";n==="Center"?await this.runCenterFlow(e,!1):n==="Arc"&&await this.runArcEntryFlow(e);return}i.status===S.OK&&await this.runAxisEndFlow(e,i.value,!1)}addKeyword(e,t){e.keywords.add(g.t(`jig.ellipse.keywords.${t}.display`),g.t(`jig.ellipse.keywords.${t}.global`),g.t(`jig.ellipse.keywords.${t}.local`))}appendEllipse(e,t){const i=new u.AcDbEllipse(t.center,Gn,t.majorAxis,t.majorRadius,t.minorRadius,t.startAngle,t.endAngle);e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){ee.emit("message",{message:g.t(`jig.ellipse.invalid.${e}`),type:"warning"})}async runArcEntryFlow(e){const t=new D(g.t("jig.ellipse.arcAxisEndpointOrCenter"));this.addKeyword(t,"center");const i=await A.instance.editor.getPoint(t);if(i.status===S.Keyword){i.stringResult==="Center"&&await this.runCenterFlow(e,!0);return}i.status===S.OK&&await this.runAxisEndFlow(e,i.value,!0)}async runCenterFlow(e,t){const i=new D(g.t("jig.ellipse.center")),n=await A.instance.editor.getPoint(i);if(n.status!==S.OK)return;const s=n.value,r=new D(g.t("jig.ellipse.firstAxisEndpoint"));r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(s),r.jig=new Vi(e.view,s);const a=await A.instance.editor.getPoint(r);if(a.status!==S.OK)return;const c=yh(s,a.value);if(!c){this.warnInvalidInput("axis");return}const l=Gi(s,a.value),h=await this.promptOtherAxis(e,s,c,l,t);h&&this.appendEllipse(e,h)}async runAxisEndFlow(e,t,i){const n=new D(g.t("jig.ellipse.secondAxisEndpoint"));n.useDashedLine=!0,n.useBasePoint=!0,n.basePoint=new u.AcGePoint3d(t),n.jig=new Vi(e.view,t);const s=await A.instance.editor.getPoint(n);if(s.status!==S.OK)return;const r=s.value,a=r.x-t.x,c=r.y-t.y,l=yo(a,c);if(!l){this.warnInvalidInput("axis");return}const h=gh(t,r),d=Gi(t,r)/2,p=await this.promptOtherAxis(e,h,l,d,i);p&&this.appendEllipse(e,p)}async promptOtherAxis(e,t,i,n,s){for(;;){const r=new D(g.t("jig.ellipse.otherAxisOrRotation"));this.addKeyword(r,"rotation"),r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(t),r.jig=new wh(e.view,h=>{const d=Gi(t,h);return Ui(t,i,n,d)},t);const a=await A.instance.editor.getPoint(r);if(a.status===S.Keyword){if(a.stringResult!=="Rotation")return;const h=new q(g.t("jig.ellipse.rotationAngle"));h.allowNegative=!1,h.allowZero=!0,h.jig=new Un(e.view,f=>{const w=n*Math.abs(Math.cos(Kn(f)));return Ui(t,i,n,w)},t);const d=await A.instance.editor.getDouble(h);if(d.status!==S.OK)return;const p=n*Math.abs(Math.cos(Kn(d.value??0))),m=Ui(t,i,n,p);if(!m){this.warnInvalidInput("rotation");continue}return s?await this.promptArcAngles(e,m):m}if(a.status!==S.OK)return;const c=Gi(t,a.value),l=Ui(t,i,n,c);if(!l){this.warnInvalidInput("otherAxis");continue}return s?await this.promptArcAngles(e,l):l}}async promptArcAngles(e,t){const i=fh(t.majorAxis),n=new ve(g.t("jig.ellipse.arcStartAngle"));n.allowNegative=!0,n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t.center),n.baseAngle=i,n.jig=new Un(e.view,l=>({...t,startAngle:Ki(l,t.majorRadius,t.minorRadius),endAngle:u.TAU}),t.center);const s=await A.instance.editor.getAngle(n);if(s.status!==S.OK)return;const r=Ki(s.value??0,t.majorRadius,t.minorRadius),a=new ve(g.t("jig.ellipse.arcEndAngle"));a.allowNegative=!0,a.useBasePoint=!0,a.useDashedLine=!0,a.basePoint=new u.AcGePoint3d(t.center),a.baseAngle=i,a.jig=new Un(e.view,l=>({...t,startAngle:r,endAngle:Ki(l,t.majorRadius,t.minorRadius)}),t.center);const c=await A.instance.editor.getAngle(a);if(c.status===S.OK)return{...t,startAngle:r,endAngle:Ki(c.value??0,t.majorRadius,t.minorRadius)}}}const on=class on extends j{constructor(){super(),this.mode=R.Write}get settings(){return on._lastSettings}normalizeSysVarNumber(e,t){const i=Number(e);return Number.isFinite(i)?i:t}normalizePositiveSysVarNumber(e,t){const i=this.normalizeSysVarNumber(e,t);return i>0?i:t}sysVarRadiansToDegrees(e){return Math.round(e*180/Math.PI*1e6)/1e6}getSysVar(e,t,i){try{return e.getVar(t,i)}catch{return}}getDatabaseSysVarSettings(e){const t=this.settings;if(!(e instanceof u.AcDbDatabase))return t;try{const i=u.AcDbSysVarManager.instance(),n=this.getSysVar(i,u.AcDbSystemVariables.HPASSOC,e);return{...t,patternName:this.normalizePatternName(this.getSysVar(i,u.AcDbSystemVariables.HPNAME,e)??t.patternName),patternScale:this.normalizePositiveSysVarNumber(this.getSysVar(i,u.AcDbSystemVariables.HPSCALE,e),t.patternScale),patternAngleDeg:this.sysVarRadiansToDegrees(this.normalizeSysVarNumber(this.getSysVar(i,u.AcDbSystemVariables.HPANG,e),t.patternAngleDeg*Math.PI/180)),associative:n==null?t.associative:Number(n)!==0}}catch{return t}}getActiveSettings(){var e;return this.getDatabaseSysVarSettings((e=A.instance.curDocument)==null?void 0:e.database)}setActiveSysVar(e,t){var n;const i=(n=A.instance.curDocument)==null?void 0:n.database;i&&u.AcDbSysVarManager.instance().setVar(e,t,i)}normalizePatternName(e){const t=e.trim().toUpperCase();return t.length>0?t:u.HATCH_PATTERN_SOLID}styleToKeyword(e){switch(e){case u.AcDbHatchStyle.Outer:return"Outer";case u.AcDbHatchStyle.Ignore:return"Ignore";case u.AcDbHatchStyle.Normal:default:return"Normal"}}keywordToStyle(e){switch(e){case"Outer":return u.AcDbHatchStyle.Outer;case"Ignore":return u.AcDbHatchStyle.Ignore;case"Normal":default:return u.AcDbHatchStyle.Normal}}buildEdgesFromPolyline(e){var s;if(!e.closed||e.numberOfVertices<2)return[];const t=(s=e._geo)==null?void 0:s.vertices,i=t&&t.length>1?t.map(r=>({x:r.x,y:r.y,bulge:r.bulge})):Array.from({length:e.numberOfVertices},(r,a)=>{const c=e.getPoint2dAt(a);return{x:c.x,y:c.y,bulge:0}});if(i.length<2)return[];const n=[];for(let r=0;r<i.length;r++){const a=i[r],c=i[(r+1)%i.length],l=a.bulge??0;Math.abs(l)>1e-12?n.push(new u.AcGeCircArc2d(a,c,l)):n.push(new u.AcGeLine2d(a,c))}return n}buildEdgesFromEntity(e){if(e instanceof u.AcDbPolyline)return this.buildEdgesFromPolyline(e);if(e instanceof u.AcDbCircle){const t=e.center;return[new u.AcGeCircArc2d({x:t.x,y:t.y},e.radius,0,Math.PI*2,!1)]}if(e instanceof u.AcDbArc){if(!e.closed)return[];const t=e.center;return[new u.AcGeCircArc2d({x:t.x,y:t.y},e.radius,e.startAngle,e.endAngle,!1)]}return e instanceof u.AcDbLine?[new u.AcGeLine2d(e.startPoint,e.endPoint)]:[]}collectLoopsFromIds(e,t){const i=e.doc.database.tables.blockTable.modelSpace,n=[];return t.forEach(s=>{const r=i.getIdAt(s);r&&n.push(...this.buildEdgesFromEntity(r))}),this.buildLoopsFromEdges(n)}collectLoopsFromAllBoundaries(e){const t=e.doc.database.tables.blockTable.modelSpace,i=[];for(const n of t.newIterator())i.push(...this.buildEdgesFromEntity(n));return this.buildLoopsFromEdges(i)}buildLoopsFromEdges(e){if(e.length===0)return[];const t=[1e-6,1e-5,1e-4,.001];let i=[];for(const n of t){const s=u.AcGeLoop2d.buildFromEdges(e,n).filter(r=>r.closed&&r.numberOfEdges>0);s.length>i.length&&(i=s)}return i}signedArea(e){if(e.length<3)return 0;let t=0;for(let i=0,n=e.length-1;i<e.length;n=i++){const s=e[n],r=e[i];t+=s.x*r.y-r.x*s.y}return t*.5}isPointOnSegment(e,t,i,n,s,r,a=1e-8){const c=s-i,l=r-n,h=e-i,d=t-n;if(Math.abs(c*d-l*h)>a)return!1;const m=h*c+d*l;if(m<-a)return!1;const f=c*c+l*l;return!(m-f>a)}isPointInPolygon(e,t){if(t.length<3)return!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[s],a=t[n];if(this.isPointOnSegment(e.x,e.y,r.x,r.y,a.x,a.y))return!0}let i=!1;for(let n=0,s=t.length-1;n<t.length;s=n++){const r=t[n].x,a=t[n].y,c=t[s].x,l=t[s].y;a>e.y!=l>e.y&&e.x<(c-r)*(e.y-a)/(l-a+Number.EPSILON)+r&&(i=!i)}return i}buildLoopInfos(e){const t=[];e.forEach(i=>{const n=i.getPoints(128).map(s=>({x:s.x,y:s.y}));n.length<3||t.push({loop:i,points:n,area:Math.abs(this.signedArea(n)),parent:null,children:[]})});for(let i=0;i<t.length;i++){const n=t[i].points[0];let s=null,r=Number.POSITIVE_INFINITY;for(let a=0;a<t.length;a++)i!==a&&(t[a].area<=t[i].area||this.isPointInPolygon(n,t[a].points)&&t[a].area<r&&(r=t[a].area,s=a));t[i].parent=s,s!=null&&t[s].children.push(i)}return t}resolveLoopsForPickPoint(e,t){const i=this.buildLoopInfos(t);if(!i.length)return[];const n=i.map((a,c)=>this.isPointInPolygon(e,a.points)?c:-1).filter(a=>a>=0);if(!n.length)return[];n.sort((a,c)=>i[a].area-i[c].area);const s=n[0],r=new Set([s]);return this.settings.style!==u.AcDbHatchStyle.Ignore&&i[s].children.forEach(a=>r.add(a)),[...r].map(a=>i[a].loop)}appendHatch(e,t){if(!t.length)return!1;const i=new u.AcDbHatch;e.doc.database instanceof u.AcDbDatabase&&(i.database=e.doc.database);const n=this.getDatabaseSysVarSettings(e.doc.database),s=this.normalizePatternName(n.patternName),r=s===u.HATCH_PATTERN_SOLID;return i.patternName=s,i.patternType=u.AcDbHatchPatternType.Predefined,i.patternScale=n.patternScale,i.patternAngle=n.patternAngleDeg*Math.PI/180,i.hatchStyle=n.style,i.isSolidFill=r,this.configureHatch(i),t.forEach(a=>i.add(a)),e.doc.database.tables.blockTable.modelSpace.appendEntity(i),!0}configureHatch(e){}async promptPatternName(){const e=new le(g.t("jig.hatch.patternName"));e.allowEmpty=!1;const t=this.getActiveSettings();e.defaultValue=t.patternName,e.useDefaultValue=!0;const i=await A.instance.editor.getString(e);if(i.status!==S.OK)return;const n=this.normalizePatternName(i.stringResult??e.defaultValue);this.settings.patternName=n,this.setActiveSysVar(u.AcDbSystemVariables.HPNAME,n)}async promptPatternScale(){const e=new q(g.t("jig.hatch.scale"));e.allowNone=!0,e.allowNegative=!1,e.allowZero=!1;const t=this.getActiveSettings();e.defaultValue=t.patternScale,e.useDefaultValue=!0;const i=await A.instance.editor.getDouble(e);if(i.status!==S.OK)return;const n=i.value??e.defaultValue;n>0&&(this.settings.patternScale=n,this.setActiveSysVar(u.AcDbSystemVariables.HPSCALE,n))}async promptPatternAngle(){const e=new q(g.t("jig.hatch.angle"));e.allowNone=!0,e.allowNegative=!0,e.allowZero=!0;const t=this.getActiveSettings();e.defaultValue=t.patternAngleDeg,e.useDefaultValue=!0;const i=await A.instance.editor.getDouble(e);if(i.status!==S.OK)return;const n=i.value??e.defaultValue;this.settings.patternAngleDeg=n,this.setActiveSysVar(u.AcDbSystemVariables.HPANG,n*Math.PI/180)}async promptStyle(){const e=this.getActiveSettings(),t=this.styleToKeyword(e.style),i=new X(`${g.t("jig.hatch.style")} <${t}>`);i.allowNone=!0,i.keywords.add(g.t("jig.hatch.keywords.normal.display"),g.t("jig.hatch.keywords.normal.global"),g.t("jig.hatch.keywords.normal.local")),i.keywords.add(g.t("jig.hatch.keywords.outer.display"),g.t("jig.hatch.keywords.outer.global"),g.t("jig.hatch.keywords.outer.local")),i.keywords.add(g.t("jig.hatch.keywords.ignore.display"),g.t("jig.hatch.keywords.ignore.global"),g.t("jig.hatch.keywords.ignore.local"));const n=await A.instance.editor.getKeywords(i);(n.status===S.OK||n.status===S.Keyword)&&n.stringResult&&(this.settings.style=this.keywordToStyle(n.stringResult))}async promptAssociative(){const t=this.getActiveSettings().associative?"Yes":"No",i=new X(`${g.t("jig.hatch.associative")} <${t}>`);i.allowNone=!0,i.keywords.add(g.t("jig.hatch.keywords.yes.display"),g.t("jig.hatch.keywords.yes.global"),g.t("jig.hatch.keywords.yes.local")),i.keywords.add(g.t("jig.hatch.keywords.no.display"),g.t("jig.hatch.keywords.no.global"),g.t("jig.hatch.keywords.no.local"));const n=await A.instance.editor.getKeywords(i);if(n.status===S.OK||n.status===S.Keyword){const s=n.stringResult==="Yes";this.settings.associative=s,this.setActiveSysVar(u.AcDbSystemVariables.HPASSOC,s?1:0)}}async doSelectObjects(e){const t=new Re(g.t("jig.hatch.select")),i=await A.instance.editor.getSelection(t);if(i.status!==S.OK||!i.value)return!1;const n=this.collectLoopsFromIds(e,i.value.ids);return n.length?this.appendHatch(e,n):!1}async doPickPoints(e){const t=this.collectLoopsFromAllBoundaries(e);if(!t.length)return!1;let i=!1;for(;;){const n=new D(g.t("jig.hatch.pickPoint"));n.allowNone=!0;const s=await A.instance.editor.getPoint(n);if(s.status!==S.OK||!s.value)break;const r=this.resolveLoopsForPickPoint(s.value,t);r.length&&this.appendHatch(e,r)&&(i=!0)}return i}async execute(e){let t=!0;for(;t;){const i=new Le(g.t("jig.hatch.prompt"));i.allowNone=!0,i.setRejectMessage(g.t("jig.hatch.invalidBoundary")),i.addAllowedClass("Polyline"),i.addAllowedClass("Circle"),i.addAllowedClass("Arc"),i.addAllowedClass("Line"),i.keywords.add(g.t("jig.hatch.keywords.pick.display"),g.t("jig.hatch.keywords.pick.global"),g.t("jig.hatch.keywords.pick.local")),i.keywords.add(g.t("jig.hatch.keywords.select.display"),g.t("jig.hatch.keywords.select.global"),g.t("jig.hatch.keywords.select.local")),i.keywords.add(g.t("jig.hatch.keywords.pattern.display"),g.t("jig.hatch.keywords.pattern.global"),g.t("jig.hatch.keywords.pattern.local")),i.keywords.add(g.t("jig.hatch.keywords.scale.display"),g.t("jig.hatch.keywords.scale.global"),g.t("jig.hatch.keywords.scale.local")),i.keywords.add(g.t("jig.hatch.keywords.angle.display"),g.t("jig.hatch.keywords.angle.global"),g.t("jig.hatch.keywords.angle.local")),i.keywords.add(g.t("jig.hatch.keywords.style.display"),g.t("jig.hatch.keywords.style.global"),g.t("jig.hatch.keywords.style.local")),i.keywords.add(g.t("jig.hatch.keywords.associative.display"),g.t("jig.hatch.keywords.associative.global"),g.t("jig.hatch.keywords.associative.local"));const n=await A.instance.editor.getEntity(i);if(n.status===S.OK&&n.objectId){const s=this.collectLoopsFromIds(e,[n.objectId]);if(!s.length)continue;this.appendHatch(e,s);continue}if(n.status===S.Keyword){const s=n.stringResult??"";s==="PickPoints"?await this.doPickPoints(e):s==="SelectObjects"?await this.doSelectObjects(e):s==="Pattern"?await this.promptPatternName():s==="Scale"?await this.promptPatternScale():s==="Angle"?await this.promptPatternAngle():s==="HatchStyle"?await this.promptStyle():s==="AssociativeMode"&&await this.promptAssociative();continue}t=!1}}};on._lastSettings={patternName:u.HATCH_PATTERN_SOLID,patternScale:1,patternAngleDeg:0,style:u.AcDbHatchStyle.Normal,associative:!0};let $i=on;class xo extends ${constructor(e,t,i){if(super(e),this._mline=new u.AcDbMLine,this._points=t,this._resolveState=i,t.length>0){const n=this._resolveState();$n(this._mline,t,n.styleName,n.justification,n.scale,!1,n.elementOffsets)}}get entity(){return this._mline}update(e){if(this._points.length<=0)return;const t=[...this._points,new u.AcGePoint3d(e)],i=this._resolveState();$n(this._mline,t,i.styleName,i.justification,i.scale,!1,i.elementOffsets)}}class So extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=e.doc.database;let i=u.AcDbMLineJustification.Zero,n=t.cmlscale??1,s=t.cmlstyle||"STANDARD";const r=[];let a=!1;const c=()=>{const P=t.objects.mlineStyle.getAt(s);return Sh((P==null?void 0:P.elements)??[],i,n)},l=P=>r.push(new u.AcGePoint3d(P)),h=()=>{r.length>1&&r.pop()},d=()=>{if(r.length<=1)return;const P=r[0],L=r[r.length-1];Ch(P,L)||l(P),a=!0},p=async()=>{const P=new X(g.t("jig.mline.justificationPrompt"));P.allowNone=!0,P.keywords.add(g.t("jig.mline.keywords.top.display"),g.t("jig.mline.keywords.top.global"),g.t("jig.mline.keywords.top.local")),P.keywords.add(g.t("jig.mline.keywords.zero.display"),g.t("jig.mline.keywords.zero.global"),g.t("jig.mline.keywords.zero.local")),P.keywords.add(g.t("jig.mline.keywords.bottom.display"),g.t("jig.mline.keywords.bottom.global"),g.t("jig.mline.keywords.bottom.local"));const L=await A.instance.editor.getKeywords(P);if(L.status===S.None)return!0;if(L.status!==S.Keyword)return!1;const M=L.stringResult??"";return M==="Top"?i=u.AcDbMLineJustification.Top:M==="Bottom"?i=u.AcDbMLineJustification.Bottom:i=u.AcDbMLineJustification.Zero,!0},m=async()=>{const P=new q(g.t("jig.mline.scalePrompt"));P.allowNone=!0,P.allowZero=!0,P.allowNegative=!0,P.useDefaultValue=!0,P.defaultValue=n;const L=await A.instance.editor.getDouble(P);return L.status===S.None?!0:L.status!==S.OK?!1:(n=L.value??n,!0)},f=()=>{const P=[...t.objects.mlineStyle.entries()].map(([L])=>L);if(P.length<=0){A.instance.editor.showMessage(g.t("jig.mline.styleListEmpty"),"warning");return}A.instance.editor.showMessage(`${g.t("jig.mline.styleListHeader")} ${P.join(", ")}`,"info")},w=async()=>{for(;;){const P=new le(g.t("jig.mline.stylePrompt"));P.allowEmpty=!1,P.allowSpaces=!1;const L=await A.instance.editor.getString(P);if(L.status!==S.OK)return!1;const M=(L.stringResult??"").trim();if(M){if(M==="?"){f();continue}return s=M,!0}}},x=async P=>P==="Justification"?await p():P==="Scale"?await m():P==="Style"?await w():!0;for(;;){const P=new D(g.t("jig.mline.startPointWithOptions"));P.keywords.add(g.t("jig.mline.keywords.justification.display"),g.t("jig.mline.keywords.justification.global"),g.t("jig.mline.keywords.justification.local")),P.keywords.add(g.t("jig.mline.keywords.scale.display"),g.t("jig.mline.keywords.scale.global"),g.t("jig.mline.keywords.scale.local")),P.keywords.add(g.t("jig.mline.keywords.style.display"),g.t("jig.mline.keywords.style.global"),g.t("jig.mline.keywords.style.local"));const L=await A.instance.editor.getPoint(P);if(L.status===S.OK){l(L.value);break}if(L.status!==S.Keyword||!await x(L.stringResult??""))return}class b{buildPrompt(){const L=new D(g.t("jig.mline.nextPointWithOptions"));return L.keywords.add(g.t("jig.mline.keywords.justification.display"),g.t("jig.mline.keywords.justification.global"),g.t("jig.mline.keywords.justification.local")),L.keywords.add(g.t("jig.mline.keywords.scale.display"),g.t("jig.mline.keywords.scale.global"),g.t("jig.mline.keywords.scale.local")),L.keywords.add(g.t("jig.mline.keywords.style.display"),g.t("jig.mline.keywords.style.global"),g.t("jig.mline.keywords.style.local")),L.keywords.add(g.t("jig.mline.keywords.undo.display"),g.t("jig.mline.keywords.undo.global"),g.t("jig.mline.keywords.undo.local")),r.length>1&&L.keywords.add(g.t("jig.mline.keywords.close.display"),g.t("jig.mline.keywords.close.global"),g.t("jig.mline.keywords.close.local")),L.useDashedLine=!0,L.useBasePoint=!0,L.basePoint=new u.AcGePoint3d(r[r.length-1]),L.jig=new xo(e.view,r,()=>({justification:i,scale:n,styleName:s,elementOffsets:c()})),L}async handleResult(L){if(L.status===S.OK)return l(L.value),"continue";if(L.status!==S.Keyword)return"finish";const M=L.stringResult??"";return M==="Undo"?(h(),"continue"):M==="Close"&&r.length>1?(d(),"finish"):await x(M)?"continue":"finish"}}const v=new Te;if(v.setState(new b),await v.run(P=>A.instance.editor.getPoint(P)),r.length<2)return;const C=new u.AcDbMLine;$n(C,r,s,i,n,a,c()),t.tables.blockTable.modelSpace.appendEntity(C),t.cmlstyle=s,t.cmlscale=n}}function $n(o,e,t,i,n,s,r){if(e.length<=0){o.clearSegments();return}if(o.styleName=t,o.styleObjectHandle="",o.justification=i,o.scale=n,o.styleCount=r.length,o.closed=s,o.startPosition=e[0],e.length<2){o.clearSegments();return}o.segments=bh(e,r)}function bh(o,e){const t=vh(o);return o.slice(1).map((i,n)=>{const s=n+1,r=xh(t,s);return{position:i,direction:t[Math.min(s,t.length-1)],miterDirection:r.direction,elements:e.map(a=>({parameterCount:1,parameters:[a*r.offsetScale],fillCount:0,fillParameters:[]}))}})}function vh(o){const e=[];for(let t=0;t<o.length-1;t++){const i=o[t],n=o[t+1],s=Wn({x:n.x-i.x,y:n.y-i.y,z:n.z-i.z});e.push(s??{x:1,y:0,z:0})}return e}function xh(o,e){if(o.length<=0)return{direction:{x:0,y:1,z:0},offsetScale:1};if(e<=0)return{direction:Wi(o[0]),offsetScale:1};if(e>=o.length)return{direction:Wi(o[o.length-1]),offsetScale:1};const t=Wi(o[e-1]),i=Wi(o[e]),n=Wn({x:t.x+i.x,y:t.y+i.y,z:t.z+i.z});if(!n)return{direction:i,offsetScale:1};const s=Math.abs(Ah(n,i));return u.AcGeTol.isNonPositive(s)?{direction:n,offsetScale:1}:{direction:n,offsetScale:1/s}}function Sh(o,e,t){if(o.length<=0)return[];let i=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(const r of o)r.offset<i&&(i=r.offset),r.offset>n&&(n=r.offset);let s=0;return e===u.AcDbMLineJustification.Top?s=-n:e===u.AcDbMLineJustification.Bottom&&(s=-i),o.map(r=>(r.offset+s)*t)}function Wi(o){return Wn({x:-o.y,y:o.x,z:0})??{x:0,y:1,z:0}}function Wn(o){const e=Math.sqrt(o.x*o.x+o.y*o.y+o.z*o.z);if(u.AcGeTol.isPositive(e))return{x:o.x/e,y:o.y/e,z:o.z/e}}function Ah(o,e){return o.x*e.x+o.y*e.y+o.z*e.z}function Ch(o,e){return u.DEFAULT_TOL.equalPoint3d(o,e)}class Ao extends j{constructor(){super(),this.mtextEditor=new Ne,this.mode=R.Write}async execute(e){const t=new yi(g.t("main.inputManager.firstCorner"),g.t("main.inputManager.secondCorner"));t.useBasePoint=!1,t.useDashedLine=!1;const i=await A.instance.editor.getBox(t);if(i.status!==S.OK||!i.value)return;const n=i.value,s=Math.max(Math.abs(n.max.x-n.min.x),1e-4),r=e.view,a=this.pixelsToWorldY(r,24),c={x:n.min.x,y:n.max.y,z:0},l=Array.from(new Set(A.instance.avaiableFonts.flatMap(m=>m.name).map(m=>m.trim()).filter(m=>m.length>0))),h=await this.mtextEditor.open({view:r,location:c,width:s,textHeight:a,toolbarFontFamilies:l});if(!h||!h.contents.trim())return;const p=new u.AcDbMText;p.location=h.location,p.contents=h.contents,p.width=h.width,p.height=h.height,p.lineSpacingFactor=h.lineSpacingFactor,p.attachmentPoint=h.attachmentPoint,e.doc.database.tables.blockTable.modelSpace.appendEntity(p)}pixelsToWorldY(e,t){const i=e.screenToWorld({x:0,y:0}),n=e.screenToWorld({x:0,y:t});return Math.max(Math.abs(n.y-i.y),1e-4)}}class Co extends j{constructor(){super(),this.mode=R.Write}async execute(e){for(;;){const t=new D(g.t("jig.point.point")),i=await A.instance.editor.getPoint(t);if(i.status!==S.OK||!i.value)return;const n=new u.AcDbPoint;n.position=new u.AcGePoint3d(i.value),e.doc.database.tables.blockTable.modelSpace.appendEntity(n)}}}const Ph=3,_h=1024;function Lh(o,e){return Math.hypot(e.x-o.x,e.y-o.y)}function Hn(o,e){o.reset(!1),e.forEach((t,i)=>o.addVertexAt(i,t)),o.closed=!0}function Po(o,e,t,i){const n=Lh(o,t);if(u.AcGeTol.isNonPositive(n))return;const s=Math.PI*2/e,r=Math.atan2(t.y-o.y,t.x-o.x),a=i==="Inscribed"?n:n/Math.cos(Math.PI/e);if(!Number.isFinite(a)||u.AcGeTol.isNonPositive(a))return;const c=i==="Inscribed"?r:r+s/2,l=[];for(let h=0;h<e;h++){const d=c+h*s;l.push(new u.AcGePoint2d(o.x+a*Math.cos(d),o.y+a*Math.sin(d)))}return l}function _o(o,e,t){const i=e.x-o.x,n=e.y-o.y,s=Math.hypot(i,n);if(u.AcGeTol.isNonPositive(s))return;const r=Math.PI*2/t,a=[new u.AcGePoint2d(o),new u.AcGePoint2d(e)];let c=e.x,l=e.y,h=i,d=n;for(let p=2;p<t;p++){const m=h*Math.cos(r)-d*Math.sin(r),f=h*Math.sin(r)+d*Math.cos(r);c+=m,l+=f,a.push(new u.AcGePoint2d(c,l)),h=m,d=f}return a}class Th extends ${constructor(e,t,i,n){super(e),this._polyline=new u.AcDbPolyline,this._center=t,this._sides=i,this._modeProvider=n}get entity(){return this._polyline}update(e){const t=Po(this._center,this._sides,e,this._modeProvider());t&&Hn(this._polyline,t)}}class Ih extends ${constructor(e,t,i){super(e),this._polyline=new u.AcDbPolyline,this._firstPoint=t,this._sides=i}get entity(){return this._polyline}update(e){const t=_o(this._firstPoint,e,this._sides);t&&Hn(this._polyline,t)}}const qt=class qt extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=await this.promptSides();if(t==null)return;const i=new D(g.t("jig.polygon.centerOrEdge"));this.addKeyword(i,"edge");const n=await A.instance.editor.getPoint(i);if(n.status===S.Keyword){n.stringResult==="Edge"&&await this.runEdgeFlow(e,t);return}n.status===S.OK&&await this.runCenterFlow(e,t,n.value)}addKeyword(e,t){e.keywords.add(g.t(`jig.polygon.keywords.${t}.display`),g.t(`jig.polygon.keywords.${t}.global`),g.t(`jig.polygon.keywords.${t}.local`))}appendPolygon(e,t){const i=new u.AcDbPolyline;Hn(i,t),e.doc.database.tables.blockTable.modelSpace.appendEntity(i)}warnInvalidInput(e){ee.emit("message",{message:g.t(`jig.polygon.invalid.${e}`),type:"warning"})}async promptSides(){for(;;){const e=qt._lastSides,t=new le(`${g.t("jig.polygon.numberOfSides")} <${e}>`);t.allowEmpty=!0,t.allowSpaces=!1;const i=await A.instance.editor.getString(t);if(i.status!==S.OK)return;const n=(i.stringResult??"").trim(),s=n===""?e:Number(n);if(Number.isInteger(s)&&s>=Ph&&s<=_h)return qt._lastSides=s,s;this.warnInvalidInput("sides")}}async runCenterFlow(e,t,i){let n="Inscribed";for(;;){const s=new D(g.t("jig.polygon.radiusOrType"));this.addKeyword(s,"inscribed"),this.addKeyword(s,"circumscribed"),s.useDashedLine=!0,s.useBasePoint=!0,s.basePoint=new u.AcGePoint3d(i),s.jig=new Th(e.view,i,t,()=>n);const r=await A.instance.editor.getPoint(s);if(r.status===S.Keyword){const c=r.stringResult??"";if(c==="Inscribed"){n="Inscribed";continue}if(c==="Circumscribed"){n="Circumscribed";continue}return}if(r.status!==S.OK)return;const a=Po(i,t,r.value,n);if(!a){this.warnInvalidInput("radius");continue}this.appendPolygon(e,a);return}}async runEdgeFlow(e,t){const i=new D(g.t("jig.polygon.edgeStart")),n=await A.instance.editor.getPoint(i);if(n.status!==S.OK)return;const s=n.value,r=new D(g.t("jig.polygon.edgeEnd"));r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(s),r.jig=new Ih(e.view,s,t);const a=await A.instance.editor.getPoint(r);if(a.status!==S.OK)return;const c=_o(s,a.value,t);if(!c){this.warnInvalidInput("edge");return}this.appendPolygon(e,c)}};qt._lastSides=4;let Hi=qt;class Lo extends ${constructor(e,t,i,n,s){super(e),this._hasTemp=!1,this._polyline=new u.AcDbPolyline,this._points=t,this._bulges=i,this._currentBulge=n,this._bulgeProvider=s,this._baseCount=t.length,this._appliedBulge=this._bulges[this._baseCount-1],this.addBaseVertices()}get entity(){return this._polyline}update(e){var s;if(this._baseCount===0)return;this._hasTemp&&(this._polyline.removeVertexAt(this._baseCount),this._hasTemp=!1);const t=this._baseCount-1,n=((s=this._bulgeProvider)==null?void 0:s.call(this,e))??this._currentBulge??this._bulges[t];if(n!==this._appliedBulge){const r=this._points[t];this._polyline.removeVertexAt(t),this._polyline.addVertexAt(t,r,n),this._appliedBulge=n}this._polyline.addVertexAt(this._baseCount,new u.AcGePoint2d(e),void 0),this._hasTemp=!0}addBaseVertices(){this._points.forEach((e,t)=>this._polyline.addVertexAt(t,e,this._bulges[t]))}}class Eh extends ${constructor(e,t,i){super(e),this._polyline=new u.AcDbPolyline,t.forEach((n,s)=>this._polyline.addVertexAt(s,n,i[s]))}get entity(){return this._polyline}update(e){}}class To extends j{constructor(){super(),this.mode=R.Write}complementBulge(e){if(u.AcGeTol.equalToZero(e))return e;const t=4*Math.atan(e),n=(Math.sign(t)||1)*(Math.PI*2-Math.abs(t));return u.AcGeTol.equalToZero(n)?e:Math.tan(n/4)}flipArcBulgeForCtrl(e){return-this.complementBulge(e)}computeArcCenterFromBulge(e,t,i){const n=t.x-e.x,s=t.y-e.y,r=Math.hypot(n,s);if(u.AcGeTol.isNonPositive(r))return;const a=(e.x+t.x)/2,c=(e.y+t.y)/2,l=-s/r,h=n/r,d=r/2*i;return{x:a+l*d,y:c+h*d}}getGeometricTangentAtPoint(e,t,i){const n=e.x-t.x,s=e.y-t.y;return i?Math.atan2(-s,n):Math.atan2(s,-n)}getArcTangentAtEnd(e,t,i){const n=this.computeArcCenterFromBulge(e,t,i);if(n)return this.getGeometricTangentAtPoint(t,n,i>=0)}getIncomingTangentRadians(e,t){if(e.length<2)return 0;const i=e[e.length-1],n=e[e.length-2],s=t[e.length-2];return s==null||u.AcGeTol.equalToZero(s)?Math.atan2(i.y-n.y,i.x-n.x):this.getArcTangentAtEnd(n,i,s)??Math.atan2(i.y-n.y,i.x-n.x)}computeBulgeFromTangentDirection(e,t,i){const n=Math.cos(i),s=Math.sin(i),r=t.x-e.x,a=t.y-e.y,c=-s,l=n,h=2*(r*c+a*l);if(u.AcGeTol.equalToZero(h))return;const d=(r*r+a*a)/h;if(!Number.isFinite(d))return;const p={x:e.x+c*d,y:e.y+l*d};return this.computeBulgeFromCenterWithTangent(e,t,p,i)}computeBulgeFromCenterWithTangent(e,t,i,n){const s=e.x-i.x,r=e.y-i.y,a=t.x-i.x,c=t.y-i.y,l=Math.cos(n),h=Math.sin(n),d=t.x-e.x,p=t.y-e.y,m=s*h-r*l;let f;u.AcGeTol.isPositive(Math.abs(m))?f=m>0:f=d*h-p*l>=0;const w=Math.atan2(r,s),x=Math.atan2(c,a);let b;if(f?(b=x-w,u.AcGeTol.isNonPositive(b)&&(b+=Math.PI*2)):(b=w-x,u.AcGeTol.isNonPositive(b)&&(b+=Math.PI*2)),!!u.AcGeTol.great(u.TAU-b,0))return f?Math.tan(b/4):-Math.tan(b/4)}computeBulgeFromTangentAndIncludedAngle(e,t,i,n){const s=Math.cos(i),r=Math.sin(i),a=t.x-e.x,c=t.y-e.y,l=-r,h=s,d=2*(a*l+c*h);if(u.AcGeTol.equalToZero(d))return;const p=(a*a+c*c)/d;if(!Number.isFinite(p))return;const m={x:e.x+l*p,y:e.y+h*p},f=this.computeBulgeFromCenterWithTangent(e,t,m,i);if(f==null)return;const w=Math.tan(n/4);if(Number.isFinite(w))return Math.sign(f)*Math.abs(w)}computeBulgeFromCenter(e,t,i){const n=e.x-i.x,s=e.y-i.y,r=t.x-i.x,a=t.y-i.y,c=n*a-s*r,l=n*r+s*a,h=Math.atan2(c,l);if(Number.isFinite(h))return Math.tan(h/4)}computeCircleCenter(e,t,i){const n=e.x,s=e.y,r=t.x,a=t.y,c=i.x,l=i.y,h=n-r,d=s-a,p=n-c,m=s-l,f=(n*n-r*r+s*s-a*a)/2,w=(n*n-c*c+s*s-l*l)/2,x=h*m-d*p;if(u.AcGeTol.equalToZero(x))return;const b=(m*f-d*w)/x,v=(-p*f+h*w)/x;return new u.AcGePoint2d(b,v)}computeBulgeFromThreePoints(e,t,i){const n=this.computeCircleCenter(e,t,i);if(n)return this.computeBulgeFromCenter(e,i,n)}computeBulgeFromRadius(e,t,i){const n=Math.abs(i),s=t.x-e.x,r=t.y-e.y,a=Math.hypot(s,r);if(a===0||a>2*n)return;const c=(e.x+t.x)/2,l=(e.y+t.y)/2,h=Math.sqrt(Math.max(0,n*n-a*a/4)),d=-r/a,p=s/a,m=i>=0?1:-1,f=c+d*h*m,w=l+p*h*m,x=new u.AcGePoint2d(f,w);return this.computeBulgeFromCenter(e,t,x)}async execute(e){A.instance.editor.resetInputToggles();const t=[],i=[];let n=!1;const s=E=>E==null?E:A.instance.editor.getInputToggles().ctrlArcFlip?this.flipArcBulgeForCtrl(E):E,r=(E,T,F)=>this.computeBulgeFromCenter(E,T,F),a=(E,T,F)=>this.computeBulgeFromThreePoints(E,T,F),c=(E,T,F)=>this.computeBulgeFromRadius(E,T,F),l=()=>this.getIncomingTangentRadians(t,i),h=E=>{const T=f();if(T)return this.computeBulgeFromTangentDirection(T,E,l())},d=(E,T,F,O)=>this.computeBulgeFromTangentAndIncludedAngle(E,T,F,O),p=()=>new Eh(e.view,t,i),m=(E,T)=>new Lo(e.view,t,i,E,T),f=()=>t[t.length-1],w=E=>{t.length>0&&(i[t.length-1]=E)},x=E=>{t.push(new u.AcGePoint2d(E)),i.push(void 0)},b=()=>{t.length<=1||(t.pop(),i.pop(),i[i.length-1]=void 0)},v=E=>E!==S.OK&&E!==S.Keyword;class C{constructor(T){this.machine=T}buildPrompt(){const T=new D(g.t("jig.polyline.nextPointWithOptions"));T.keywords.add(g.t("jig.polyline.keywords.arc.display"),g.t("jig.polyline.keywords.arc.global"),g.t("jig.polyline.keywords.arc.local")),T.keywords.add(g.t("jig.polyline.keywords.undo.display"),g.t("jig.polyline.keywords.undo.global"),g.t("jig.polyline.keywords.undo.local")),T.keywords.add(g.t("jig.polyline.keywords.close.display"),g.t("jig.polyline.keywords.close.global"),g.t("jig.polyline.keywords.close.local")),T.useDashedLine=!0,T.useBasePoint=!0;const F=f();return F&&(T.basePoint=new u.AcGePoint3d(F)),T.jig=m(void 0),T}async handleResult(T){if(T.status===S.Keyword){const F=T.stringResult??"";if(F==="Arc")this.machine.setState(new P(this.machine));else if(F==="Undo")b();else if(F==="Close"&&t.length>1)return n=!0,w(void 0),"finish";return"continue"}return T.status===S.OK?(w(void 0),x(T.value),"continue"):"finish"}}class P{constructor(T){this.machine=T}buildPrompt(){const T=new D(g.t("jig.polyline.nextPointWithArcOptions"));T.keywords.add(g.t("jig.polyline.keywords.angle.display"),g.t("jig.polyline.keywords.angle.global"),g.t("jig.polyline.keywords.angle.local")),T.keywords.add(g.t("jig.polyline.keywords.center.display"),g.t("jig.polyline.keywords.center.global"),g.t("jig.polyline.keywords.center.local")),T.keywords.add(g.t("jig.polyline.keywords.secondPoint.display"),g.t("jig.polyline.keywords.secondPoint.global"),g.t("jig.polyline.keywords.secondPoint.local")),T.keywords.add(g.t("jig.polyline.keywords.radius.display"),g.t("jig.polyline.keywords.radius.global"),g.t("jig.polyline.keywords.radius.local")),T.keywords.add(g.t("jig.polyline.keywords.line.display"),g.t("jig.polyline.keywords.line.global"),g.t("jig.polyline.keywords.line.local")),T.keywords.add(g.t("jig.polyline.keywords.undo.display"),g.t("jig.polyline.keywords.undo.global"),g.t("jig.polyline.keywords.undo.local")),T.keywords.add(g.t("jig.polyline.keywords.close.display"),g.t("jig.polyline.keywords.close.global"),g.t("jig.polyline.keywords.close.local")),T.useDashedLine=!0,T.useBasePoint=!0;const F=f();return F&&(T.basePoint=new u.AcGePoint3d(F)),T.jig=m(void 0,O=>s(h(O))),T}async handleResult(T){if(T.status===S.OK){const z=h(T.value);return z===void 0||(w(s(z)),x(T.value)),"continue"}if(T.status!==S.Keyword)return"finish";const F=T.stringResult??"";if(F==="Line")return this.machine.setState(new C(this.machine)),"continue";if(F==="Undo")return b(),"continue";if(F==="Close"&&t.length>1)return n=!0,w(void 0),"finish";const O=f();if(!O)return"finish";if(F==="Angle"){const z=new q(g.t("jig.polyline.arcAngle"));z.jig=p();const U=await A.instance.editor.getDouble(z);if(v(U.status))return"finish";const V=new D(g.t("jig.polyline.arcEndPoint"));V.useDashedLine=!0,V.useBasePoint=!0,V.basePoint=new u.AcGePoint3d(O);const G=(U.value??0)*(Math.PI/180),K=l();V.jig=m(void 0,Ae=>s(d(O,Ae,K,G)));const W=await A.instance.editor.getPoint(V);if(v(W.status))return"finish";const te=d(O,W.value,K,G);return te===void 0||(w(s(te)),x(W.value)),"continue"}if(F==="Center"){const z=new D(g.t("jig.polyline.arcCenter"));z.jig=p();const U=await A.instance.editor.getPoint(z);if(v(U.status))return"finish";const V=new D(g.t("jig.polyline.arcEndPoint"));V.useDashedLine=!0,V.useBasePoint=!0,V.basePoint=new u.AcGePoint3d(O),V.jig=m(void 0,W=>s(r(O,W,U.value)));const G=await A.instance.editor.getPoint(V);if(v(G.status))return"finish";const K=r(O,G.value,U.value);return K===void 0||(w(s(K)),x(G.value)),"continue"}if(F==="SecondPoint"){const z=new D(g.t("jig.polyline.arcSecondPoint"));z.jig=p(),z.useDashedLine=!0,z.useBasePoint=!0,z.basePoint=new u.AcGePoint3d(O);const U=await A.instance.editor.getPoint(z);if(v(U.status))return"finish";const V=new D(g.t("jig.polyline.arcEndPoint"));V.useDashedLine=!0,V.useBasePoint=!0,V.basePoint=new u.AcGePoint3d(O),V.jig=m(void 0,W=>s(a(O,U.value,W)));const G=await A.instance.editor.getPoint(V);if(v(G.status))return"finish";const K=a(O,U.value,G.value);return K===void 0||(w(s(K)),x(G.value)),"continue"}if(F==="Radius"){const z=new q(g.t("jig.polyline.arcRadius"));z.jig=p();const U=await A.instance.editor.getDouble(z);if(v(U.status))return"finish";const V=new D(g.t("jig.polyline.arcEndPoint"));V.useDashedLine=!0,V.useBasePoint=!0,V.basePoint=new u.AcGePoint3d(O),V.jig=m(void 0,W=>s(c(O,W,U.value??0)));const G=await A.instance.editor.getPoint(V);if(v(G.status))return"finish";const K=c(O,G.value,U.value??0);return K===void 0||(w(s(K)),x(G.value)),"continue"}return"continue"}}const L=new D(g.t("jig.polyline.firstPoint")),M=await A.instance.editor.getPoint(L);if(M.status!==S.OK)return;x(M.value);const k=new Te;if(k.setState(new C(k)),await k.run(E=>A.instance.editor.getPoint(E)),t.length>=2){const E=e.doc.database,T=new u.AcDbPolyline;t.forEach((F,O)=>T.addVertexAt(O,F,i[O])),n&&(T.closed=!0),E.tables.blockTable.modelSpace.appendEntity(T)}}}function Io(o,e){const t=new u.AcGePoint3d(e).sub(o);if(u.AcGeTol.isPositive(t.length()))return t.normalize()}class kh extends ${constructor(e,t){super(e),this._startPoint=new u.AcGePoint3d(t),this._ray=new u.AcDbRay,this._ray.basePoint=new u.AcGePoint3d(t),this._ray.unitDir=new u.AcGePoint3d(1,0,0)}get entity(){return this._ray}update(e){const t=Io(this._startPoint,e);t&&(this._ray.basePoint=new u.AcGePoint3d(this._startPoint),this._ray.unitDir=t)}}class Eo extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=e.doc.database,i=new D(g.t("jig.ray.startPoint")),n=await A.instance.editor.getPoint(i);if(n.status!==S.OK)return;const s=new u.AcGePoint3d(n.value);for(;;){const r=new D(g.t("jig.ray.throughPoint"));r.useDashedLine=!0,r.useBasePoint=!0,r.basePoint=new u.AcGePoint3d(s),r.jig=new kh(e.view,s);const a=await A.instance.editor.getPoint(r);if(a.status!==S.OK)break;const c=Io(s,a.value);if(!c)continue;const l=new u.AcDbRay;l.basePoint=new u.AcGePoint3d(s),l.unitDir=c,t.tables.blockTable.modelSpace.appendEntity(l)}}}const Bh=Math.tan(Math.PI/8),Dh={chamferDist1:0,chamferDist2:0,filletRadius:0,width:0,elevation:0,thickness:0,rotation:0};function Ve(o,e){o.keywords.add(g.t(`jig.rect.keywords.${e}.display`),g.t(`jig.rect.keywords.${e}.global`),g.t(`jig.rect.keywords.${e}.local`))}function Mh(o,e){o.keywords.add(g.t(`jig.rect.keywords.${e}.display`),g.t(`jig.rect.keywords.${e}.global`),g.t(`jig.rect.keywords.${e}.local`))}function Yn(o){ee.emit("message",{message:g.t(`jig.rect.${o}`),type:"warning"})}function Oh(o,e,t){const i=Math.cos(t),n=Math.sin(t);return new u.AcGePoint2d(o.x+e.x*i-e.y*n,o.y+e.x*n+e.y*i)}function Fh(o,e,t){const i=e.x-o.x,n=e.y-o.y,s=Math.cos(t),r=Math.sin(t);return new u.AcGePoint2d(i*s+n*r,-i*r+n*s)}function ut(o){return Number.isFinite(o??NaN)?Math.max(0,o??0):0}function Xn(o,e){return[{point:new u.AcGePoint2d(0,0)},{point:new u.AcGePoint2d(o,0)},{point:new u.AcGePoint2d(o,e)},{point:new u.AcGePoint2d(0,e)}]}function ko(o,e,t,i){const n=o>=0?1:-1,s=e>=0?1:-1,r=Math.abs(o),a=Math.abs(e),c=Math.min(ut(t),r/2),l=Math.min(ut(i),a/2);if(u.AcGeTol.isNonPositive(c)&&u.AcGeTol.isNonPositive(l))return Xn(o,e);const h=new u.AcGePoint2d(n*c,0),d=new u.AcGePoint2d(0,s*l),p=new u.AcGePoint2d(o-n*c,0),m=new u.AcGePoint2d(o,s*l),f=new u.AcGePoint2d(o,e-s*l),w=new u.AcGePoint2d(o-n*c,e),x=new u.AcGePoint2d(n*c,e),b=new u.AcGePoint2d(0,e-s*l);return[{point:h},{point:p},{point:m},{point:f},{point:w},{point:x},{point:b},{point:d}]}function Rh(o,e,t){const i=Math.abs(o),n=Math.abs(e),s=Math.min(ut(t),i/2,n/2);if(u.AcGeTol.isNonPositive(s))return Xn(o,e);const r=ko(o,e,s,s),c=(o*e>=0?1:-1)*Bh;return r.map((l,h)=>({point:l.point,bulge:h%2===1?c:void 0}))}function jh(o,e,t){return u.AcGeTol.isPositive(t.filletRadius)?Rh(o,e,t.filletRadius):u.AcGeTol.isPositive(t.chamferDist1)||u.AcGeTol.isPositive(t.chamferDist2)?ko(o,e,t.chamferDist1,t.chamferDist2):Xn(o,e)}function qn(o,e,t,i){let n=0,s=0;if(t.mode==="corner"){const c=Fh(e,t.secondPoint,i.rotation);n=c.x,s=c.y}else n=t.length,s=t.width;if(u.AcGeTol.equalToZero(n)||u.AcGeTol.equalToZero(s))return!1;o.reset(!1);const r=jh(n,s,i),a=ut(i.width);return r.forEach((c,l)=>{const h=Oh(e,c.point,i.rotation);u.AcGeTol.isPositive(a)?o.addVertexAt(l,h,c.bulge,a,a):o.addVertexAt(l,h,c.bulge)}),o.elevation=i.elevation,o.closed=!0,!0}class Bo extends ${constructor(e,t,i){super(e),this._rect=new u.AcDbPolyline,this._firstPoint=new u.AcGePoint2d(t),this._settingsProvider=i}get entity(){return this._rect}update(e){qn(this._rect,this._firstPoint,{mode:"corner",secondPoint:e},this._settingsProvider())}}class dt extends ${constructor(e,t,i,n){super(e),this._rect=new u.AcDbPolyline,qn(this._rect,t,i,n)}get entity(){return this._rect}update(e){}}function Zn(o){return{chamferDist1:o.chamferDist1,chamferDist2:o.chamferDist2,filletRadius:o.filletRadius,width:o.width,elevation:o.elevation,thickness:o.thickness,rotation:o.rotation}}function Ie(o){return Number.isFinite(o??NaN)&&u.AcGeTol.isPositive(o??0)}const Zt=class Zt extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=Zn(Zt._settings),i=await this.promptFirstCorner(t);if(!i)return;const n=await this.promptSecondInput(e,i,t);if(!n)return;const s=new u.AcDbPolyline;if(!qn(s,i,n,t)){Yn("invalidRect");return}u.AcGeTol.isPositive(t.thickness)&&Yn("thicknessNotSupported"),e.doc.database.tables.blockTable.modelSpace.appendEntity(s),Zt._settings=Zn(t)}async promptFirstCorner(e){for(;;){const t=new D(g.t("jig.rect.firstPointWithOptions"));Ve(t,"chamfer"),Ve(t,"elevation"),Ve(t,"fillet"),Ve(t,"thickness"),Ve(t,"width");const i=await A.instance.editor.getPoint(t);if(i.status===S.OK)return i.value;if(i.status!==S.Keyword)return;const n=i.stringResult??"";if(n==="Chamfer"){if(!await this.promptChamfer(e))return}else if(n==="Elevation"){if(!await this.promptElevation(e))return}else if(n==="Fillet"){if(!await this.promptFillet(e))return}else if(n==="Thickness"){if(!await this.promptThickness(e))return}else if(n==="Width"&&!await this.promptWidth(e))return}}async promptSecondInput(e,t,i){let n;class s{constructor(c){this.cmd=c}buildPrompt(){const c=new D(g.t("jig.rect.otherCornerWithOptions"));return Ve(c,"area"),Ve(c,"dimensions"),Ve(c,"rotation"),c.useDashedLine=!1,c.useBasePoint=!0,c.basePoint=new u.AcGePoint3d(t),c.jig=new Bo(e.view,t,()=>i),c}async handleResult(c){if(c.status===S.OK)return n={mode:"corner",secondPoint:c.value},"finish";if(c.status!==S.Keyword)return"finish";const l=c.stringResult??"";if(l==="Rotation")return await this.cmd.promptRotation(e,t,i)?"continue":"finish";if(l==="Dimensions"){const h=await this.cmd.promptDimensions(e,t,i);return h&&(n=h),"finish"}if(l==="Area"){const h=await this.cmd.promptArea(e,t,i);return h&&(n=h),"finish"}return"continue"}}const r=new Te;return r.setState(new s(this)),await r.run(a=>A.instance.editor.getPoint(a)),n}async promptPositiveDouble(e,t){for(;;){const i=new q(e);i.allowNegative=!1,i.allowZero=!1,t&&(i.jig=t);const n=await A.instance.editor.getDouble(i);if(n.status!==S.OK)return;if(Ie(n.value))return n.value;Yn("invalidPositive")}}async promptChamfer(e){const t=await this.promptPositiveDouble(g.t("jig.rect.chamferFirst"));if(!Ie(t))return!1;const i=await this.promptPositiveDouble(g.t("jig.rect.chamferSecond"));return Ie(i)?(e.chamferDist1=t,e.chamferDist2=i,e.filletRadius=0,!0):!1}async promptFillet(e){const t=await this.promptPositiveDouble(g.t("jig.rect.filletRadius"));return Ie(t)?(e.filletRadius=t,e.chamferDist1=0,e.chamferDist2=0,!0):!1}async promptWidth(e){const t=new q(g.t("jig.rect.segmentWidth"));t.allowNegative=!1,t.allowZero=!0;const i=await A.instance.editor.getDouble(t);return i.status!==S.OK?!1:(e.width=ut(i.value),!0)}async promptElevation(e){const t=new q(g.t("jig.rect.elevationValue"));t.allowNegative=!0,t.allowZero=!0;const i=await A.instance.editor.getDouble(t);return i.status!==S.OK?!1:(e.elevation=i.value??0,!0)}async promptThickness(e){const t=new q(g.t("jig.rect.thicknessValue"));t.allowNegative=!1,t.allowZero=!0;const i=await A.instance.editor.getDouble(t);return i.status!==S.OK?!1:(e.thickness=ut(i.value),!0)}async promptRotation(e,t,i){const n=new ve(g.t("jig.rect.rotationAngle"));n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=new u.AcGePoint3d(t),n.allowNegative=!0,n.allowZero=!0,n.jig=new dt(e.view,t,{mode:"dimensions",length:1,width:1},i);const s=await A.instance.editor.getAngle(n);return s.status!==S.OK?!1:(i.rotation=(s.value??0)*Math.PI/180,!0)}async promptDimensions(e,t,i){const n={mode:"dimensions",length:1,width:1},s=await this.promptPositiveDouble(g.t("jig.rect.dimensionLength"),new dt(e.view,t,n,i));if(!Ie(s))return;const r=await this.promptPositiveDouble(g.t("jig.rect.dimensionWidth"),new dt(e.view,t,{mode:"dimensions",length:s,width:1},i));if(Ie(r))return{mode:"dimensions",length:s,width:r}}async promptArea(e,t,i){const n=await this.promptPositiveDouble(g.t("jig.rect.areaValue"),new dt(e.view,t,{mode:"dimensions",length:1,width:1},i));if(!Ie(n))return;const s=new q(g.t("jig.rect.areaLengthOrWidth"));Mh(s,"rectWidth"),s.allowNegative=!1,s.allowZero=!1,s.jig=new dt(e.view,t,{mode:"dimensions",length:1,width:1},i);const r=await A.instance.editor.getDouble(s);if(r.status===S.Keyword){if(r.stringResult!=="Width")return;const c=await this.promptPositiveDouble(g.t("jig.rect.areaSpecifyWidth"),new dt(e.view,t,{mode:"dimensions",length:1,width:1},i));return Ie(c)?{mode:"dimensions",length:(n??0)/(c??1),width:c}:void 0}if(r.status!==S.OK||!Ie(r.value))return;const a=r.value;return{mode:"dimensions",length:a,width:(n??0)/a}}};Zt._settings=Zn(Dh);let Yi=Zt;class Do extends ${constructor(e,t,i,n){super(e),this._points=t,this._settings=i,this._closed=n,this._spline=this.createSpline(t)}get entity(){return this._spline}update(e){const t=new u.AcGePoint2d(e),i=this._points[this._points.length-1],s=!i||!Vh(i,t)?[...this._points,t]:[...this._points];try{this.rebuildSpline(s)}catch{this.rebuildSpline(this._points)}}createSpline(e){return Jn(e,this._settings,this._closed)}rebuildSpline(e){if(e.length<2){const r=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],a=1,c=jt(r.length,a);this._spline.rebuild(r,c,void 0,a);return}const t=e.map(r=>new u.AcGePoint3d(r.x,r.y,0)),i=Oo(t.length,this._settings),n=this._closed&&t.length>=3;if(this._settings.method==="fit"){this._spline.rebuild(t,Fo(this._settings.knotsType),i,n);return}const s=jt(t.length,i);this._spline.rebuild(t,s,void 0,i,!1),n&&(this._spline.closed=!0)}}class Mo extends j{constructor(){super(),this.mode=R.Write}async execute(e){const t=[],i={method:"fit",knotsType:"chord",degree:3};let n=!1;const s=v=>{t.push(new u.AcGePoint2d(v))},r=()=>{t.length<=1||t.pop()},a=()=>t[t.length-1],c=()=>t.length>=3,l=()=>new Do(e.view,t,i,n),h=()=>new Nh(e.view,t,i,n),d=async()=>{const v=new X(g.t("jig.spline.methodPrompt"));v.keywords.add(g.t("jig.spline.keywords.fit.display"),g.t("jig.spline.keywords.fit.global"),g.t("jig.spline.keywords.fit.local")),v.keywords.add(g.t("jig.spline.keywords.cv.display"),g.t("jig.spline.keywords.cv.global"),g.t("jig.spline.keywords.cv.local"));const C=await A.instance.editor.getKeywords(v);return C.status!==S.OK?!1:(C.stringResult==="Fit"?i.method="fit":C.stringResult==="CV"&&(i.method="cv"),!0)},p=async()=>{const v=new X(g.t("jig.spline.knotsPrompt"));v.jig=h(),v.keywords.add(g.t("jig.spline.keywords.chord.display"),g.t("jig.spline.keywords.chord.global"),g.t("jig.spline.keywords.chord.local")),v.keywords.add(g.t("jig.spline.keywords.sqrtChord.display"),g.t("jig.spline.keywords.sqrtChord.global"),g.t("jig.spline.keywords.sqrtChord.local")),v.keywords.add(g.t("jig.spline.keywords.uniform.display"),g.t("jig.spline.keywords.uniform.global"),g.t("jig.spline.keywords.uniform.local"));const C=await A.instance.editor.getKeywords(v);return C.status!==S.OK?!1:(C.stringResult==="Chord"?i.knotsType="chord":C.stringResult==="SqrtChord"?i.knotsType="sqrtChord":C.stringResult==="Uniform"&&(i.knotsType="uniform"),!0)},m=async()=>{const v=new Pn(g.t("jig.spline.degreePrompt"),1,10);v.jig=h();const C=await A.instance.editor.getInteger(v);if(C.status!==S.OK)return!1;const P=Math.floor(C.value??i.degree);return i.degree=Math.max(1,P),!0},f=v=>{v.useDashedLine=!0,v.useBasePoint=!0;const C=a();C&&(v.basePoint=new u.AcGePoint3d(C)),v.jig=l()};class w{constructor(C){this.machine=C}buildPrompt(){const C=new D(g.t("jig.spline.nextPointWithFitOptions"));return C.keywords.add(g.t("jig.spline.keywords.method.display"),g.t("jig.spline.keywords.method.global"),g.t("jig.spline.keywords.method.local")),C.keywords.add(g.t("jig.spline.keywords.knots.display"),g.t("jig.spline.keywords.knots.global"),g.t("jig.spline.keywords.knots.local")),C.keywords.add(g.t("jig.spline.keywords.undo.display"),g.t("jig.spline.keywords.undo.global"),g.t("jig.spline.keywords.undo.local")),C.keywords.add(g.t("jig.spline.keywords.close.display"),g.t("jig.spline.keywords.close.global"),g.t("jig.spline.keywords.close.local")),f(C),C}async handleResult(C){if(C.status===S.OK)return s(C.value),"continue";if(C.status!==S.Keyword)return"finish";const P=C.stringResult??"";return P==="Method"?await d()?(i.method==="cv"&&this.machine.setState(new x(this.machine)),"continue"):"finish":P==="Knots"?await p()?"continue":"finish":P==="Undo"?(r(),"continue"):P==="Close"&&c()?(n=!0,"finish"):"continue"}}class x{constructor(C){this.machine=C}buildPrompt(){const C=new D(g.t("jig.spline.nextPointWithCvOptions"));return C.keywords.add(g.t("jig.spline.keywords.method.display"),g.t("jig.spline.keywords.method.global"),g.t("jig.spline.keywords.method.local")),C.keywords.add(g.t("jig.spline.keywords.degree.display"),g.t("jig.spline.keywords.degree.global"),g.t("jig.spline.keywords.degree.local")),C.keywords.add(g.t("jig.spline.keywords.undo.display"),g.t("jig.spline.keywords.undo.global"),g.t("jig.spline.keywords.undo.local")),C.keywords.add(g.t("jig.spline.keywords.close.display"),g.t("jig.spline.keywords.close.global"),g.t("jig.spline.keywords.close.local")),f(C),C}async handleResult(C){if(C.status===S.OK)return s(C.value),"continue";if(C.status!==S.Keyword)return"finish";const P=C.stringResult??"";return P==="Method"?await d()?(i.method==="fit"&&this.machine.setState(new w(this.machine)),"continue"):"finish":P==="Degree"?await m()?"continue":"finish":P==="Undo"?(r(),"continue"):P==="Close"&&c()?(n=!0,"finish"):"continue"}}for(;t.length===0;){const v=new D(g.t("jig.spline.firstPointWithOptions"));v.keywords.add(g.t("jig.spline.keywords.method.display"),g.t("jig.spline.keywords.method.global"),g.t("jig.spline.keywords.method.local"));const C=await A.instance.editor.getPoint(v);if(C.status===S.OK){s(C.value);break}if(C.status===S.Keyword&&C.stringResult==="Method"){if(!await d())return;continue}return}const b=new Te;if(b.setState(i.method==="fit"?new w(b):new x(b)),await b.run(v=>A.instance.editor.getPoint(v)),t.length>=2){const v=e.doc.database,C=Jn(t,i,n);v.tables.blockTable.modelSpace.appendEntity(C)}}}class Nh extends ${constructor(e,t,i,n){super(e),this._spline=Jn(t,i,n)}get entity(){return this._spline}update(e){}}function Jn(o,e,t){if(o.length<2){const l=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],h=1,d=jt(l.length,h);return new u.AcDbSpline(l,d,void 0,h)}const i=o.map(l=>new u.AcGePoint3d(l.x,l.y,0)),n=e.method==="fit"?zh(i):i;if(n.length<2){const l=[new u.AcGePoint3d(0,0,0),new u.AcGePoint3d(1,1,0)],h=1,d=jt(l.length,h);return new u.AcDbSpline(l,d,void 0,h)}const s=Oo(n.length,e),r=t&&n.length>=3;if(e.method==="fit")return new u.AcDbSpline(n,Fo(e.knotsType),s,r);const a=jt(n.length,s),c=new u.AcDbSpline(n,a,void 0,s,!1);return r&&(c.closed=!0),c}function Oo(o,e){const t=Math.max(1,o-1);return e.method==="fit"?Math.min(3,t):Math.min(Math.max(1,e.degree),t)}function zh(o){if(o.length<=1)return o;const e=[new u.AcGePoint3d(o[0])];for(let t=1;t<o.length;t++){const i=e[e.length-1],n=o[t];Gh(i,n)||e.push(new u.AcGePoint3d(n))}return e}function Vh(o,e){return u.DEFAULT_TOL.equalPoint2d(o,e)}function Gh(o,e){return u.DEFAULT_TOL.equalPoint3d(o,e)}function Fo(o){switch(o){case"chord":return"Chord";case"sqrtChord":return"SqrtChord";case"uniform":default:return"Uniform"}}function jt(o,e){const t=[],i=o+e+1;for(let n=0;n<i;n++)n<e+1?t.push(0):n>=i-e-1?t.push(1):t.push((n-e)/(o-e));return t}const gt=1e6;class Ro extends j{constructor(){super(),this.mode=R.Write}async execute(e){let t="point";for(;;){const i=new D(g.t("jig.xline.firstPointOrOptions"));i.keywords.add(g.t("jig.xline.keywords.hor.display"),g.t("jig.xline.keywords.hor.global"),g.t("jig.xline.keywords.hor.local")),i.keywords.add(g.t("jig.xline.keywords.ver.display"),g.t("jig.xline.keywords.ver.global"),g.t("jig.xline.keywords.ver.local")),i.keywords.add(g.t("jig.xline.keywords.ang.display"),g.t("jig.xline.keywords.ang.global"),g.t("jig.xline.keywords.ang.local"));const n=await A.instance.editor.getPoint(i);if(n.status===S.Keyword)n.stringResult==="Hor"?t="hor":n.stringResult==="Ver"?t="ver":n.stringResult==="Ang"&&(t="ang");else if(n.status===S.OK&&n.value){t="point";const h=new D(g.t("jig.xline.secondPoint"));h.useBasePoint=!0,h.useDashedLine=!0,h.basePoint=new u.AcGePoint3d(n.value);const d=await A.instance.editor.getPoint(h);if(d.status!==S.OK||!d.value)return;const p={x:d.value.x-n.value.x,y:d.value.y-n.value.y,z:d.value.z-n.value.z};this.appendFiniteXLine(e,n.value,p)||A.instance.editor.showMessage(g.t("jig.xline.invalidDirection"),"warning");continue}else return;if(t==="hor"){const h=new D(g.t("jig.xline.throughPoint")),d=await A.instance.editor.getPoint(h);if(d.status!==S.OK||!d.value)return;this.appendFiniteXLine(e,d.value,{x:1,y:0,z:0});continue}if(t==="ver"){const h=new D(g.t("jig.xline.throughPoint")),d=await A.instance.editor.getPoint(h);if(d.status!==S.OK||!d.value)return;this.appendFiniteXLine(e,d.value,{x:0,y:1,z:0});continue}const s=new q(g.t("jig.xline.angle")),r=await A.instance.editor.getDouble(s);if(r.status!==S.OK||r.value==null)return;const a=new D(g.t("jig.xline.throughPoint")),c=await A.instance.editor.getPoint(a);if(c.status!==S.OK||!c.value)return;const l=r.value*Math.PI/180;this.appendFiniteXLine(e,c.value,{x:Math.cos(l),y:Math.sin(l),z:0})}}appendFiniteXLine(e,t,i){const n=this.normalizeDirection(i);if(!n)return!1;const s=new u.AcGePoint3d(t.x-n.x*gt,t.y-n.y*gt,t.z-n.z*gt),r=new u.AcGePoint3d(t.x+n.x*gt,t.y+n.y*gt,t.z+n.z*gt);return e.doc.database.tables.blockTable.modelSpace.appendEntity(new u.AcDbLine(s,r)),!0}normalizeDirection(e){const t=Math.sqrt(e.x*e.x+e.y*e.y+e.z*e.z);if(u.AcGeTol.isPositive(t))return{x:e.x/t,y:e.y/t,z:e.z/t}}}const Qn=[];function pt(o){Qn.push(o)}function es(o){Qn.forEach(e=>e()),Qn.length=0,o.htmlTransientManager.clear("measurement")}class ts extends j{constructor(){super(),this.mode=R.Read}async execute(e){es(e.view)}}const Kh=Object.freeze(Object.defineProperty({__proto__:null,AcApClearMeasurementsCmd:ts,clearAllMeasurements:es,registerMeasurementCleanup:pt},Symbol.toStringTag,{value:"Module"})),is=new Set;function jo(o,e="drawing"){const t=o==null?void 0:o.trim();return t&&(t.split(/[\\/]/).pop()??t).replace(/\.[^.]+$/,"").trim()||e}function Uh(o,e,t="drawing"){const i=jo(o,t),n=e.startsWith(".")?e:`.${e}`;let s=0,r=`${i}${n}`;for(;is.has(r);)s+=1,r=`${i}-${s+1}${n}`;return is.add(r),r}function $h(){is.clear()}class Xi{static isFontLoaded(e){return B.FontManager.instance.isFontLoaded(e)}static getFontType(e){return B.FontManager.instance.getFontType(e)}static getReplacementFontName(e){return B.FontManager.instance.findAndReplaceFont(e)}static getShxCodePoints(e){var s;const t=B.FontManager.instance.getFontByName(e,!1);if(!t||t.type!=="shx")return[];const i=t.data;return Object.keys(((s=i.content)==null?void 0:s.data)??{}).map(r=>Number(r)).filter(r=>Number.isFinite(r)).sort((r,a)=>r-a)}static getLoadedShxFontData(e){const t=B.FontManager.instance.getFontByName(e,!1);if(!(!t||t.type!=="shx"))return t.data}static createShxParserFont(e){return new B.ShxParserFont(e)}static findFontInfoByName(e){var n;const t=((n=A.instance)==null?void 0:n.avaiableFonts)??[],i=e.trim().toLowerCase();if(i)return t.find(s=>s.name.some(r=>r.trim().toLowerCase()===i))}static getCatalogFontType(e){var t;return(t=Xi.findFontInfoByName(e))==null?void 0:t.type}static async ensureDrawingFontLoaded(e){const t=A.instance;t&&(Xi.isFontLoaded(e)||await t.loadFonts([e]))}}function Nt(o){return u.AcDbSysVarManager.instance().getVar(u.AcDbSystemVariables.MEASUREMENTCOLOR,o)}function ns(o,e){return`rgba(${o.red}, ${o.green}, ${o.blue}, ${e})`}function pe(o){return o.cssColor??`rgb(${o.red}, ${o.green}, ${o.blue})`}function Ee(o){const e=document.createElement("div");return e.style.cssText=`width:12px;height:12px;border-radius:50%;background:${pe(o)};border:2px solid var(--ml-ui-border, #fff);box-sizing:border-box;pointer-events:none;transform:translate(-50%,-50%);`,e}function zt(o,e=""){const t=document.createElement("div");return t.textContent=e,t.style.cssText=`background:var(--ml-ui-bg, rgba(255,255,255,0.95));color:${pe(o)};font-size:13px;font-family:sans-serif;font-weight:500;padding:3px 14px;border-radius:20px;pointer-events:none;transform:translate(-50%,-50%);white-space:nowrap;box-shadow:var(--ml-ui-shadow, 0 1px 4px rgba(0,0,0,0.2));`,t}function Vt(o){const e=document.createElement("div");return e.style.cssText=`position:fixed;background:var(--ml-ui-bg, rgba(255,255,255,0.95));color:${pe(o)};font-size:13px;font-family:sans-serif;font-weight:500;padding:3px 14px;border-radius:20px;pointer-events:none;transform:translate(-50%,-50%);white-space:nowrap;box-shadow:var(--ml-ui-shadow, 0 1px 4px rgba(0,0,0,0.2));z-index:99999;display:none;`,document.body.appendChild(e),e}function No(o){const e=document.createElement("div");return e.style.cssText=`position:fixed;width:12px;height:12px;border-radius:50%;background:${pe(o)};border:2px solid var(--ml-ui-border, #fff);box-sizing:border-box;pointer-events:none;transform:translate(-50%,-50%);z-index:99999;`,document.body.appendChild(e),e}function ss(o){const e=document.createElement("div");return e.style.cssText=`position:fixed;width:10px;height:10px;border:2px solid ${pe(o)};background:transparent;pointer-events:none;box-sizing:border-box;transform:translate(-50%,-50%);z-index:99998;display:none;`,document.body.appendChild(e),e}function Je(o){const e=document.createElement("canvas");return e.style.cssText="position:absolute;pointer-events:none;z-index:1;",o.appendChild(e),e}const zo=o=>new u.AcGeBox3d(o.min,o.max),Vo=o=>new u.AcGeBox2d(o.min,o.max),Go=o=>new y.Box3(o.min,o.max),Ko=o=>new u.AcGeBox2d(o.min,o.max),Uo=o=>new y.Box2(o.min,o.max),$o=o=>new u.AcGeBox2d(o.min,o.max),Wo=o=>{const e=new y.Box3;return e.min.set(o.min.x,o.min.y,0),e.max.set(o.max.x,o.max.y,0),e},qi={threeBo2dToGeBox2d:Ko,geBox2dToThreeBox2d:Uo,threeBox3dToGeBox3d:zo,geBox3dToThreeBox3d:Go,goBox3dToGeBox2d:Vo,threeBox3dToGeBox2d:$o,geBox2dToThreeBox3d:Wo};function Wh(){return new Promise(o=>{requestAnimationFrame(()=>{requestAnimationFrame(()=>o())})})}function Ho(o,e,t){const i=e.x-o.x,n=e.y-o.y,s=t.x-o.x,r=t.y-o.y,a=i*s+n*r,c=i*r-n*s;return Math.atan2(Math.abs(c),a)*180/Math.PI}const Hh=o=>(o%(2*Math.PI)+2*Math.PI)%(2*Math.PI);function rs(o,e,t,i,n){const s=e.canvas.getBoundingClientRect(),r=window.devicePixelRatio||1,a=Math.round(s.width),c=Math.round(s.height),l=e.canvasToContainer({x:0,y:0});o.style.left=`${l.x}px`,o.style.top=`${l.y}px`,o.style.width=`${a}px`,o.style.height=`${c}px`,(o.width!==a*r||o.height!==c*r)&&(o.width=a*r,o.height=c*r);const h=o.getContext("2d");if(!h)return;h.clearRect(0,0,o.width,o.height),h.save(),h.scale(r,r);const d=e.worldToScreen(t),p=e.worldToScreen(i);h.beginPath(),h.moveTo(d.x,d.y),h.lineTo(p.x,p.y),h.strokeStyle=pe(n),h.lineWidth=2,h.setLineDash([8,5]),h.stroke(),h.setLineDash([]),h.restore()}function Yo(o,e,t,i,n,s){const r=e.canvas.getBoundingClientRect(),a=window.devicePixelRatio||1,c=Math.round(r.width),l=Math.round(r.height),h=e.canvasToContainer({x:0,y:0});o.style.left=`${h.x}px`,o.style.top=`${h.y}px`,o.style.width=`${c}px`,o.style.height=`${l}px`,(o.width!==c*a||o.height!==l*a)&&(o.width=c*a,o.height=l*a);const d=o.getContext("2d");if(!d)return;d.clearRect(0,0,o.width,o.height),d.save(),d.scale(a,a);const p=e.worldToScreen(t),m=e.worldToScreen(i),f=e.worldToScreen(n),w=Math.hypot(m.x-p.x,m.y-p.y),x=Math.hypot(f.x-p.x,f.y-p.y),b=Math.max(Math.min(w,x)*.3,15),v=Math.atan2(m.y-p.y,m.x-p.x),C=Math.atan2(f.y-p.y,f.x-p.x),P=Hh(C-v)>Math.PI;d.beginPath(),d.arc(p.x,p.y,b,v,C,P),d.strokeStyle=pe(s),d.lineWidth=2,d.stroke(),d.restore()}class Yh extends ${constructor(e,t,i){super(e),this._line=new u.AcDbLine(t,t),this._line.color=i,this._line.lineWeight=u.AcGiLineWeight.LineWeight070}get entity(){return this._line}update(e){this._line.endPoint=e}}class Xh extends ${constructor(e,t,i,n,s,r){super(e),this._vertex=i,this._arm1=n,this._view=e,this._canvas=s,this._color=r,this._db=t,this._line=new u.AcDbLine(i,i),this._line.color=r,this._line.lineWeight=u.AcGiLineWeight.LineWeight070,this._badge=Vt(r)}get entity(){return this._line}update(e){this._line.endPoint=e,rs(this._canvas,this._view,this._vertex,this._arm1,this._color);const t=Ho(this._vertex,this._arm1,e);this._badge.textContent=this._db.formatter.formatAngle(t*Math.PI/180,{showUnits:!0,showApproximate:!0,applyAngbaseAngdir:!1}),this._badge.style.display="block";const i=this._view.canvas.getBoundingClientRect(),n=this._view.worldToScreen(this._vertex);this._badge.style.left=`${n.x+i.left}px`,this._badge.style.top=`${n.y+i.top-30}px`}end(){super.end(),this._badge.remove()}}class Xo extends j{constructor(){super(),this.mode=R.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Nt(i);await e.view.withMode(oe.SELECTION,()=>t.withCursor(be.Crosshair,async()=>{const s=new D(g.t("jig.measureAngle.vertex")),r=await t.getPoint(s);if(r.status!==S.OK)return;const a=r.value,c=new D(g.t("jig.measureAngle.arm1"));c.useBasePoint=!0,c.jig=new Yh(e.view,a,n);const l=await t.getPoint(c);if(l.status!==S.OK)return;const h=l.value,d=Je(e.view.container);rs(d,e.view,a,h,n);const p=()=>rs(d,e.view,a,h,n);e.view.events.viewChanged.addEventListener(p);const m=new D(g.t("jig.measureAngle.arm2"));m.jig=new Xh(e.view,i,a,h,d,n);let f;try{const Ge=await t.getPoint(m);if(Ge.status!==S.OK){e.view.events.viewChanged.removeEventListener(p),d.remove();return}f=Ge.value}catch{e.view.events.viewChanged.removeEventListener(p),d.remove();return}e.view.events.viewChanged.removeEventListener(p),d.remove();const w=Ho(a,h,f),x=new u.AcDbLine(a,h);x.color=n,x.lineWeight=u.AcGiLineWeight.LineWeight070,e.view.addTransientEntity(x);const b=new u.AcDbLine(a,f);b.color=n,b.lineWeight=u.AcGiLineWeight.LineWeight070,e.view.addTransientEntity(b);const v=Je(e.view.container);Yo(v,e.view,a,h,f,n);const C=()=>Yo(v,e.view,a,h,f,n);e.view.events.viewChanged.addEventListener(C);const P=e.view.htmlTransientManager,L=`angle-${Date.now()}`;P.add(`${L}-dotV`,Ee(n),a,"measurement"),P.add(`${L}-dot1`,Ee(n),h,"measurement"),P.add(`${L}-dot2`,Ee(n),f,"measurement");const M=h.x-a.x,k=h.y-a.y,E=f.x-a.x,T=f.y-a.y,F=Math.hypot(M,k),O=Math.hypot(E,T),z=F>0?M/F:1,U=F>0?k/F:0,V=O>0?E/O:1,G=O>0?T/O:0;let K=z+V,W=U+G;const te=Math.hypot(K,W);te>0?(K/=te,W/=te):(K=-U,W=z);const Ae=Math.max(Math.min(F,O)*.4,Math.max(F,O)*.15),bt={x:a.x+K*Ae,y:a.y+W*Ae};P.add(`${L}-badge`,zt(n,i.formatter.formatAngle(w*Math.PI/180,{showUnits:!0,applyAngbaseAngdir:!1})),bt,"measurement"),pt(()=>{e.view.removeTransientEntity(x.objectId),e.view.removeTransientEntity(b.objectId),v.remove(),e.view.events.viewChanged.removeEventListener(C),P.remove(`${L}-dotV`),P.remove(`${L}-dot1`),P.remove(`${L}-dot2`),P.remove(`${L}-badge`)})}))}}class qh extends ${constructor(e,t,i,n){super(e),this._line=new u.AcDbLine(t,t),this._line.color=i,this._line.lineWeight=u.AcGiLineWeight.LineWeight070,this._onMove=n}get entity(){return this._line}update(e){this._line.endPoint=e,this._onMove(e)}}function Zh(o,e,t,i){const n=e.x-o.x,s=e.y-o.y,r=i.x-t.x,a=i.y-t.y,c=n*a-s*r;if(Math.abs(c)<1e-10)return!1;const l=t.x-o.x,h=t.y-o.y,d=(l*a-h*r)/c,p=(l*s-h*n)/c;return d>0&&d<1&&p>0&&p<1}function qo(o){let e=0;const t=o.length;for(let i=0;i<t;i++){const n=(i+1)%t;e+=o[i].x*o[n].y,e-=o[n].x*o[i].y}return Math.abs(e)/2}function Zo(o){const e=o.reduce((i,n)=>i+n.x,0)/o.length,t=o.reduce((i,n)=>i+n.y,0)/o.length;return{x:e,y:t}}function Jo(o,e,t,i){const n=e.canvas.getBoundingClientRect(),s=window.devicePixelRatio||1,r=Math.round(n.width),a=Math.round(n.height),c=e.canvasToContainer({x:0,y:0});o.style.left=`${c.x}px`,o.style.top=`${c.y}px`,o.style.width=`${r}px`,o.style.height=`${a}px`,(o.width!==r*s||o.height!==a*s)&&(o.width=r*s,o.height=a*s);const l=o.getContext("2d");if(!l||t.length<3)return;l.clearRect(0,0,o.width,o.height),l.save(),l.scale(s,s);const h=t.map(d=>e.worldToScreen(d));l.beginPath(),l.moveTo(h[0].x,h[0].y);for(let d=1;d<h.length;d++)l.lineTo(h[d].x,h[d].y);l.closePath(),l.fillStyle=ns(i,.2),l.fill(),l.strokeStyle=pe(i),l.lineWidth=2.5,l.stroke(),l.restore()}class Qo extends j{constructor(){super(),this.mode=R.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Nt(i),s=[],r=Je(e.view.container),a=Vt(n);await e.view.withMode(oe.SELECTION,()=>t.withCursor(be.Crosshair,async()=>{const c=v=>{const C=e.view.canvas.getBoundingClientRect(),P=window.devicePixelRatio||1,L=Math.round(C.width),M=Math.round(C.height),k=e.view.canvasToContainer({x:0,y:0});r.style.left=`${k.x}px`,r.style.top=`${k.y}px`,r.style.width=`${L}px`,r.style.height=`${M}px`,(r.width!==L*P||r.height!==M*P)&&(r.width=L*P,r.height=M*P);const E=r.getContext("2d");if(!E||s.length<1)return;E.clearRect(0,0,r.width,r.height),E.save(),E.scale(P,P);const T=s.map(O=>e.view.worldToScreen(O)),F=v?[...T,e.view.worldToScreen(v)]:T;if(F.length>=3){E.beginPath(),E.moveTo(F[0].x,F[0].y);for(let O=1;O<F.length;O++)E.lineTo(F[O].x,F[O].y);E.closePath(),E.fillStyle=ns(n,.2),E.fill()}if(T.length>=2){E.beginPath(),E.moveTo(T[0].x,T[0].y);for(let O=1;O<T.length;O++)E.lineTo(T[O].x,T[O].y);E.strokeStyle=pe(n),E.lineWidth=2.5,E.setLineDash([8,5]),E.stroke(),E.setLineDash([])}E.restore()},l=()=>c();e.view.events.viewChanged.addEventListener(l);const h=await t.getPoint(new D(g.t("jig.measureArea.firstPoint")));if(h.status!==S.OK)return;const d=h.value;s.push(d),c();try{for(;s.length<50;){const v=new D(g.t("jig.measureArea.nextPoint"));v.useBasePoint=!0,v.allowNone=!0;const C=M=>{if(s.length<2)return;const k=[...s,M],E=qo(k);a.textContent=`${i.formatter.formatLength(E,{showUnits:!0,showApproximate:!0})}²`,a.style.display="";const T=Zo(k),F=e.view.canvas.getBoundingClientRect(),O=e.view.worldToScreen(T);a.style.left=`${O.x+F.left}px`,a.style.top=`${O.y+F.top}px`,c(M)};v.jig=new qh(e.view,s[s.length-1],n,C);const P=await t.getPoint(v);if(P.status!==S.OK)break;const L=P.value;if(a.style.display="none",s.length>=3){const M=e.view.worldToScreen(L),k=E=>{const T=e.view.worldToScreen(E),F=M.x-T.x,O=M.y-T.y;return F*F+O*O<=14*14};if(k(s[0])||k(s[s.length-1]))break}if(s.length>=3){const M=s[s.length-1];let k=!1;for(let E=0;E<s.length-2;E++)if(Zh(M,L,s[E],s[E+1])){k=!0;break}if(k)break}s.push(L),c()}}catch{}if(a.remove(),e.view.events.viewChanged.removeEventListener(l),r.remove(),s.length<3)return;const p=qo(s),m=Je(e.view.container);Jo(m,e.view,s,n);const f=()=>Jo(m,e.view,s,n);e.view.events.viewChanged.addEventListener(f);const w=e.view.htmlTransientManager,x=`area-${Date.now()}`,b=Zo(s);w.add(`${x}-badge`,zt(n,`${i.formatter.formatLength(p,{showUnits:!0,showApproximate:!0})}²`),b,"measurement"),s.forEach((v,C)=>{w.add(`${x}-dot${C}`,Ee(n),v,"measurement")}),pt(()=>{m.remove(),e.view.events.viewChanged.removeEventListener(f),w.remove(`${x}-badge`),s.forEach((v,C)=>{w.remove(`${x}-dot${C}`)})})}))}}function os(o,e){const t=Math.atan2(o.y-e.cy,o.x-e.cx);return{x:e.cx+e.r*Math.cos(t),y:e.cy+e.r*Math.sin(t),z:0}}function ea(o,e,t){const i=Math.atan2(o.y-t.cy,o.x-t.cx),n=Math.atan2(e.y-t.cy,e.x-t.cx),r=(a=>(a%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(n-i);return Math.min(r,2*Math.PI-r)*t.r}function ta(o,e,t){const i=Math.atan2(o.y-t.cy,o.x-t.cx),n=Math.atan2(e.y-t.cy,e.x-t.cx),r=(c=>(c%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(n-i),a=r<=Math.PI?i+r/2:i-(2*Math.PI-r)/2;return{x:t.cx+t.r*Math.cos(a),y:t.cy+t.r*Math.sin(a),z:0}}function Zi(o,e,t,i,n,s){const r=e.canvas.getBoundingClientRect(),a=window.devicePixelRatio||1,c=Math.round(r.width),l=Math.round(r.height),h=e.canvasToContainer({x:0,y:0});o.style.left=`${h.x}px`,o.style.top=`${h.y}px`,o.style.width=`${c}px`,o.style.height=`${l}px`,(o.width!==c*a||o.height!==l*a)&&(o.width=c*a,o.height=l*a);const d=o.getContext("2d");if(!d)return;d.clearRect(0,0,o.width,o.height),d.save(),d.scale(a,a);const p=e.worldToScreen({x:t.cx,y:t.cy}),m=e.worldToScreen(i),f=e.worldToScreen(n),w=Math.hypot(m.x-p.x,m.y-p.y),x=Math.atan2(m.y-p.y,m.x-p.x),b=Math.atan2(f.y-p.y,f.x-p.x),P=(L=>(L%(2*Math.PI)+2*Math.PI)%(2*Math.PI))(b-x)>Math.PI;d.beginPath(),d.arc(p.x,p.y,w,x,b,P),d.strokeStyle=pe(s),d.lineWidth=4,d.stroke(),d.restore()}class Jh extends ${constructor(e,t,i){super(e.view),this._ctx=e,this._onSnap=i;const n={x:0,y:0,z:0};this._dummy=new u.AcDbLine(n,n),this._indicator=ss(t)}get entity(){return this._dummy}update(e){const t=this._ctx.view.pick(e),i=this._ctx.doc.database.tables.blockTable.modelSpace;let n=null,s=Number.MAX_VALUE;for(const r of t){const a=i.getIdAt(r.id);let c=null;if(a instanceof u.AcDbCircle?c={cx:a.center.x,cy:a.center.y,r:a.radius}:a instanceof u.AcDbArc&&(c={cx:a.center.x,cy:a.center.y,r:a.radius}),c){const l=Math.hypot(e.x-c.cx,e.y-c.cy),h=Math.abs(l-c.r);h<s&&(s=h,n=c)}}if(n){const r=os(e,n),a=this._ctx.view.worldToScreen(e),c=this._ctx.view.worldToScreen(r);if(Math.hypot(a.x-c.x,a.y-c.y)<=20){const h=this._ctx.view.canvas.getBoundingClientRect();this._indicator.style.left=`${c.x+h.left}px`,this._indicator.style.top=`${c.y+h.top}px`,this._indicator.style.display="block",this._onSnap(n,r);return}}this._indicator.style.display="none",this._onSnap(null,null)}end(){super.end(),this._indicator.remove()}}class Qh extends ${constructor(e,t,i,n){super(e.view),this._ctx=e,this._geom=t,this._onMove=n;const s={x:0,y:0,z:0};this._dummy=new u.AcDbLine(s,s),this._indicator=ss(i),this._indicator.style.display="block"}get entity(){return this._dummy}update(e){const t=os(e,this._geom),i=this._ctx.view.canvas.getBoundingClientRect(),n=this._ctx.view.worldToScreen(t);this._indicator.style.left=`${n.x+i.left}px`,this._indicator.style.top=`${n.y+i.top}px`,this._onMove(t)}end(){super.end(),this._indicator.remove()}}class ia extends j{constructor(){super(),this.mode=R.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Nt(i),s=Je(e.view.container);await e.view.withMode(oe.SELECTION,()=>t.withCursor(be.Crosshair,async()=>{let r=null,a=null;const c=new Jh(e,n,(O,z)=>{r=O,a=z}),l=new D(g.t("jig.measureArc.startPoint"));l.jig=c;try{if((await t.getPoint(l)).status!==S.OK){s.remove();return}}catch{s.remove();return}if(!r||!a){s.remove();return}const h=r,d=a,p=No(n),m=Vt(n),f=()=>{const O=e.view.canvas.getBoundingClientRect(),z=e.view.worldToScreen(d);p.style.left=`${z.x+O.left}px`,p.style.top=`${z.y+O.top}px`};f();const w=()=>Zi(s,e.view,h,d,d,n),x=()=>{f(),w()};e.view.events.viewChanged.addEventListener(x);const b=O=>{Zi(s,e.view,h,d,O,n);const z=ea(d,O,h);m.textContent=i.formatter.formatLength(z,{showUnits:!0,showApproximate:!0}),m.style.display="";const U=ta(d,O,h),V=e.view.canvas.getBoundingClientRect(),G=e.view.worldToScreen(U);m.style.left=`${G.x+V.left}px`,m.style.top=`${G.y+V.top}px`,f()},v=new D(g.t("jig.measureArc.endPoint"));v.jig=new Qh(e,h,n,b);let C;try{const O=await t.getPoint(v);if(O.status!==S.OK){s.remove(),p.remove(),m.remove(),e.view.events.viewChanged.removeEventListener(x);return}C=O.value}catch{s.remove(),p.remove(),m.remove(),e.view.events.viewChanged.removeEventListener(x);return}m.remove(),p.remove(),e.view.events.viewChanged.removeEventListener(x),s.remove();const P=os(C,h),L=ea(d,P,h),M=ta(d,P,h),k=Je(e.view.container);Zi(k,e.view,h,d,P,n);const E=()=>Zi(k,e.view,h,d,P,n);e.view.events.viewChanged.addEventListener(E);const T=e.view.htmlTransientManager,F=`arc-${Date.now()}`;T.add(`${F}-dot1`,Ee(n),d,"measurement"),T.add(`${F}-dot2`,Ee(n),P,"measurement"),T.add(`${F}-badge`,zt(n,i.formatter.formatLength(L,{showUnits:!0,showApproximate:!0})),M,"measurement"),pt(()=>{k.remove(),e.view.events.viewChanged.removeEventListener(E),T.remove(`${F}-dot1`),T.remove(`${F}-dot2`),T.remove(`${F}-badge`)})}))}}function na(o,e){const t=e.x-o.x,i=e.y-o.y;return Math.sqrt(t*t+i*i)}class sa extends ${constructor(e,t,i,n){super(e),this._p1=i,this._view=e,this._db=t,this._line=new u.AcDbLine(i,i),this._line.color=n,this._line.lineWeight=u.AcGiLineWeight.LineWeight070,this._badge=Vt(n)}get entity(){return this._line}update(e){this._line.endPoint=e;const t=na(this._p1,e);if(t<1e-4){this._badge.style.display="none";return}this._badge.textContent=this._db.formatter.formatLength(t,{showUnits:!0,showApproximate:!0}),this._badge.style.display="block";const i={x:(this._p1.x+e.x)/2,y:(this._p1.y+e.y)/2},n=this._view.canvas.getBoundingClientRect(),s=this._view.worldToScreen(i);this._badge.style.left=`${s.x+n.left}px`,this._badge.style.top=`${s.y+n.top}px`}end(){super.end(),this._badge.remove()}}class ra extends j{constructor(){super(),this.mode=R.Read}async execute(e){const t=e.view.editor,i=e.doc.database,n=Nt(i);await e.view.withMode(oe.SELECTION,()=>t.withCursor(be.Crosshair,async()=>{const s=new D(g.t("jig.measureDistance.firstPoint")),r=await t.getPoint(s);if(r.status!==S.OK)return;const a=r.value,c=new D(g.t("jig.measureDistance.secondPoint"));c.useBasePoint=!0,c.jig=new sa(e.view,i,a,n);const l=await t.getPoint(c);if(l.status!==S.OK)return;const h=l.value,d=na(a,h),p=new u.AcDbLine(a,h);p.color=n,p.lineWeight=u.AcGiLineWeight.LineWeight070,e.view.addTransientEntity(p);const m=e.view.htmlTransientManager,f=`dist-${Date.now()}`,w={x:(a.x+h.x)/2,y:(a.y+h.y)/2};m.add(`${f}-dot1`,Ee(n),a,"measurement"),m.add(`${f}-dot2`,Ee(n),h,"measurement"),m.add(`${f}-badge`,zt(n,i.formatter.formatLength(d,{showUnits:!0,showApproximate:!0})),w,"measurement"),pt(()=>{e.view.removeTransientEntity(p.objectId),m.remove(`${f}-dot1`),m.remove(`${f}-dot2`),m.remove(`${f}-badge`)})}))}}class as extends ${constructor(e,t,i,n=1,s=!1){super(e),this._view=e,this._basePoint=new u.AcGePoint3d(i),this._copyCount=Math.max(0,n),this._fitMode=s,this._previewItems=[];for(let r=1;r<=this._copyCount;r++)t.map(a=>a.clone()).filter(a=>!!a).forEach(a=>{this._previewItems.push({entity:a,factor:r,lastDisplacement:new u.AcGePoint3d(0,0,0)})})}get entity(){var e;return((e=this._previewItems[0])==null?void 0:e.entity)??null}update(e){if(this._previewItems.length===0)return;const t=new u.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z);this._previewItems.forEach(i=>{const n=this.scaleDisplacement(t,i.factor),s=new u.AcGePoint3d(n.x-i.lastDisplacement.x,n.y-i.lastDisplacement.y,n.z-i.lastDisplacement.z);s.x===0&&s.y===0&&s.z===0||(i.entity.transformBy(new u.AcGeMatrix3d().makeTranslation(s.x,s.y,s.z)),i.lastDisplacement=n)})}render(){this._previewItems.length!==0&&this._view.addTransientEntity(this._previewItems.map(e=>e.entity))}end(){this._previewItems.forEach(e=>this._view.removeTransientEntity(e.entity.objectId))}scaleDisplacement(e,t){const i=this._fitMode&&this._copyCount>0?t/this._copyCount:t;return new u.AcGePoint3d(e.x*i,e.y*i,e.z*i)}}const Jt=class Jt extends j{constructor(){super(),this.mode=R.Review}addKeyword(e,t){e.keywords.add(g.t(`jig.copy.keywords.${t}.display`),g.t(`jig.copy.keywords.${t}.global`),g.t(`jig.copy.keywords.${t}.local`))}computeDisplacement(e,t){return new u.AcGePoint3d(t.x-e.x,t.y-e.y,t.z-e.z)}scaleDisplacement(e,t,i,n){const s=n&&i>0?t/i:t;return new u.AcGePoint3d(e.x*s,e.y*s,e.z*s)}buildCopies(e,t,i=1,n=!1){const s=[];for(let r=1;r<=i;r++){const a=e.map(h=>h.clone()).filter(h=>!!h),c=this.scaleDisplacement(t,r,i,n),l=new u.AcGeMatrix3d().makeTranslation(c.x,c.y,c.z);a.forEach(h=>h.transformBy(l)),s.push(...a)}return s}async promptCopyMode(e){const t=new X(`${g.t("jig.copy.modePrompt")} <${e}>`);t.allowNone=!0,this.addKeyword(t,"single"),this.addKeyword(t,"multiple");const i=await A.instance.editor.getKeywords(t);if(i.status===S.None)return e;if(i.status!==S.OK)return;const n=i.stringResult??"";return n==="Single"||n==="Multiple"?n:e}async promptArrayPlacement(e,t,i){const n=new Pn(g.t("jig.copy.arrayItemCount"),2);n.lowerLimit=2,n.allowNegative=!1,n.allowZero=!1;const s=await A.instance.editor.getInteger(n);if(s.status!==S.OK)return;const r=s.value??2,a=Math.max(1,r-1);for(;;){const c=new D(g.t("jig.copy.arraySecondPointOrFit"));this.addKeyword(c,"fit"),c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=i,c.jig=new as(e.view,t,i,a);const l=await A.instance.editor.getPoint(c);if(l.status===S.OK)return{copyCount:a,endPoint:new u.AcGePoint3d(l.value),fitMode:!1};if(l.status===S.Keyword&&l.stringResult==="Fit"){const h=new D(g.t("jig.copy.arrayFitSecondPoint"));h.useBasePoint=!0,h.useDashedLine=!0,h.basePoint=i,h.jig=new as(e.view,t,i,a,!0);const d=await A.instance.editor.getPoint(h);if(d.status===S.OK)return{copyCount:a,endPoint:new u.AcGePoint3d(d.value),fitMode:!0}}return}}async executeCopyLoop(e,t,i,n,s=!1){const r=e.doc.database.tables.blockTable;for(;;){const a=new D(g.t(s?"jig.copy.displacementOrArray":"jig.copy.secondPointOrArray"));this.addKeyword(a,"array"),a.useBasePoint=!0,a.useDashedLine=!0,a.basePoint=i,a.allowNone=n==="Multiple",a.jig=new as(e.view,t,i);const c=await A.instance.editor.getPoint(a);if(c.status===S.OK){const l=this.buildCopies(t,this.computeDisplacement(i,c.value));if(l.length>0&&r.modelSpace.appendEntity(l),n==="Single")return;continue}if(c.status===S.Keyword&&c.stringResult==="Array"){const l=await this.promptArrayPlacement(e,t,i);if(!l)continue;const h=this.buildCopies(t,this.computeDisplacement(i,l.endPoint),l.copyCount,l.fitMode);if(h.length>0&&r.modelSpace.appendEntity(h),n==="Single")return;continue}return}}async execute(e){var d;const t=e.view.selectionSet,i=new fe(e.doc.database),n=e.doc.database.tables.blockTable,s=t.count>0?t.ids:((d=(await A.instance.editor.getSelection(new Re(g.sysCmdPrompt("copy")))).value)==null?void 0:d.ids)??[];if(s.length===0)return;const r=e.doc.openMode==R.Review?i.filterAnnotationEntities(s):s;if(r.length===0){t.clear();return}const a=r.map(p=>n.getEntityById(p)).filter(p=>!!p);if(a.length===0){t.clear();return}let c=Jt._defaultMode,l,h=!1;for(;!l;){const p=new D(g.t("jig.copy.basePointOrOptions"));p.allowNone=!0,this.addKeyword(p,"displacement"),this.addKeyword(p,"mode"),c!=="Multiple"&&this.addKeyword(p,"multiple");const m=await A.instance.editor.getPoint(p);if(m.status===S.OK){l=new u.AcGePoint3d(m.value);break}if(m.status===S.None){l=new u.AcGePoint3d(0,0,0),h=!0;break}if(m.status!==S.Keyword){t.clear();return}const f=m.stringResult??"";if(f==="Displacement"){l=new u.AcGePoint3d(0,0,0),h=!0;break}if(f==="Multiple"){c="Multiple";continue}if(f!=="Mode"){t.clear();return}const w=await this.promptCopyMode(c);if(!w){t.clear();return}c=w,Jt._defaultMode=w}await this.executeCopyLoop(e,a,l,c,h),t.clear()}};Jt._defaultMode="Multiple";let Ji=Jt;class oa extends j{constructor(){super(),this.mode=R.Review}async execute(e){const t=e.view.selectionSet,i=new fe(e.doc.database);if(t.count>0){const n=e.doc.openMode==R.Review?i.filterAnnotationEntities(t.ids):t.ids;e.doc.database.tables.blockTable.removeEntity(n),t.clear()}else{const n=g.sysCmdPrompt("erase"),s=new Re(n),r=await A.instance.editor.getSelection(s);if(r.status===S.OK&&r.value&&r.value.count>0){let a=r.value.ids;e.doc.openMode==R.Review&&(a=i.filterAnnotationEntities(a)),e.doc.database.tables.blockTable.removeEntity(a),t.clear()}}}}class aa extends ${constructor(e,t,i){super(e),this._view=e,this._basePoint=new u.AcGePoint3d(i),this._lastDisplacement=new u.AcGePoint3d(0,0,0),this._previewEntities=t.map(n=>this.cloneEntity(n)).filter(n=>!!n)}get entity(){return this._previewEntities[0]??null}update(e){if(this._previewEntities.length===0)return;const t=new u.AcGePoint3d(e.x-this._basePoint.x,e.y-this._basePoint.y,e.z-this._basePoint.z),i=new u.AcGePoint3d(t.x-this._lastDisplacement.x,t.y-this._lastDisplacement.y,t.z-this._lastDisplacement.z);if(!(i.x!==0||i.y!==0||i.z!==0))return;const s=new u.AcGeMatrix3d().makeTranslation(i.x,i.y,i.z);this._previewEntities.forEach(r=>r.transformBy(s)),this._lastDisplacement=t}render(){this._previewEntities.length!==0&&this._view.addTransientEntity(this._previewEntities)}end(){this._previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}cloneEntity(e){return e.clone()}}class ca extends j{constructor(){super(),this.mode=R.Review}async execute(e){var x;const t=e.view.selectionSet,i=new fe(e.doc.database),n=e.doc.database.tables.blockTable,s=t.count>0?t.ids:((x=(await A.instance.editor.getSelection(new Re(g.sysCmdPrompt("move")))).value)==null?void 0:x.ids)??[];if(s.length===0)return;const r=e.doc.openMode==R.Review?i.filterAnnotationEntities(s):s;if(r.length===0){t.clear();return}const a=r.map(b=>n.getEntityById(b)).filter(b=>!!b);if(a.length===0){t.clear();return}let c,l;const h=b=>{b.keywords.add(g.t("jig.move.keywords.displacement.display"),g.t("jig.move.keywords.displacement.global"),g.t("jig.move.keywords.displacement.local"))};class d{constructor(v){this.machine=v}buildPrompt(){const v=new D(g.t("jig.move.basePointOrDisplacement"));return h(v),v}async handleResult(v){return v.status===S.OK?(c=new u.AcGePoint3d(v.value),this.machine.setState(new p(this.machine)),"continue"):v.status===S.Keyword&&v.stringResult==="Displacement"?(this.machine.setState(new m),"continue"):"finish"}}class p{constructor(v){this.machine=v}buildPrompt(){const v=new D(g.t("jig.move.secondPointOrDisplacement"));return h(v),c&&(v.useBasePoint=!0,v.useDashedLine=!0,v.basePoint=c,v.jig=new aa(e.view,a,c)),v}async handleResult(v){if(v.status===S.OK&&c){const C=new u.AcGePoint3d(v.value);return l=new u.AcGePoint3d(C.x-c.x,C.y-c.y,C.z-c.z),"finish"}return v.status===S.Keyword&&v.stringResult==="Displacement"?(this.machine.setState(new m),"continue"):"finish"}}class m{buildPrompt(){const v=new D(g.t("jig.move.displacement"));return v.useBasePoint=!0,v.useDashedLine=!0,v.basePoint=new u.AcGePoint3d(0,0,0),v.jig=new aa(e.view,a,v.basePoint),v}async handleResult(v){return v.status===S.OK&&(l=new u.AcGePoint3d(v.value)),"finish"}}const f=new Te;if(f.setState(new d(f)),await f.run(b=>A.instance.editor.getPoint(b)),!l){t.clear();return}const w=new u.AcGeMatrix3d().makeTranslation(l.x,l.y,l.z);r.forEach(b=>{const v=n.getEntityById(b);v&&(v.transformBy(w),v.triggerModifiedEvent())}),t.clear()}}function eu(o){return o instanceof u.AcDbCurve}function tu(o,e){e.layer=o.layer,e.color=o.color.clone(),e.lineType=o.lineType,e.lineWeight=o.lineWeight,e.linetypeScale=o.linetypeScale,e.transparency=o.transparency,e.visibility=o.visibility}function la(o,e,t){try{const i=o.getOffsetSideAtPoint(t),n=o.getOffsetCurves(e*i);return n.forEach(s=>tu(o,s)),n}catch{return[]}}class iu extends ${constructor(e,t,i){super(e),this._previewCurves=[],this._renderedIds=[],this._view=e,this._curve=t,this._distance=i}get entity(){return this._previewCurves[0]??null}update(e){this.clearRendered(),this._previewCurves=la(this._curve,this._distance,e)}render(){this._previewCurves.length!==0&&(this._view.addTransientEntity(this._previewCurves),this._renderedIds=this._previewCurves.map(e=>e.objectId))}end(){this.clearRendered()}clearRendered(){this._renderedIds.forEach(e=>this._view.removeTransientEntity(e)),this._renderedIds=[]}}class Gt extends j{constructor(){super(),this.mode=R.Review}async execute(e){const t=e.doc.database.tables.blockTable,i=new fe(e.doc.database);let n,s;class r{constructor(d){this.machine=d}buildPrompt(){const d=Gt._lastDistance,p=d!=null?`${g.t("jig.offset.distance")} <${d}>`:g.t("jig.offset.distance"),m=new ue(p);return m.useBasePoint=!1,m.useDashedLine=!0,m.allowZero=!1,m.allowNegative=!1,d!=null&&(m.defaultValue=d,m.useDefaultValue=!0,m.allowNone=!0),m}handleResult(d){return!(d instanceof se)||d.status!==S.OK||d.value==null?"finish":!Number.isFinite(d.value)||u.AcGeTol.isNonPositive(d.value)?(A.instance.editor.showMessage(g.t("jig.offset.invalidDistance"),"warning"),"finish"):(n=d.value,Gt._lastDistance=d.value,this.machine.setState(new a(this.machine)),"continue")}}class a{constructor(d){this.machine=d}buildPrompt(){const d=new Le(g.t("jig.offset.selectObject"));return d.allowNone=!0,d.allowObjectOnLockedLayer=!0,d.setRejectMessage(g.t("jig.offset.invalidSelection")),d}handleResult(d){if(!(d instanceof vi)||d.status===S.None||d.status!==S.OK||!d.objectId)return"finish";const p=e.doc.openMode==R.Review?i.filterAnnotationEntities([d.objectId]):[d.objectId],m=t.getEntityById(p[0]);return eu(m)?(s=m,this.machine.setState(new c(this.machine)),"continue"):(A.instance.editor.showMessage(g.t("jig.offset.invalidSelection"),"warning"),"continue")}}class c{constructor(d){this.machine=d}buildPrompt(){const d=new D(g.t("jig.offset.sidePoint"));if(d.allowNone=!0,d.disableOSnap=!0,s&&n!=null){const p=new iu(e.view,s,n);p.update({...e.view.curPos,z:0}),p.render(),d.jig=p}return d}handleResult(d){if(!(d instanceof Si)||d.status!==S.OK||!d.value||!s||n==null)return"finish";const p=la(s,n,new u.AcGePoint3d(d.value));return p.length===0?A.instance.editor.showMessage(g.t("jig.offset.offsetFailed"),"warning"):t.modelSpace.appendEntity(p),s=void 0,this.machine.setState(new a(this.machine)),"continue"}}const l=new Te;l.setState(new r(l)),await l.run(h=>h instanceof ue?A.instance.editor.getDistance(h):h instanceof Le?A.instance.editor.getEntity(h):A.instance.editor.getPoint(h))}}class Qi extends ${constructor(e,t){super(e),this._view=e,this._previewEntities=t.map(i=>i.clone()).filter(i=>!!i)}get entity(){return this._previewEntities[0]??null}update(e){}render(){this._previewEntities.length!==0&&this._view.addTransientEntity(this._previewEntities)}end(){this._previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}}class ha extends ${constructor(e,t,i,n=0){super(e),this._lastAngleRad=0,this._view=e,this._basePoint=new u.AcGePoint3d(i),this._referenceAngleDeg=n,this._previewEntities=t.map(s=>s.clone()).filter(s=>!!s)}get entity(){return this._previewEntities[0]??null}update(e){if(this._previewEntities.length===0)return;const t=(e-this._referenceAngleDeg)*Math.PI/180,i=t-this._lastAngleRad;if(u.AcGeTol.equalToZero(i))return;const n=Kt.createRotationMatrix(this._basePoint,i);this._previewEntities.forEach(s=>s.transformBy(n)),this._lastAngleRad=t}render(){this._previewEntities.length!==0&&this._view.addTransientEntity(this._previewEntities)}end(){this._previewEntities.forEach(e=>this._view.removeTransientEntity(e.objectId))}}class Kt extends j{constructor(){super(),this.mode=R.Review}static createRotationMatrix(e,t){return new u.AcGeMatrix3d().makeTranslation(e.x,e.y,e.z).multiply(new u.AcGeMatrix3d().makeRotationZ(t)).multiply(new u.AcGeMatrix3d().makeTranslation(-e.x,-e.y,-e.z))}addKeyword(e,t){e.keywords.add(g.t(`jig.rotate.keywords.${t}.display`),g.t(`jig.rotate.keywords.${t}.global`),g.t(`jig.rotate.keywords.${t}.local`))}warnInvalidInput(e){ee.emit("message",{message:g.t(`jig.rotate.invalid.${e}`),type:"warning"})}computeAngleDeg(e,t){const i=t.x-e.x,n=t.y-e.y;if(u.AcGeTol.isPositive(Math.hypot(i,n)))return Math.atan2(n,i)*180/Math.PI}async promptReferenceAngle(e,t,i){for(;;){const n=new ve(g.t("jig.rotate.referenceAngleOrPoints"));this.addKeyword(n,"points"),n.useBasePoint=!0,n.useDashedLine=!0,n.basePoint=i,n.allowNegative=!0,n.allowZero=!0,n.useDefaultValue=!0,n.defaultValue=0,n.jig=new Qi(e.view,t);const s=await A.instance.editor.getAngle(n);if(s.status===S.OK)return s.value??0;if(s.status===S.Keyword&&s.stringResult==="Points"){const r=new D(g.t("jig.rotate.firstReferencePoint"));r.jig=new Qi(e.view,t);const a=await A.instance.editor.getPoint(r);if(a.status!==S.OK)return;const c=new D(g.t("jig.rotate.secondReferencePoint"));c.useBasePoint=!0,c.useDashedLine=!0,c.basePoint=new u.AcGePoint3d(a.value),c.jig=new Qi(e.view,t);const l=await A.instance.editor.getPoint(c);if(l.status!==S.OK)return;const h=this.computeAngleDeg(a.value,l.value);if(h==null){this.warnInvalidInput("referencePoints");continue}return h}return}}async promptRotationAngle(e,t,i){let n=!1;for(;;){const s=new ve(g.t("jig.rotate.rotationAngleOrOptions"));this.addKeyword(s,"copy"),this.addKeyword(s,"reference"),s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=i,s.allowNegative=!0,s.allowZero=!0,s.jig=new ha(e.view,t,i);const r=await A.instance.editor.getAngle(s);if(r.status===S.OK)return{copyMode:n,angleRad:(r.value??0)*Math.PI/180};if(r.status!==S.Keyword)return;const a=r.stringResult??"";if(a==="Copy"){n=!0;continue}if(a!=="Reference")return;const c=await this.promptReferenceAngle(e,t,i);if(c==null)return;const l=new ve(g.t("jig.rotate.newAngle"));l.useBasePoint=!0,l.useDashedLine=!0,l.basePoint=i,l.allowNegative=!0,l.allowZero=!0,l.jig=new ha(e.view,t,i,c);const h=await A.instance.editor.getAngle(l);return h.status!==S.OK?void 0:{copyMode:n,angleRad:((h.value??0)-c)*Math.PI/180}}}async execute(e){var m;const t=e.view.selectionSet,i=new fe(e.doc.database),n=e.doc.database.tables.blockTable,s=t.count>0?t.ids:((m=(await A.instance.editor.getSelection(new Re(g.sysCmdPrompt("rotate")))).value)==null?void 0:m.ids)??[];if(s.length===0)return;const r=e.doc.openMode==R.Review?i.filterAnnotationEntities(s):s;if(r.length===0){t.clear();return}const a=r.map(f=>n.getEntityById(f)).filter(f=>!!f);if(a.length===0){t.clear();return}const c=new D(g.t("jig.rotate.basePoint"));c.jig=new Qi(e.view,a);const l=await A.instance.editor.getPoint(c);if(l.status!==S.OK){t.clear();return}const h=new u.AcGePoint3d(l.value),d=await this.promptRotationAngle(e,a,h);if(!d){t.clear();return}const p=Kt.createRotationMatrix(h,d.angleRad);if(d.copyMode){const f=a.map(w=>w.clone()).filter(w=>!!w);f.forEach(w=>w.transformBy(p)),f.length>0&&n.modelSpace.appendEntity(f)}else a.forEach(f=>{f.transformBy(p),f.triggerModifiedEvent()});t.clear()}}class mt extends j{constructor(){super(),this.mode=R.Review,this._isShowEntityDrawStyleToolbar=!0}get isShowEntityDrawStyleToolbar(){return this._isShowEntityDrawStyleToolbar}set isShowEntityDrawStyleToolbar(e){this._isShowEntityDrawStyleToolbar=e}onCommandWillStart(e){const t=e.doc.database,i=new fe(t);this._previousLayer=t.clayer,this._previousCecolor=t.cecolor.toString(),this._previousCelweight=t.celweight,this._revisionLayer=i.getAnnotationLayer(),t.clayer=this._revisionLayer}onCommandEnded(e){const t=e.doc.database;this._previousLayer&&(t.clayer=this._previousLayer),this._previousCecolor&&(t.cecolor=u.AcCmColor.fromString(this._previousCecolor)??new u.AcCmColor),this._previousCelweight&&(t.celweight=this._previousCelweight),this._previousLayer=void 0,this._revisionLayer=void 0}}const nu=8;function su(o,e,t){const i=o.worldToScreen(t),n=new u.AcGePoint2d(i.x+e,i.y),s=o.screenToWorld(n);return Math.abs(s.x-t.x)}function ua(o,e,t,i){o.reset(!1);const n=Math.min(e.x,t.x),s=Math.max(e.x,t.x),r=Math.min(e.y,t.y),a=Math.max(e.y,t.y),c=s-n,l=a-r,h=new u.AcGePoint2d((n+s)/2,(r+a)/2),p=su(i,nu,h),m=Math.max(4,Math.ceil(c/p)*2),f=Math.max(4,Math.ceil(l/p)*2),w=[],x=[];let b=0;const v=C=>C?.4:-.4;for(let C=0;C<=m;C++){const P=C/m,L=n+c*P,M=r;if(w.push(new u.AcGePoint2d(L,M)),C<m){const k=b%2===0;x.push(v(k)),b++}else x.push(void 0)}for(let C=1;C<=f;C++){const P=C/f,L=s,M=r+l*P;if(w.push(new u.AcGePoint2d(L,M)),C<f){const k=b%2===0;x.push(v(k)),b++}else x.push(void 0)}for(let C=1;C<=m;C++){const P=1-C/m,L=n+c*P,M=a;if(w.push(new u.AcGePoint2d(L,M)),C<m){const k=b%2===0;x.push(v(k)),b++}else x.push(void 0)}for(let C=1;C<f;C++){const P=1-C/f,L=n,M=r+l*P;if(w.push(new u.AcGePoint2d(L,M)),C<f-1){const k=b%2===0;x.push(v(k)),b++}else x.push(void 0)}for(let C=0;C<w.length;C++){const P=x[C];o.addVertexAt(C,w[C],P)}o.closed=!0}class da extends ${constructor(e,t){super(e),this._cloud=new u.AcDbPolyline,this._firstPoint=new u.AcGePoint2d(t),this._view=e}get entity(){return this._cloud}update(e){ua(this._cloud,this._firstPoint,e,this._view)}}class ga extends mt{constructor(){super(),this.mode=R.Review}async execute(e){const t=new D(g.t("jig.line.firstPoint")),i=await A.instance.editor.getPoint(t);if(i.status!==S.OK)return;const n=i.value,s=new D(g.t("jig.line.nextPoint"));s.jig=new da(e.view,n),s.useDashedLine=!1,s.useBasePoint=!0;const r=await A.instance.editor.getPoint(s);if(r.status!==S.OK)return;const a=r.value,c=e.doc.database,l=new u.AcDbPolyline;ua(l,n,a,e.view),c.tables.blockTable.modelSpace.appendEntity(l)}}class pa extends mt{constructor(){super(),this.mode=R.Review}async execute(e){const t=new D(g.t("jig.circle.center")),i=await A.instance.editor.getPoint(t);if(i.status!==S.OK)return;const n=i.value,s=new ue(g.t("jig.circle.radius"));s.allowZero=!1,s.useBasePoint=!0,s.useDashedLine=!0,s.basePoint=new u.AcGePoint3d(n),s.jig=new zi(e.view,n);const r=await A.instance.editor.getDistance(s);if(r.status!==S.OK)return;const a=r.value;e.doc.database.tables.blockTable.modelSpace.appendEntity(new u.AcDbCircle(n,a))}}function ma(o,e,t){o.reset(!1),o.addVertexAt(0,new u.AcGePoint2d(e)),o.addVertexAt(1,new u.AcGePoint2d(t.x,e.y)),o.addVertexAt(2,new u.AcGePoint2d(t)),o.addVertexAt(3,new u.AcGePoint2d(e.x,t.y)),o.closed=!0}class ru extends ${constructor(e,t){super(e),this._rect=new u.AcDbPolyline,this._firstPoint=new u.AcGePoint2d(t)}get entity(){return this._rect}update(e){ma(this._rect,this._firstPoint,e)}}class fa extends mt{constructor(){super(),this.mode=R.Review}async execute(e){const t=new D(g.t("jig.rect.firstPoint")),i=await A.instance.editor.getPoint(t);if(i.status!==S.OK)return;const n=i.value,s=new D(g.t("jig.rect.nextPoint"));s.jig=new ru(e.view,n),s.useDashedLine=!1,s.useBasePoint=!0;const r=await A.instance.editor.getPoint(s);if(r.status!==S.OK)return;const a=r.value,c=e.doc.database,l=new u.AcDbPolyline;ma(l,n,a),c.tables.blockTable.modelSpace.appendEntity(l)}}class ya extends mt{constructor(){super(),this.mode=R.Review,this.isShowEntityDrawStyleToolbar=!1}async execute(e){const t=e.doc.database,n=new fe(t).getAnnotationLayer();if(n){const s=t.tables.layerTable.getAt(n);s&&(s.isOff=!s.isOff)}}}const ou=.1;function wa(o,e){const t=e.x-o.x,i=e.y-o.y;return Math.sqrt(t*t+i*i)}class ba extends ${constructor(e,t){super(e),this._lastPoint=null,this._polyline=new u.AcDbPolyline,this._points=[new u.AcGePoint2d(t)],this._lastPoint=new u.AcGePoint2d(t),this._polyline.addVertexAt(0,this._points[0])}get entity(){return this._polyline}get points(){return this._points}update(e){if(this._lastPoint===null)return;const t=new u.AcGePoint2d(e);wa(this._lastPoint,t)>=ou&&(this._points.push(t),this._lastPoint=t,this._polyline.addVertexAt(this._points.length,t))}}class va extends mt{constructor(){super(),this.mode=R.Review}async execute(e){const t=new D(g.t("jig.sketch.firstPoint")),i=await A.instance.editor.getPoint(t);if(i.status!==S.OK)return;const n=i.value,s=new ba(e.view,n),r=new D(g.t("jig.sketch.nextPoint"));r.jig=s,r.useDashedLine=!1,r.useBasePoint=!0;const a=await A.instance.editor.getPoint(r);if(a.status!==S.OK)return;const c=a.value,l=s.points,h=l[l.length-1],d=new u.AcGePoint2d(c);wa(h,d)>.01&&l.push(d);const p=e.doc.database,m=new u.AcDbPolyline;for(let f=0;f<l.length;f++)m.addVertexAt(f,l[f]);p.tables.blockTable.modelSpace.appendEntity(m)}}class xa extends j{async execute(e){this.printSelectionSet(e),this.printStats(e),this.printPerformanceData()}printSelectionSet(e){const t=e.doc.database.tables.blockTable.modelSpace;e.view.selectionSet.ids.forEach(i=>{const n=t.getIdAt(i);n&&u.log.info(n)})}printStats(e){const t=e.view.stats,i=t.layouts;u.log.info("Geometry information in current drawing:");for(let n=0;n<i.length;++n){console.group(`Layout: ${n}`);const s=i[n],r=[0,0,0,0,0,0,0],a=[0,0,0,0,0,0,0];let c=0;const l=s.layers.map(h=>(r[0]=h.line.indexed.geometrySize/1024,r[1]=h.line.nonIndexed.geometrySize/1024,r[2]=h.mesh.indexed.geometrySize/1024,r[3]=h.mesh.nonIndexed.geometrySize/1024,r[4]=h.point.indexed.geometrySize/1024,r[5]=h.point.nonIndexed.geometrySize/1024,r[6]=h.unbatched.geometrySize/1024,a[0]+=r[0],a[1]+=r[1],a[2]+=r[2],a[3]+=r[3],a[4]+=r[4],a[5]+=r[5],a[6]+=r[6],c+=h.unbatched.count,{name:h.name,"idx line (KB)":r[0].toFixed(1),"line (KB)":r[1].toFixed(1),"idx mesh (KB)":r[2].toFixed(1),"mesh (KB)":r[3].toFixed(1),"idx point (KB)":r[4].toFixed(1),"point (KB)":r[5].toFixed(1),"unbatched (KB)":r[6].toFixed(1),"unbatched count":h.unbatched.count,"unbatched line":h.unbatched.byType.line,"unbatched mesh":h.unbatched.byType.mesh,"unbatched point":h.unbatched.byType.point,"unbatched other":h.unbatched.byType.other,"total geo (KB)":(h.summary.totalGeometrySize/1024).toFixed(1),"total mapping (KB)":(h.summary.totalMappingSize/1024).toFixed(1)}));l.push({name:"total","idx line (KB)":a[0].toFixed(1),"line (KB)":a[1].toFixed(1),"idx mesh (KB)":a[2].toFixed(1),"mesh (KB)":a[3].toFixed(1),"idx point (KB)":a[4].toFixed(1),"point (KB)":a[5].toFixed(1),"unbatched (KB)":a[6].toFixed(1),"unbatched count":c,"unbatched line":s.summary.totalSize.unbatchedByType.line,"unbatched mesh":s.summary.totalSize.unbatchedByType.mesh,"unbatched point":s.summary.totalSize.unbatchedByType.point,"unbatched other":s.summary.totalSize.unbatchedByType.other,"total geo (KB)":(s.summary.totalSize.geometry/1024).toFixed(1),"total mapping (KB)":(s.summary.totalSize.mapping/1024).toFixed(1)}),console.table(l),console.table([{layoutCount:t.summary.layoutCount,entityCount:t.summary.entityCount,"scene line (KB)":(t.summary.totalSize.line/1024).toFixed(1),"scene mesh (KB)":(t.summary.totalSize.mesh/1024).toFixed(1),"scene point (KB)":(t.summary.totalSize.point/1024).toFixed(1),"scene unbatched (KB)":(t.summary.totalSize.unbatched/1024).toFixed(1),"scene unbatched count":t.summary.totalSize.unbatchedCount,"scene unbatched line":t.summary.totalSize.unbatchedByType.line,"scene unbatched mesh":t.summary.totalSize.unbatchedByType.mesh,"scene unbatched point":t.summary.totalSize.unbatchedByType.point,"scene unbatched other":t.summary.totalSize.unbatchedByType.other,"scene total geo (KB)":(t.summary.totalSize.geometry/1024).toFixed(1),"scene total mapping (KB)":(t.summary.totalSize.mapping/1024).toFixed(1)}]),console.groupEnd()}}printPerformanceData(){u.AcCmPerformanceCollector.getInstance().printAll()}}class Sa extends j{async execute(e){ee.emit("open-file",{})}}class Aa extends j{async execute(e){const t=A.instance.baseUrl;A.instance.openUrl(t+"templates/acadiso.dxf")}}class Ca extends j{async execute(){A.instance.regen()}}class Pa extends j{async execute(e){e.view.mode=oe.SELECTION,e.view.setCursor(be.Crosshair)}}class _a extends j{constructor(){super(),this.mode=R.Review}async execute(e){const t=u.AcDbSysVarManager.instance(),i=t.getVar(this.globalName,e.doc.database),n=g.t("jig.sysvar.prompt").trim(),s=n.match(/([::])\s*$/),r=(s==null?void 0:s[1])??":",a=s?n.slice(0,s.index).trimEnd():n,c=i==null?"":` <${String(i)}>`,l=`${a}${c}${r}`,h=new le(l),d=await A.instance.editor.getString(h);if(d.status!==S.OK||!d.stringResult)return;const p=d.stringResult;t.getDescriptor(this.globalName)&&t.setVar(this.globalName,p,e.doc.database)}}class La extends j{async execute(e){const t=e.doc.database,i=e.view,n=i.activeLayoutBtrId===i.modelSpaceBtrId,s=Sn(n),r=u.AcDbSysVarManager.instance();if(!r.getDescriptor(s))return;const c=r.getVar(s,t);r.setVar(s,Xs(c),t)}}class Qe extends j{captureCurrentViewBox(e){const t=e.view.screenToWorld({x:0,y:0}),i=e.view.screenToWorld({x:e.view.width,y:e.view.height});return new u.AcGeBox2d().expandByPoint(t).expandByPoint(i)}rememberViewBeforeZoom(e){Qe.previousViewBox=this.captureCurrentViewBox(e)}zoomToExtents(e){this.rememberViewBeforeZoom(e),e.view.zoomToFitDrawing()}zoomToWindow(e,t,i){const n=new u.AcGeBox2d().expandByPoint(t).expandByPoint(i);this.rememberViewBeforeZoom(e),e.view.zoomTo(n,1)}async promptAndZoomWindowFromFirstCorner(e,t){const i=new D(g.t("jig.zoom.secondCorner"));i.useBasePoint=!0,i.basePoint=new u.AcGePoint3d(t),i.useDashedLine=!0;const n=await A.instance.editor.getPoint(i);n.status!==S.OK||!n.value||this.zoomToWindow(e,t,n.value)}async promptAndZoomWindowByBox(e){const t=new yi(g.t("jig.zoom.firstCorner"),g.t("jig.zoom.secondCorner")),i=await A.instance.editor.getBox(t);i.status!==S.OK||!i.value||(this.rememberViewBeforeZoom(e),e.view.zoomTo(i.value,1))}async runCenter(e){const t=new D(g.t("jig.zoom.centerPoint")),i=await A.instance.editor.getPoint(t);if(i.status!==S.OK||!i.value)return;const n=new le(g.t("jig.zoom.heightOrScale")),s=await A.instance.editor.getString(n);if(s.status!==S.OK||!s.stringResult)return;const r=this.parseScaleFactor(s.stringResult);if(r!=null){this.applyRelativeScale(e,r,i.value);return}const a=Number(s.stringResult);if(!Number.isFinite(a)||a<=0)return;const c=e.view.width/Math.max(e.view.height,1),l=a/2,h=a*c/2,d=new u.AcGeBox2d().expandByPoint({x:i.value.x-h,y:i.value.y-l}).expandByPoint({x:i.value.x+h,y:i.value.y+l});this.rememberViewBeforeZoom(e),e.view.zoomTo(d,1)}parseScaleFactor(e){const t=e.trim().toLowerCase();if(!t)return;if(t.endsWith("xp")){const n=Number(t.slice(0,-2));return Number.isFinite(n)&&n>0?n:void 0}if(t.endsWith("x")){const n=Number(t.slice(0,-1));return Number.isFinite(n)&&n>0?n:void 0}const i=Number(t);return Number.isFinite(i)&&i>0?i:void 0}applyRelativeScale(e,t,i){const n=this.captureCurrentViewBox(e),s=Math.max(n.max.x-n.min.x,u.FLOAT_TOL),r=Math.max(n.max.y-n.min.y,u.FLOAT_TOL),a=s/(2*t),c=r/(2*t),l=i??{x:(n.min.x+n.max.x)/2,y:(n.min.y+n.max.y)/2},h=new u.AcGeBox2d().expandByPoint({x:l.x-a,y:l.y-c}).expandByPoint({x:l.x+a,y:l.y+c});this.rememberViewBeforeZoom(e),e.view.zoomTo(h,1)}runPrevious(e){if(!Qe.previousViewBox)return;const t=this.captureCurrentViewBox(e);e.view.zoomTo(Qe.previousViewBox,1),Qe.previousViewBox=t}async execute(e){const t=new D(g.t("jig.zoom.mainPrompt"));t.allowNone=!0,t.keywords.add(g.t("jig.zoom.keywords.all.display"),g.t("jig.zoom.keywords.all.global"),g.t("jig.zoom.keywords.all.local")),t.keywords.add(g.t("jig.zoom.keywords.center.display"),g.t("jig.zoom.keywords.center.global"),g.t("jig.zoom.keywords.center.local")),t.keywords.add(g.t("jig.zoom.keywords.extents.display"),g.t("jig.zoom.keywords.extents.global"),g.t("jig.zoom.keywords.extents.local")),t.keywords.add(g.t("jig.zoom.keywords.previous.display"),g.t("jig.zoom.keywords.previous.global"),g.t("jig.zoom.keywords.previous.local")),t.keywords.add(g.t("jig.zoom.keywords.scale.display"),g.t("jig.zoom.keywords.scale.global"),g.t("jig.zoom.keywords.scale.local")),t.keywords.add(g.t("jig.zoom.keywords.window.display"),g.t("jig.zoom.keywords.window.global"),g.t("jig.zoom.keywords.window.local"));const i=await A.instance.editor.getPoint(t);if(i.status===S.None){this.zoomToExtents(e);return}if(i.status===S.OK&&i.value){await this.promptAndZoomWindowFromFirstCorner(e,i.value);return}if(i.status!==S.Keyword)return;const n=i.stringResult??"";if(n==="All"||n==="Extents"){this.zoomToExtents(e);return}if(n==="Window"){await this.promptAndZoomWindowByBox(e);return}if(n==="Center"){await this.runCenter(e);return}if(n==="Scale"){const s=new le(g.t("jig.zoom.scaleFactor")),r=await A.instance.editor.getString(s);if(r.status!==S.OK||!r.stringResult)return;const a=this.parseScaleFactor(r.stringResult);if(a==null)return;this.applyRelativeScale(e,a);return}n==="Previous"&&this.runPrevious(e)}}class Ta extends j{async execute(e){e.view.mode=oe.PAN,e.view.setCursor(be.Grab)}}class Ia{constructor(e,t){this._plugins=new Map,this._lazyRegistrations=new Map,this._triggerToPluginName=new Map,this._lazyLoadPromises=new Map,this._context=e,this._commandManager=t}async loadPlugin(e){const t=e.name;if(!t)throw new Error("[AcApPluginManager] Plugin name is required");if(this._plugins.has(t))throw new Error(`[AcApPluginManager] Plugin '${t}' is already loaded`);try{await e.onLoad(this._context,this._commandManager)}catch(i){throw new Error(`[AcApPluginManager] Failed to load plugin '${t}': ${i}`)}this._plugins.set(t,e)}registerLazyPlugin(e){const t=e.name;if(!t)throw new Error("[AcApPluginManager] Lazy plugin name is required");if(this._lazyRegistrations.has(t))throw new Error(`[AcApPluginManager] Lazy plugin '${t}' is already registered`);if(!e.triggers.length)throw new Error(`[AcApPluginManager] Lazy plugin '${t}' requires at least one trigger`);this._lazyRegistrations.set(t,e);for(const i of e.triggers){const n=i.trim().toUpperCase();if(n){if(this._triggerToPluginName.has(n))throw new Error(`[AcApPluginManager] Trigger '${i}' is already registered to lazy plugin '${this._triggerToPluginName.get(n)}'`);this._triggerToPluginName.set(n,t)}}}isLazyPluginTrigger(e){return this._triggerToPluginName.has(e.trim().toUpperCase())}getLazyPluginTriggers(){return Array.from(this._triggerToPluginName.keys())}async loadByTrigger(e){const t=e.trim().toUpperCase(),i=this._triggerToPluginName.get(t);if(!i)return!1;if(this.isPluginLoaded(i))return!0;const n=this._lazyLoadPromises.get(i);if(n)return n;const s=this._lazyRegistrations.get(i);if(!s)return!1;const r=(async()=>{try{const a=await s.loader();if(a.name!==i)throw new Error(`[AcApPluginManager] Lazy plugin '${i}' loader returned plugin '${a.name}'`);return this.isPluginLoaded(i)||await this.loadPlugin(a),!0}catch(a){return u.log.error(`[AcApPluginManager] Failed to load lazy plugin '${i}' for trigger '${e}':`,a),!1}finally{this._lazyLoadPromises.delete(i)}})();return this._lazyLoadPromises.set(i,r),r}async unloadPlugin(e){const t=this._plugins.get(e);if(!t)return!1;try{await t.onUnload(this._context,this._commandManager)}catch(i){u.log.error(`[AcApPluginManager] Error unloading plugin '${e}':`,i)}return this._plugins.delete(e),!0}isPluginLoaded(e){return this._plugins.has(e)}getPlugin(e){return this._plugins.get(e)}getLoadedPlugins(){return Array.from(this._plugins.keys())}async unloadAllPlugins(){const e=Array.from(this._plugins.keys());for(const t of e)await this.unloadPlugin(t)}async loadPluginsFromConfig(e,t){const i=(t==null?void 0:t.continueOnError)??!1,n=[],s=[];for(const r of e)try{const a=typeof r=="function"?r():r;await this.loadPlugin(a),n.push(a.name)}catch(a){const c=typeof r=="function"?"Unknown":r.name||"Unknown",l=a instanceof Error?a:new Error(String(a));if(s.push({name:c,error:l}),!i)throw l}return{loaded:n,failed:s}}async loadPluginsFromFolder(e,t){const i=(t==null?void 0:t.continueOnError)??!1,n=(t==null?void 0:t.pluginList)||[],s=[],r=[];if(n.length===0)return u.log.warn("[AcApPluginManager] No plugin list provided. Cannot load plugins from folder without a list of files."),{loaded:s,failed:r};const a=e.replace(/\/$/,""),c=a.startsWith("./")?a:`./${a}`;for(const l of n)try{const d=await import(`${c}/${l.replace(/^\//,"")}`);let p=d.default,m;if(!p){const w=l.replace(/\.(js|ts)$/,"");m=w.split(/[-_]/).map(x=>x.charAt(0).toUpperCase()+x.slice(1).toLowerCase()).join(""),p=d[m]||d.Plugin||d[w]}if(!p){const w=m||"Plugin";throw new Error(`No plugin export found in ${l}. Expected default export, or named export 'Plugin' or '${w}'.`)}let f;if(typeof p=="function"?p.prototype&&p.prototype.onLoad?f=new p:f=p():f=p,!f||typeof f.onLoad!="function")throw new Error(`Invalid plugin in ${l}. Plugin must implement AcApPlugin interface.`);await this.loadPlugin(f),s.push(f.name)}catch(h){const d=h instanceof Error?h:new Error(String(h));if(r.push({name:l,error:d}),!i)throw d}return{loaded:s,failed:r}}}class au{constructor(){this.items=new Map}insert(e){this.items.set(e.id,e)}load(e){for(const t of e)this.items.set(t.id,t)}remove(e){this.items.delete(e.id)}removeById(e){this.items.delete(e)}clear(){this.items.clear()}search(e){const t=[];for(const i of this.items.values())Ea(i,e)&&t.push(i);return t}collides(e){for(const t of this.items.values())if(Ea(t,e))return!0;return!1}all(){return Array.from(this.items.values())}}function Ea(o,e){return!(o.maxX<e.minX||o.minX>e.maxX||o.maxY<e.minY||o.minY>e.maxY)}function ka(o,e,t=0,i=o.length-1,n=cu){for(;i>t;){if(i-t>600){const c=i-t+1,l=e-t+1,h=Math.log(c),d=.5*Math.exp(2*h/3),p=.5*Math.sqrt(h*d*(c-d)/c)*(l-c/2<0?-1:1),m=Math.max(t,Math.floor(e-l*d/c+p)),f=Math.min(i,Math.floor(e+(c-l)*d/c+p));ka(o,e,m,f,n)}const s=o[e];let r=t,a=i;for(Ut(o,t,e),n(o[i],s)>0&&Ut(o,t,i);r<a;){for(Ut(o,r,a),r++,a--;n(o[r],s)<0;)r++;for(;n(o[a],s)>0;)a--}n(o[t],s)===0?Ut(o,t,a):(a++,Ut(o,a,i)),a<=e&&(t=a+1),e<=a&&(i=a-1)}}function Ut(o,e,t){const i=o[e];o[e]=o[t],o[t]=i}function cu(o,e){return o<e?-1:o>e?1:0}class lu{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(!tn(e,t))return i;const n=this.toBBox,s=[];for(;t;){for(let r=0;r<t.children.length;r++){const a=t.children[r],c=t.leaf?n(a):a;tn(e,c)&&(t.leaf?i.push(a):ls(e,c)?this._all(a,i):s.push(a))}t=s.pop()}return i}collides(e){let t=this.data;if(!tn(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(tn(e,r)){if(t.leaf||ls(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=yt([]),this}remove(e,t){if(!e)return this;let i=this.data;const n=this.toBBox(e),s=[],r=[];let a,c,l;for(;i||s.length;){if(i||(i=s.pop(),c=s[s.length-1],a=r.pop(),l=!0),i.leaf){const h=hu(e,i.children,t);if(h!==-1)return i.children.splice(h,1),s.push(i),this._condense(s),this}!l&&!i.leaf&&ls(i,n)?(s.push(i),r.push(a),a=0,c=i,i=i.children[0]):c?(a++,i=c.children[a],l=!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,a;if(s<=r)return a=yt(e.slice(t,i+1)),ft(a,this.toBBox),a;n||(n=Math.ceil(Math.log(s)/Math.log(r)),r=Math.ceil(s/Math.pow(r,n-1))),a=yt([]),a.leaf=!1,a.height=n;const c=Math.ceil(s/r),l=c*Math.ceil(Math.sqrt(r));Ba(e,t,i,l,this.compareMinX);for(let h=t;h<=i;h+=l){const d=Math.min(h+l-1,i);Ba(e,h,d,c,this.compareMinY);for(let p=h;p<=d;p+=c){const m=Math.min(p+c-1,d);a.children.push(this._build(e,p,m,n-1))}}return ft(a,this.toBBox),a}_chooseSubtree(e,t,i,n){for(;n.push(t),!(t.leaf||n.length-1===i);){let s=1/0,r=1/0,a;for(let c=0;c<t.children.length;c++){const l=t.children[c],h=cs(l),d=gu(e,l)-h;d<r?(r=d,s=h<s?h:s,a=l):d===r&&h<s&&(s=h,a=l)}t=a||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),Wt(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),a=yt(i.children.splice(r,i.children.length-r));a.height=i.height,a.leaf=i.leaf,ft(i,this.toBBox),ft(a,this.toBBox),t?e[t-1].children.push(a):this._splitRoot(i,a)}_splitRoot(e,t){this.data=yt([e,t]),this.data.height=e.height+1,this.data.leaf=!1,ft(this.data,this.toBBox)}_chooseSplitIndex(e,t,i){let n,s=1/0,r=1/0;for(let a=t;a<=i-t;a++){const c=$t(e,0,a,this.toBBox),l=$t(e,a,i,this.toBBox),h=pu(c,l),d=cs(c)+cs(l);h<s?(s=h,n=a,r=d<r?d:r):h===s&&d<r&&(r=d,n=a)}return n||i-t}_chooseSplitAxis(e,t,i){const n=e.leaf?this.compareMinX:uu,s=e.leaf?this.compareMinY:du,r=this._allDistMargin(e,t,i,n),a=this._allDistMargin(e,t,i,s);r<a&&e.children.sort(n)}_allDistMargin(e,t,i,n){e.children.sort(n);const s=this.toBBox,r=$t(e,0,t,s),a=$t(e,i-t,i,s);let c=en(r)+en(a);for(let l=t;l<i-t;l++){const h=e.children[l];Wt(r,e.leaf?s(h):h),c+=en(r)}for(let l=i-t-1;l>=t;l--){const h=e.children[l];Wt(a,e.leaf?s(h):h),c+=en(a)}return c}_adjustParentBBoxes(e,t,i){for(let n=i;n>=0;n--)Wt(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():ft(e[t],this.toBBox)}}function hu(o,e,t){if(!t)return e.indexOf(o);for(let i=0;i<e.length;i++)if(t(o,e[i]))return i;return-1}function ft(o,e){$t(o,0,o.children.length,e,o)}function $t(o,e,t,i,n){n||(n=yt(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=o.children[s];Wt(n,o.leaf?i(r):r)}return n}function Wt(o,e){return o.minX=Math.min(o.minX,e.minX),o.minY=Math.min(o.minY,e.minY),o.maxX=Math.max(o.maxX,e.maxX),o.maxY=Math.max(o.maxY,e.maxY),o}function uu(o,e){return o.minX-e.minX}function du(o,e){return o.minY-e.minY}function cs(o){return(o.maxX-o.minX)*(o.maxY-o.minY)}function en(o){return o.maxX-o.minX+(o.maxY-o.minY)}function gu(o,e){return(Math.max(e.maxX,o.maxX)-Math.min(e.minX,o.minX))*(Math.max(e.maxY,o.maxY)-Math.min(e.minY,o.minY))}function pu(o,e){const t=Math.max(o.minX,e.minX),i=Math.max(o.minY,e.minY),n=Math.min(o.maxX,e.maxX),s=Math.min(o.maxY,e.maxY);return Math.max(0,n-t)*Math.max(0,s-i)}function ls(o,e){return o.minX<=e.minX&&o.minY<=e.minY&&e.maxX<=o.maxX&&e.maxY<=o.maxY}function tn(o,e){return e.minX<=o.maxX&&e.minY<=o.maxY&&e.maxX>=o.minX&&e.maxY>=o.minY}function yt(o){return{children:o,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function Ba(o,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;ka(o,r,e,t,n),s.push(e,r,r,t)}}class Da{constructor(e){this.tree=new lu(e),this.idMap=new Map}insert(e){this.idMap.has(e.id)||(this.tree.insert(e),this.idMap.set(e.id,e))}load(e){this.tree.load(e)}remove(e,t){this.tree.remove(e,t),this.idMap.delete(e.id)}removeById(e){this.tree.remove({minX:0,minY:0,maxX:0,maxY:0,id:e},(t,i)=>t.id===i.id),this.idMap.delete(e)}clear(){this.tree.clear(),this.idMap.clear()}search(e){return this.tree.search(e)}collides(e){return this.tree.collides(e)}all(){return this.tree.all()}}const an=class an{constructor(e){this.childIndexes=new Map,this.rootIndex=e??new Da}setChildIndex(e,t){this.childIndexes.set(e,t)}removeChildIndex(e){this.childIndexes.delete(e)}insert(e){this.rootIndex.insert(e)}load(e){this.rootIndex.load(e)}remove(e,t){this.rootIndex.remove(e,t),this.childIndexes.delete(e.id)}removeById(e){this.rootIndex.removeById(e),this.childIndexes.delete(e)}clear(){this.rootIndex.clear(),this.childIndexes.forEach(e=>e.clear()),this.childIndexes.clear()}search(e){const t=this.rootIndex.search(e),i=[];for(const n of t){const s=this.childIndexes.get(n.id);if(!s){i.push(n);continue}const r=s.search(e);i.push({...n,children:r})}return i}collides(e){return this.rootIndex.collides(e)?this.rootIndex.search(e).some(i=>{const n=this.childIndexes.get(i.id);return n?n.collides(e):!0}):!1}all(){const e=[];for(const t of this.rootIndex.all()){const i=this.childIndexes.get(t.id);i?e.push(...i.all()):e.push(t)}return e}hasChildIndex(e){return this.childIndexes.has(e)}ensureChildIndex(e,t){if(this.hasChildIndex(e))return this.childIndexes.get(e);const i=this.createIndexBySize(t.length);if(i)return t.forEach(n=>i.insert(n)),this.setChildIndex(e,i),i}createChildIndex(e){return this.ensureChildIndex(e.objectId,e.boxes)}createIndexBySize(e){if(e>an.THRESHOLD)return new Da;if(e>0)return new au}};an.THRESHOLD=100;let hs=an;class mu{constructor(e){this._group=new Sc,this._name=e.name,this._box=new y.Box3,this._group.visible=!(e.isFrozen||e.isOff)}get name(){return this._name}set name(e){this._name=e}get box(){return this._box}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}update(e){this._name=e.name,this._group.visible=!(e.isFrozen||e.isOff)}updateMaterial(e,t){this._group.updateMaterial(e,t)}rerenderPoints(e){this._group.rerenderPoints(e)}hasEntity(e){return this._group.hasEntity(e)}addEntity(e,t=!0){this._group.addEntity(e);const i=e.box;t&&this._box.union(i)}isIntersectWith(e,t){return this._group.isIntersectWith(e,t)}removeEntity(e){return this._group.removeEntity(e)}updateEntity(e){if(!e.objectId)return!1;const t=this._group.removeEntity(e.objectId);return t&&this._group.addEntity(e),t}clear(){this._group.clear(),this._box.makeEmpty(),this._group.removeFromParent()}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 fu{constructor(){this._group=new y.Group,this._spatialIndex=new hs,this._box=new y.Box3,this._layers=new Map,this._isLoaded=!1}get internalObject(){return this._group}get layers(){return this._layers}get box(){return this._box}get isLoaded(){return this._isLoaded}set isLoaded(e){this._isLoaded=e}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,a=0,c=0;const l={line:0,mesh:0,point:0,other:0};return this._layers.forEach(h=>{const d=h.stats;e.push(d),n+=d.line.indexed.geometrySize+d.line.nonIndexed.geometrySize,s+=d.mesh.indexed.geometrySize+d.mesh.nonIndexed.geometrySize,r+=d.point.indexed.geometrySize+d.point.nonIndexed.geometrySize,a+=d.unbatched.geometrySize,c+=d.unbatched.count,l.line+=d.unbatched.byType.line,l.mesh+=d.unbatched.byType.mesh,l.point+=d.unbatched.byType.point,l.other+=d.unbatched.byType.other,t+=d.summary.totalGeometrySize,i+=d.summary.totalMappingSize}),{layers:e,summary:{entityCount:this.entityCount,totalSize:{line:n,mesh:s,point:r,unbatched:a,geometry:t,mapping:i,unbatchedCount:c,unbatchedByType:l}}}}clear(){return this._layers.forEach(e=>{e.clear()}),this._layers.clear(),this._box.makeEmpty(),this._spatialIndex.clear(),this}rerenderPoints(e){this._layers.forEach(t=>{t.rerenderPoints(e)})}isIntersectWith(e,t){const i=this.getLayersByObjectId(e);for(let n=0;n<i.length;++n){const s=i[n];if(s&&s.isIntersectWith(e,t))return!0}return!1}hasVisibleEntity(e){return this.getLayersByObjectId(e).some(t=>t.visible)}addEntity(e,t=!0){if(!e.objectId)throw new Error("Object id is required to add one entity!");if(!e.layerName)throw new Error("Layer name is required to add one entity!");const i=this._layers.get(e.layerName);if(!i)throw new Error(`layer '${e.layerName}' doesn't exist!`);i.addEntity(e);const n=e.box;t&&this._box.union(n),this._spatialIndex.insert({minX:n.min.x,minY:n.min.y,maxX:n.max.x,maxY:n.max.y,id:e.objectId});const s=this.getSpatialIndexChildBoxes(e);return s?this._spatialIndex.ensureChildIndex(e.objectId,s):e instanceof Ye&&this._spatialIndex.createChildIndex(e),this}removeEntity(e){let t=!1;for(const[i,n]of this._layers)n.removeEntity(e)&&(t=!0);return this._spatialIndex.removeById(e),t}updateEntity(e){for(const[t,i]of this._layers)if(i.updateEntity(e))return!0;return!1}getLayer(e){return this._layers.get(e)}addLayer(e){const t=e.name;let i=this._layers.get(t);return i===void 0&&(i=new mu(e),this._layers.set(t,i),this._group.add(i.internalObject)),i}updateLayer(e){const t=this._layers.get(e.name);return t&&t.update(e),t}hover(e){e.forEach(t=>{this.getLayersByObjectId(t).forEach(n=>n.hover([t]))})}unhover(e){e.forEach(t=>{this.getLayersByObjectId(t).forEach(n=>n.unhover([t]))})}select(e){e.forEach(t=>{this.getLayersByObjectId(t).forEach(n=>n.select([t]))})}unselect(e){e.forEach(t=>{this.getLayersByObjectId(t).forEach(n=>n.unselect([t]))})}search(e){return this._spatialIndex.search({minX:e.min.x,minY:e.min.y,maxX:e.max.x,maxY:e.max.y})}getLayersByObjectId(e){const t=[];for(const[i,n]of this._layers)n.hasEntity(e)&&t.push(n);return t}getSpatialIndexChildBoxes(e){const t=e.userData.spatialIndexChildBoxes;if(!(!t||t.length===0))return t}}class Ma{constructor(){this._scene=new y.Scene,this._transientManager=new Rs(this._scene),this._htmlTransientManager=new Fs(this._scene),this._layers=new Map,this._layouts=new Map,this._activeLayoutBtrId="",this._modelSpaceBtrId=""}get htmlTransientManager(){return this._htmlTransientManager}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=[];let t=0,i=0,n=0,s=0,r=0,a=0,c=0,l=0;const h={line:0,mesh:0,point:0,other:0};return this._layouts.forEach(d=>e.push(d.stats)),e.forEach(d=>{t+=d.summary.entityCount,i+=d.summary.totalSize.line,n+=d.summary.totalSize.mesh,s+=d.summary.totalSize.point,r+=d.summary.totalSize.unbatched,a+=d.summary.totalSize.geometry,c+=d.summary.totalSize.mapping,l+=d.summary.totalSize.unbatchedCount,h.line+=d.summary.totalSize.unbatchedByType.line,h.mesh+=d.summary.totalSize.unbatchedByType.mesh,h.point+=d.summary.totalSize.unbatchedByType.point,h.other+=d.summary.totalSize.unbatchedByType.other}),{layouts:e,summary:{layoutCount:e.length,entityCount:t,totalSize:{line:i,mesh:n,point:s,unbatched:r,geometry:a,mapping:c,unbatchedCount:l,unbatchedByType:h}}}}addEmptyLayout(e){const t=this._layouts.get(e);if(t)return t;const i=new fu;return this._layouts.set(e,i),this._scene.add(i.internalObject),i.visible=e==this._activeLayoutBtrId,this._layers.forEach(n=>{i.addLayer(n)}),i}clear(){return this._layouts.forEach(e=>{this._scene.remove(e.internalObject),e.clear()}),this._layouts.clear(),this._layers.clear(),this._transientManager.clear(),this._htmlTransientManager.clear(),this._scene.clear(),this._transientManager=new Rs(this._scene),this._htmlTransientManager=new Fs(this._scene),this}hover(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.hover(e)),!0)}unhover(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.unhover(e)),!0)}select(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.select(e)),!0)}unselect(e){return this._layouts.size===0?!1:(this._layouts.forEach(t=>t.unselect(e)),!0)}search(e){const t=this.activeLayout;return t?t==null?void 0:t.search(e):[]}addLayer(e){const t=[];return this._layers.set(e.name,e),this._layouts.forEach(i=>{const n=i.addLayer(e);n&&t.push(n)}),t}updateLayer(e){const t=[];return this._layers.set(e.name,e),this._layouts.forEach(i=>{const n=i.updateLayer(e);n&&t.push(n)}),t}addTransientEntity(e){this._transientManager.update(e)}removeTransientEntity(e){this._transientManager.remove(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 u.log.warn("[AcTrSecene] The owner id of one entity cannot be empty!");return this}removeEntity(e){for(const[t,i]of this._layouts)if(i.removeEntity(e))return!0;return!1}updateEntity(e){for(const[t,i]of this._layouts)if(i.updateEntity(e))return!0;return!1}}var nn=(o=>(o[o.LEFT_BOTTOM=0]="LEFT_BOTTOM",o[o.LEFT_TOP=1]="LEFT_TOP",o[o.RIGHT_TOP=2]="RIGHT_TOP",o[o.RIGHT_BOTTOM=4]="RIGHT_BOTTOM",o))(nn||{});class yu extends y.Object3D{constructor(e,t,i=150,n=2){super(),this.camera=e,this.renderer=t,this.gizmoCamera=new y.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 y.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,a=i-s;switch(n){case 0:r=0,a=0;break;case 1:r=0;break;case 4:a=0;break}return{x:r,y:a}}calculateViewportBbox(){const e=this.renderer.domElement,t=e.offsetWidth,i=e.offsetHeight,n=this.gizmoPos,s=this.gizmoDim,r=new y.Box2(new y.Vector2(t-s,0),new y.Vector2(t,s));switch(n){case 0:r.set(new y.Vector2(0,i-s),new y.Vector2(s,i));break;case 1:r.set(new y.Vector2(0,0),new y.Vector2(s,s));break;case 4:r.set(new y.Vector2(t-s,i-s),new y.Vector2(t,i));break}return r}}function wu(o,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",a=e.color?e.color.join(", "):"0, 0, 0, 1.0",c=document.createElement("canvas");c.width=n,c.height=s;const l=c.getContext("2d");if(l){l.font=`bold ${i}px ${t}`,l.fillStyle=`rgba(${r})`,l.fillRect(0,0,n,s);const p=l.measureText(o).width;l.fillStyle=`rgba(${a})`,l.fillText(o,n/2-p/2,s/2+i/2-2)}const h=new y.Texture(c);return h.minFilter=y.LinearFilter,h.needsUpdate=!0,h}function us(o){const e=wu(o,{fontSize:100,font:"Arial Narrow, sans-serif",color:[255,255,255,1],bgColor:[0,0,0,0]}),t=new y.SpriteMaterial({map:e,transparent:!0});return new y.Sprite(t)}nn.RIGHT_TOP;const bu={pos:nn.LEFT_BOTTOM,size:100,hasZAxis:!0};class vu extends yu{constructor(e,t,i){const n={...bu,...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 a=new y.BufferGeometry;a.setAttribute("position",new y.Float32BufferAttribute(s,3)),a.setAttribute("color",new y.Float32BufferAttribute(r,3));const c=new y.LineBasicMaterial({vertexColors:!0,toneMapped:!1});this.axes=new y.LineSegments(a,c),this.axes.position.set(-1,-1,-1),this.add(this.axes),this.xText=us("X"),this.xText.position.set(1.5,-1,-1),this.add(this.xText),this.yText=us("Y"),this.yText.position.set(-1,1.5,-1),this.add(this.yText),this.hasZAxis&&(this.zText=us("Z"),this.zText.position.set(-1,-1,1.5),this.add(this.zText))}setLineColors(e,t){const i=new y.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 xu extends Ws{constructor(e,t,i,n){super(e,i,n),this._layoutBtrId=t,this._mode=oe.SELECTION,this._axesGizmo=this.createAxesGizmo(),this._viewportViews=new Map}get layoutBtrId(){return this._layoutBtrId}get mode(){return this._mode}set mode(e){e==oe.SELECTION?this._cameraControls.mouseButtons={MIDDLE:y.MOUSE.PAN}:e==oe.PAN&&(this._cameraControls.mouseButtons={LEFT:y.MOUSE.PAN}),this._cameraControls.update(),this._mode=e}get viewportCount(){return this._viewportViews.size}get viewportViews(){return this._viewportViews.values()}get internalCamera(){return this._camera.internalCamera}get viewportsBoundingBox(){if(this._viewportViews.size===0)return;const e=new u.AcGeBox2d;return this._viewportViews.forEach(t=>{const i=t.viewport.box;e.expandByPoint(i.min),e.expandByPoint(i.max)}),e.isEmpty()?void 0:e}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 n;this._renderer.clear();const t=this._renderer.render(e.internalScene,this._camera),i=e.modelSpaceLayout;return i&&this.drawViewports(i.internalObject),(n=this._axesGizmo)==null||n.update(),t}createAxesGizmo(){return new vu(this._camera.internalCamera,this._renderer.internalRenderer,{hasZAxis:!1,pos:nn.LEFT_BOTTOM})}drawViewports(e){if(this._viewportViews.size>0){const t=this._renderer.autoClear;this._renderer.autoClear=!1;const i=new y.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 Su{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;return((t=this.activeLayoutView)==null?void 0:t.render(e))??!1}}function Au(o,e){return[...o].sort((t,i)=>Cu(t,i,e))}function Cu(o,e,t){const i=Oa(o)-Oa(e);if(Math.abs(i)>Number.EPSILON)return i;const n=Fa(t,o)-Fa(t,e);return Math.abs(n)>Number.EPSILON?n:0}function Oa(o){return Math.max(o.maxX-o.minX,0)*Math.max(o.maxY-o.minY,0)}function Fa(o,e){const t=o.x<e.minX?e.minX-o.x:o.x>e.maxX?o.x-e.maxX:0,i=o.y<e.minY?e.minY-o.y:o.y>e.maxY?o.y-e.maxY:0;return t*t+i*i}const ds={background:qe};class Ra extends Mr{constructor(e=ds){const t={...ds,...e},i=t.container??document.createElement("div");t.container=i;const n=new y.WebGLRenderer({antialias:!0,alpha:!0});i.appendChild(n.domElement),super(n.domElement,i),this._rafId=null,this._loadingLayouts=new Set,this._initializedLayouts=new Set,this.animate=()=>{var x;this._rafId=requestAnimationFrame(this.animate),this.events.renderFrame.dispatch({render:this._renderer,camera:this.internalCamera});const f=this._numOfEntitiesToProcess>0;if(!this._isDirty&&!f)return;const w=this._layoutViewManager.render(this._scene);this.internalCamera&&this._css2dRenderer.render(this._scene.internalScene,this.internalCamera),(x=this._stats)==null||x.update(),this._isDirty=f||w},e.calculateSizeCallback&&this.setCalculateSizeCallback(e.calculateSizeCallback),n.setPixelRatio(Math.min(window.devicePixelRatio,2)),n.setSize(this.width,this.height),this._renderer=new Hc(n);const s=me.instance.fontMapping;this._renderer.setFontMapping(s),this._renderer.events.fontNotFound.addEventListener(f=>{ee.emit("font-not-found",{fontName:f.fontName,count:f.count??0})}),this._scene=this.createScene(),this.backgroundColor=t.background??qe,this._stats=this.createStats(me.instance.isShowStats);const r=u.AcDbSysVarManager.instance(),a=u.AcDbSystemVariables.MODELBKCOLOR.toLowerCase(),c=u.AcDbSystemVariables.PAPERBKCOLOR.toLowerCase();r.events.sysVarChanged.addEventListener(f=>{const w=f.name.toLowerCase();if(w===a||w===c){const x=this.isModelSpaceLayout(f.database);if(!(w===a&&x||w===c&&!x))return;this.applyCanvasBackground(gi(f.database,x))}}),me.instance.events.modified.addEventListener(f=>{f.key=="isShowStats"&&this.toggleStatsVisibility(this._stats,f.value)});let l=null,h=null,d=null;const p=()=>this.mode===oe.SELECTION&&!this.editor.isActive&&!Ne.getActiveInputBox(),m=()=>{d==null||d.remove(),d=null};this.canvas.addEventListener("mousedown",f=>{f.button===0&&p()&&(h=this.viewportToCanvas({x:f.clientX,y:f.clientY}),l=this.screenToWorld(h),d=document.createElement("div"),d.className="ml-jig-preview-rect",this.container.appendChild(d))}),this.canvas.addEventListener("mousemove",f=>{if(!l||!d||!h)return;const w=this.viewportToCanvas({x:f.clientX,y:f.clientY}),x=this.screenToWorld(w),b=this.worldToScreen(l),v=this.worldToScreen(x),C=Math.min(b.x,v.x),P=Math.min(b.y,v.y),L=Math.abs(b.x-v.x),M=Math.abs(b.y-v.y),k=this.getSelectionMode(h,w),E=this.getPointerSelectionAction(f),T=this.getSelectionPreviewStyle(k,E);Object.assign(d.style,{left:`${C}px`,top:`${P}px`,width:`${L}px`,height:`${M}px`,borderStyle:T.borderStyle,background:T.background}),d.style.setProperty("--line-color",T.lineColor)}),this.canvas.addEventListener("mouseup",f=>{if(!l||!h)return;const w=this.viewportToCanvas({x:f.clientX,y:f.clientY}),x=this.screenToWorld(w);m();const b=this.getPointerSelectionAction(f);if(this.isSelectionClick(h,w)){const v=this.pick(x);v.length>0?this.applySelection([v[0].id],b):b==="replace"&&this.selectionSet.clear()}else{const v=new u.AcGeBox2d().expandByPoint(l).expandByPoint(x),C=this.getSelectionMode(h,w);this.selectByBoxWithMode(v,C,b)}l=null,h=null}),this.canvas.addEventListener("dblclick",f=>{f.button===0&&p()&&A.instance.curDocument.openMode===R.Write&&this.openPickedMTextEditor(f)}),document.addEventListener("keydown",f=>{const w=f.target,x=w instanceof HTMLInputElement||w instanceof HTMLTextAreaElement||(w==null?void 0:w.isContentEditable)===!0,b=f.isComposing||f.keyCode===229;if(!(x||b))switch(f.code){case"Escape":this.selectionSet.clear();break;case"Delete":case"Backspace":this.editor.isActive||A.instance.sendStringToExecute("erase");break}}),u.acdbHostApplicationServices().layoutManager.events.layoutSwitched.addEventListener(f=>{const w=f.layout.blockTableRecordId,x=!this._initializedLayouts.has(w);this._initializedLayouts.add(w),Promise.resolve().then(()=>Kh).then(({clearAllMeasurements:b})=>b(this)),this.activeLayoutBtrId=w,this.createLayoutViewIfNeeded(w),this.loadLayoutEntitiesIfNeeded(w),this.refreshCanvasBackgroundForActiveLayout(),this._isDirty=!0,x&&this.applyInitialZoom(w,f.layout)}),this._css2dRenderer=new fs.CSS2DRenderer,this._css2dRenderer.setSize(this.width,this.height),this._css2dRenderer.domElement.style.position="absolute",this._css2dRenderer.domElement.style.top="0px",this._css2dRenderer.domElement.style.left="0px",this._css2dRenderer.domElement.style.pointerEvents="none",this._css2dRenderer.domElement.style.zIndex="99998",i.appendChild(this._css2dRenderer.domElement),this._missedImages=new Map,this._layoutViewManager=new Su,this.initialize(),this.onWindowResize(),this._isDirty=!0,this.startAnimationLoop(),this._numOfEntitiesToProcess=0}getPointerSelectionAction(e){return Dr(e)}initialize(){this.setCursor(be.Crosshair)}get mode(){const e=this.activeLayoutView;return e?e.mode:oe.SELECTION}set mode(e){this.activeLayoutView.mode=e}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.applyCanvasBackground(e)}applyCanvasBackground(e){this._renderer.setClearColor(e),this._renderer.currentBackgroundColor=e,this._renderer.changeBackground(e),this.editor.syncCursorBackground(e),this._isDirty=!0}isModelSpaceLayout(e){return e?Hs(e):this.activeLayoutBtrId===this.modelSpaceBtrId}syncDisplaySysVars(e){this.applyCanvasBackground(gi(e,this.isModelSpaceLayout(e)))}refreshCanvasBackgroundForActiveLayout(){var n,s;const t=(s=(n=A._instance)==null?void 0:n.curDocument)==null?void 0:s.database;if(!t)return;const i=this.activeLayoutBtrId===this.modelSpaceBtrId;this.applyCanvasBackground(gi(t,i))}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}get cadScene(){return this._scene}get internalScene(){return this._scene.internalScene}get htmlTransientManager(){return this._scene.htmlTransientManager}get internalCamera(){var e;return(e=this.activeLayoutView)==null?void 0:e.internalCamera}set ltscale(e){this._renderer.ltscale=e}set celtscale(e){this._renderer.celtscale=e}screenToWorld(e){const t=this.activeLayoutView;return t?t.screenToWorld(e):new u.AcGePoint2d(e)}worldToScreen(e){const t=this.activeLayoutView;return t?t.worldToScreen(e):new u.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)}zoomToFitDrawing(e=0){new Mn(()=>this._numOfEntitiesToProcess<=0,()=>{if(this._scene.box){const i=qi.threeBox3dToGeBox2d(this._scene.box);this.zoomTo(i),this._isDirty=!0}},300,e).start()}zoomToFitLayer(e){const t=this._scene.activeLayout;if(t){const i=t.getLayer(e);if(i&&!i.box.isEmpty()){const n=qi.threeBox3dToGeBox2d(i.box);return this.zoomTo(n),this._isDirty=!0,!0}}return!1}flyTo(e,t){this.activeLayoutView.flyTo(e,t),this._isDirty=!0}async openPickedMTextEditor(e){const t=this.viewportToCanvas({x:e.clientX,y:e.clientY}),i=this.screenToWorld(t),n=this.pick(i,void 0,!0);if(!n.length)return;const s=A.instance.curDocument.database.tables.blockTable.getEntityById(n[0].id);s instanceof u.AcDbMText&&(e.preventDefault(),await this.editMTextEntity(s))}async editMTextEntity(e){e.lineSpacingFactor!==Ne.defaultLineSpacingFactor&&(e.lineSpacingFactor=Ne.defaultLineSpacingFactor,e.triggerModifiedEvent()),this._isDirty=!0;const t=new Ne;let i=!1;try{const n=await t.open({view:this,location:e.location,width:this.resolveMTextEditorWidth(e),textHeight:this.resolveMTextEditorTextHeight(e),initialText:e.contents,initialAttachmentPoint:e.attachmentPoint,toolbarFontFamilies:this.getMTextToolbarFontFamilies()});if(!n)return;e.location=n.location,e.contents=n.contents,e.width=n.width,e.height=n.height,e.lineSpacingFactor=n.lineSpacingFactor,e.attachmentPoint=n.attachmentPoint,e.triggerModifiedEvent(),i=!0}finally{i||(this.updateEntity(e),this._isDirty=!0)}}resolveMTextEditorWidth(e){const t=Number(e.width);return Number.isFinite(t)&&t>0?t:1e-4}resolveMTextEditorTextHeight(e){const t=Number(e.height);return Number.isFinite(t)&&t>0?t:this.pixelsToWorldY(24)}pixelsToWorldY(e){const t=this.screenToWorld({x:0,y:0}),i=this.screenToWorld({x:0,y:e});return Math.max(Math.abs(i.y-t.y),1e-4)}getMTextToolbarFontFamilies(){return Array.from(new Set(A.instance.avaiableFonts.flatMap(e=>e.name).map(e=>e.trim()).filter(e=>e.length>0)))}pick(e,t,i){e==null&&(e=this.curPos);const n=[],s=this._scene.activeLayout;if(!s)return n;const r=this.activeLayoutView,a=t??this.selectionBoxSize,c=r.pointToBox(e,a),l=Math.max(c.size.width/2,c.size.height/2),h=r.layoutBtrId!==this._scene.modelSpaceBtrId,d=(c.size.width+c.size.height)/2,p=[],m=new Set;if(h)for(const b of r.viewportViews)b.containsPaperPoint(e)&&!b.isNearPaperBorder(e,d)&&(p.push(b),m.add(b.viewport.id));const f=this._scene.search(c),w=r.resetRaycaster(e,l);f.forEach(b=>{m.has(b.id)||s.isIntersectWith(b.id,w)&&n.push(b)}),p.length>0&&this.pickThroughViewports(e,c,p,n);const x=Au(n,e);return i?x.slice(0,1):x}pickThroughViewports(e,t,i,n){const s=this._scene.modelSpaceLayout;if(!s)return;const r=(t.size.width+t.size.height)/4;for(const a of i){const c=a.paperPointToModel(e),l=r*a.paperToModelScale;if(l<=0)continue;const h=new u.AcGeBox2d().setFromPoints([new u.AcGePoint2d(c.x-l,c.y-l),new u.AcGePoint2d(c.x+l,c.y+l)]),d=a.resetRaycaster(c,l);s.search(h).forEach(m=>{s.isIntersectWith(m.id,d)&&n.push(m)})}}search(e){return this._scene.search(e)}select(e){const t=[];this.pick(e).forEach(n=>t.push(n.id)),t.length>0&&this.selectionSet.add(t)}selectByBox(e){this.selectByBoxWithMode(e,"crossing","add")}addLayer(e){const t=this._scene.addLayer({name:e.name,isFrozen:e.isFrozen,isOff:e.isOff,color:e.color}),i={layer:e.name,color:e.color.clone(),rgbColor:e.color.RGB,lineType:e.lineStyle,lineWeight:e.lineWeight,transparency:e.transparency},n=this._renderer.updateLayerMaterial(e.name,i);t.forEach(s=>{for(const r in n){const a=n[r];s.updateMaterial(Number(r),a)}}),this._isDirty=!0}updateLayer(e,t){const i=this._scene.updateLayer({name:e.name,isFrozen:e.isFrozen,isOff:e.isOff,color:e.color}),n={};t.color&&(n.color=t.color.clone(),n.rgbColor=t.color.RGB),t.lineStyle&&(n.lineType=e.lineStyle),t.lineWeight!==void 0&&(n.lineWeight=t.lineWeight),t.transparency!==void 0&&(n.transparency=t.transparency),n.layer=e.name;const s=this._renderer.updateLayerMaterial(e.name,n);i.forEach(r=>{for(const a in s){const c=s[a];r.updateMaterial(Number(a),c)}}),this._isDirty=!0}addTransientEntity(e){const t=Array.isArray(e)?e:[e];for(let i=0;i<t.length;++i){const n=t[i],s=this.drawEntity(n,!0);s&&(s.objectId=n.objectId,this._scene.addTransientEntity(s),this._isDirty=!0)}}removeTransientEntity(e){this._scene.removeTransientEntity(e),this._isDirty=!0}addEntity(e){const t=Array.isArray(e)?e:[e];this._numOfEntitiesToProcess+=t.length,setTimeout(async()=>{await this.batchConvert(t)}),this._isDirty=!0}removeEntity(e){(Array.isArray(e)?e:[e]).forEach(i=>this._scene.removeEntity(i.objectId)),this._isDirty=!0}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.worldDraw(this._renderer);s&&(s.objectId=n.objectId,s.ownerId=n.ownerId,s.layerName=n.layer,s.visible=n.visibility,this._scene.updateEntity(s))}this._isDirty=!0,setTimeout(()=>{this._isDirty=!0},100)}addLayout(e){this._scene.addEmptyLayout(e.blockTableRecordId),this.createLayoutViewIfNeeded(e.blockTableRecordId),this._isDirty=!0}markLayoutAsInitialized(e){this._initializedLayouts.add(e)}applyInitialZoom(e,t){new Mn(()=>this._numOfEntitiesToProcess<=0,()=>{const n=t.limits,s=this._layoutViewManager.getAt(e),r=s==null?void 0:s.viewportsBoundingBox,a=!n||n.isEmpty()?!1:r?n.min.x<=r.min.x&&n.min.y<=r.min.y&&n.max.x>=r.max.x&&n.max.y>=r.max.y:!0;if(n&&!n.isEmpty()&&a)this.zoomTo(n);else if(r)this.zoomTo(r);else if(t.extents&&!t.extents.isEmpty()){const c=t.extents;this.zoomTo(new u.AcGeBox2d({x:c.min.x,y:c.min.y},{x:c.max.x,y:c.max.y}))}else this._scene.box&&this.zoomTo(qi.threeBox3dToGeBox2d(this._scene.box));this._isDirty=!0},300,0).start()}clear(){this._scene.clear(),this._isDirty=!0,this._missedImages.clear(),this._renderer.dispose()}highlight(e){this._isDirty=this._scene.select(e)}unhighlight(e){this._isDirty=this._scene.unselect(e)}stopAnimationLoop(){this._rafId!=null&&(cancelAnimationFrame(this._rafId),this._rafId=null)}onHover(e){this._isDirty=this._scene.hover([e])}onUnhover(e){this._isDirty=this._scene.unhover([e])}createScene(){return new Ma}createStats(e){const t=new Ha;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._css2dRenderer.setSize(this.width,this.height),this._layoutViewManager.resize(this.width,this.height),this._isDirty=!0}startAnimationLoop(){this._rafId==null&&(this._rafId=requestAnimationFrame(this.animate))}createLayoutViewIfNeeded(e){let t=this._layoutViewManager.getAt(e);return t==null&&(t=new xu(this._renderer,e,this.width,this.height),t.events.viewChanged.addEventListener(()=>{this._isDirty=!0,this.events.viewChanged.dispatch(),this.clearHover()}),this._layoutViewManager.add(t)),t}loadLayoutEntitiesIfNeeded(e){try{const i=A.instance.curDocument.database.tables.blockTable.getIdAt(e);if(!i)return;const n=this._scene.layouts.get(e);if(n&&n.isLoaded||this._loadingLayouts.has(e))return;const s=this._layoutViewManager.getAt(e);if(n&&n.entityCount>0&&s&&s.viewportCount===0&&this.ensureViewportViews(i,s),n&&n.entityCount>0){n.isLoaded=!0;return}n||this._scene.addEmptyLayout(e);const r=[],a=i.newIterator();for(const c of a)r.push(c);if(r.length===0){const c=this._scene.layouts.get(e);c&&(c.isLoaded=!0);return}this._loadingLayouts.add(e),this._numOfEntitiesToProcess+=r.length,setTimeout(async()=>{try{await this.batchConvert(r);const c=this._scene.layouts.get(e);c&&(c.isLoaded=!0)}finally{this._loadingLayouts.delete(e)}})}catch(t){u.log.error("[AcTrView2d] Error loading layout entities:",t)}}toggleStatsVisibility(e,t){t?e.dom.style.display="block":e.dom.style.display="none"}drawEntity(e,t){return e.worldDraw(this._renderer,t)}ensureViewportViews(e,t){const i=e.newIterator();for(const n of i){if(!(n instanceof u.AcDbViewport)||Fe.isDefaultPaperSpaceViewport(n))continue;const s=new Fe(t,n.toGiViewport(),this._renderer);t.addViewport(s)}}async batchConvert(e){for(let t=0;t<e.length;++t){const i=e[t];try{if(i instanceof u.AcDbViewport&&Fe.isDefaultPaperSpaceViewport(i)||!i.visibility)continue;const n=this.drawEntity(i,!0);if(!n)continue;if(n.objectId=i.objectId,n.ownerId=i.ownerId,n.layerName=i.layer,n.visible=i.visibility,n instanceof Ye&&n.isOnTheSameLayer&&this.remapInheritedLayerObjects(n.children,"0",n.layerName),n instanceof Ye&&!n.isOnTheSameLayer)this.handleGroup(n);else{const s=!(i instanceof u.AcDbRay||i instanceof u.AcDbXline);await n.draw(),this._scene.addEntity(n,s),n.dispose(),this._isDirty=!0}if(i instanceof u.AcDbViewport){if(!Fe.isDefaultPaperSpaceViewport(i)){const s=this._layoutViewManager.getAt(i.ownerId);if(s){const r=new Fe(s,i.toGiViewport(),this._renderer);s.addViewport(r)}}}else if(i instanceof u.AcDbRasterImage){const s=i.imageFileName;s&&this._missedImages.set(i.objectId,s)}}catch(n){u.log.error(`[AcTrView2d] Failed to convert entity ${i.objectId} (${i.type}):`,n)}finally{this.decreaseNumOfEntitiesToProcess()}}}handleGroup(e){const t=e.children,i=new Map;t.forEach(l=>{var d;if(!l.visible)return;const h=l.userData.layerName;i.has(h)||i.set(h,[]),(d=i.get(h))==null||d.push(l)}),e.children=[];for(const l of t)l.parent=null;const n=e.styleManager,s=e.objectId,r=e.layerName,a=e.box,c=e.boxes.map(l=>({...l}));i.forEach((l,h)=>{const d=h==="0"?r:h;this.remapInheritedLayerObjects(l,h,d);const p=new Y(n);p.applyMatrix4(e.matrix),p.objectId=s,p.ownerId=e.ownerId,p.layerName=d,p.box=a;const m=p.userData;m.spatialIndexChildBoxes=c;for(let f=0;f<l.length;f++)p.add(l[f]);this._scene.addEntity(p,!0),p.dispose()}),e.dispose(),this._isDirty=!0}remapInheritedLayerObjects(e,t,i){if(t===i)return;const n=this._renderer,s=this.getEffectiveLayerTraits(i);for(const r of e)r.traverse(a=>{if(a.userData.layerName===t&&(a.userData.layerName=i),!("material"in a))return;const c=a.material;if(Array.isArray(c)){const h=c;a.material=h.map(d=>n.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(d,t),i,s));return}const l=n.getLayerBoundMaterial(this.promoteLayerZeroByLayerColor(c,t),i,s);a.material=l,a.userData.styleMaterialId=l.id})}promoteLayerZeroByLayerColor(e,t){const i=Ce(e),n=Cs(i)&&i.isByLayerColor!==!0;return t==="0"&&n&&ln(e,{isByLayerColor:!0}),e}getEffectiveLayerTraits(e){const t=A.instance.curDocument.database.tables.layerTable.getAt(e);if(t)return{layer:t.name,color:t.color.clone(),rgbColor:t.color.RGB,lineType:t.lineStyle,lineWeight:t.lineWeight,transparency:t.transparency}}decreaseNumOfEntitiesToProcess(){this._numOfEntitiesToProcess--,this._numOfEntitiesToProcess<0&&(this._numOfEntitiesToProcess=0,u.log.warn("Something wrong! The number of entities to process should not be less than 0."))}}class Pu{constructor(){this._loader=new Pc}get baseUrl(){return this._loader.baseUrl}set baseUrl(e){this._loader.baseUrl=e}get avaiableFonts(){return this._loader.avaiableFonts}async getAvaiableFonts(){return await this._loader.getAvailableFonts()}async load(e){const t=await this._loader.load(e),i=[],n=[];t.forEach(s=>{s.status==="NotFound"?i.push(s.fontName):s.status==="FailedToLoad"&&n.push({fontName:s.fontName,url:s.url})}),i.length>0&&ee.emit("fonts-not-found",{fonts:i}),n.length>0&&ee.emit("fonts-not-loaded",{fonts:n})}}const Be=class Be{constructor(e={}){this.options={size:e.size??"48px",borderWidth:e.borderWidth??"5px",color:e.color??"var(--ml-ui-accent, #0b84ff)",host:e.host??document.body,overlay:e.overlay??!0,overlayColor:e.overlayColor??"var(--ml-ui-overlay, rgba(0,0,0,0.5))",message:e.message??""},Be.stylesInjected||this.injectStyles(),this.createDom()}show(){return this.root.style.display="flex",this}hide(){return this.root.style.display="none",this}setMessage(e=""){return this.messageEl.textContent=e,this.messageEl.style.display=e?"block":"none",this}destroy(){var e;(e=this.root)!=null&&e.parentNode&&this.root.parentNode.removeChild(this.root)}createDom(){const e=this.options.host;getComputedStyle(e).position==="static"&&(e.style.position="relative");const i=document.createElement("div");i.className="ml-ccl-overlay",i.style.display="flex",i.style.background=this.options.overlay?this.options.overlayColor:"transparent";const n=document.createElement("div");n.className="ml-ccl-spinner",n.style.width=this.options.size,n.style.height=this.options.size,n.style.borderWidth=this.options.borderWidth,n.style.borderTopColor=this.options.color;const s=document.createElement("div");s.className="ml-ccl-message",s.textContent=this.options.message,s.style.display=this.options.message?"block":"none";const r=document.createElement("div");r.className="ml-ccl-wrapper",r.appendChild(n),r.appendChild(s),i.appendChild(r),e.appendChild(i),this.root=i,this.spinner=n,this.messageEl=s}injectStyles(){if(document.getElementById(Be.styleId)){Be.stylesInjected=!0;return}const e=`
|
|
858
839
|
.ml-ccl-overlay {
|
|
859
840
|
position: absolute;
|
|
860
841
|
inset: 0;
|
|
@@ -892,8 +873,8 @@
|
|
|
892
873
|
@keyframes ml-ccl-rotate {
|
|
893
874
|
to { transform: rotate(360deg); }
|
|
894
875
|
}
|
|
895
|
-
`.trim(),t=document.createElement("style");t.id=
|
|
876
|
+
`.trim(),t=document.createElement("style");t.id=Be.styleId,t.textContent=e,document.head.appendChild(t),Be.stylesInjected=!0}};Be.styleId="ml-ccl-loader-styles",Be.stylesInjected=!1;let sn=Be;function ja(o){return o.percentage<100?!1:o.subStageStatus==="ERROR"?!0:o.subStageStatus!=="END"?!1:o.stage==="FETCH_FILE"||o.subStage==="END"}const _u="https://mlightcad.gitlab.io/cad-data/",Lu={ARC:["A"],CIRCLE:["C"],ELLIPSE:["EL"],ERASE:["E"],DIMLINEAR:["DLI"],MEASUREDISTANCE:["DI","DIST"],MEASUREAREA:["AA","AREA"],MEASUREANGLE:["ANG"],"-HATCH":["-H"],LAYER:["LA"],"-LAYER":["-LA"],LINE:["L"],MLINE:["ML"],MTEXT:["T"],MOVE:["M"],OFFSET:["O"],COPY:["CO"],ROTATE:["RO"],OPEN:["OP"],PAN:["P"],POINT:["PO"],POLYGON:["POL"],PLINE:["PL"],RAY:["RA"],RECTANG:["REC"],REGEN:["RE"],SELECT:["SE"],SPLINE:["SPL"],XLINE:["XL"],ZOOM:["Z"]};class A{constructor(e={}){var a;this._openFileProgressPeak=0,this.events={documentToBeOpened:new u.AcCmEventManager,documentCreated:new u.AcCmEventManager,documentActivated:new u.AcCmEventManager},this._baseUrl=e.baseUrl??_u,this._htmlViewerRuntimeUrl=e.htmlViewerRuntimeUrl,this._commandAliasOverrides=this.normalizeCommandAliasConfig(e.commandAliases),e.useMainThreadDraw?Xe.getInstance().setRenderMode("main"):Xe.getInstance().setRenderMode("worker"),this.events.documentToBeOpened.addEventListener(()=>{this.resetOpenFileProgress()});const t=new Or;t.database.events.openProgress.addEventListener(c=>{const l=this.normalizeOpenFileProgress({database:t.database,percentage:c.percentage,stage:c.stage,subStage:c.subStage,subStageStatus:c.subStageStatus,data:c.data});ee.emit("open-file-progress",l),this.updateProgress(l),c.subStage==="HEADER"&&(this.curView.ltscale=t.database.ltscale,this.curView.celtscale=t.database.celtscale,this.curView.renderer.showLineWeight=t.database.lwdisplay)});const i=((a=e.container)==null?void 0:a.getBoundingClientRect())??{width:300,height:150},n=()=>{var c;if(e.autoResize){const l=(c=e.container)==null?void 0:c.getBoundingClientRect();return{width:(l==null?void 0:l.width)??i.width,height:(l==null?void 0:l.height)??i.height}}else return{width:e.width??i.width,height:e.height??i.height}},s=new Ra({container:e.container,calculateSizeCallback:n});this._context=new ys(s,t),this._fontLoader=new Pu,this._fontLoader.baseUrl=this._baseUrl+"fonts/",u.acdbHostApplicationServices().workingDatabase=t.database,this._commandManager=new he,this.registerCommands(),this._pluginManager=new Ia(this._context,this._commandManager),this._progress=new sn({host:s.container}),this._progress.hide();const r=e.busyIndicatorHost??s.container;this._busyProgress=new sn({host:r}),this._busyProgress.hide(),e.notLoadDefaultFonts||this.loadDefaultFonts(),this.registerWorkers(e.webworkerFileUrls),this.loadPlugins(e.plugins).catch(c=>{u.log.error("[AcApDocManager] Error loading plugins:",c)})}static createInstance(e={}){return A._instance==null&&(A._instance=new A(e)),this._instance}static get instance(){if(!A._instance)throw new Error("AcApDocManager instance is not created yet!");return A._instance}async destroy(){await this._pluginManager.unloadAllPlugins(),A._instance=void 0}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 commandManager(){return this._commandManager}get pluginManager(){return this._pluginManager}get baseUrl(){return this._baseUrl}get htmlViewerRuntimeUrl(){return this._htmlViewerRuntimeUrl}resolveColors(){const e=this.curDocument.database,t=e.tables.layerTable.getAt(e.clayer),i=this.resolveColorToRgb(t==null?void 0:t.color);let n=e.cecolor;return n!=null&&n.isByLayer&&(n=t==null?void 0:t.color),{entityColor:this.resolveColorToRgb(n),layerColor:i}}resolveColorToRgb(e){return!e||e.isByLayer||e.isByBlock||e.isByACI&&e.colorIndex===7?this.resolveAci7ForBackground():e.RGB??this.resolveAci7ForBackground()}resolveAci7ForBackground(){return this.curView.backgroundColor===16777215?0:16777215}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){t=this.setOptions(t),this.onBeforeOpenDocument(t);const i=await this.context.doc.openUri(e,t);return this.onAfterOpenDocument(i,t),i}async openDocument(e,t,i){i=this.setOptions(i),this.onBeforeOpenDocument(i);const n=await this.context.doc.openDocument(e,t,i);return this.onAfterOpenDocument(n,i),n}regen(){this.curView.clear(),this.context.doc.database.regen()}lookupLocalCmd(e){return this._commandManager.lookupLocalCmd(e,this.curDocument.openMode)}lookupGlobalCmd(e){return this._commandManager.lookupGlobalCmd(e,this.curDocument.openMode)}searchCommandsByPrefix(e){return this._commandManager.searchCommandsByPrefix(e,this.curDocument.openMode)}registerCommands(){const e=this._commandManager,t=(n,s,r)=>{const a=Lu[n.toUpperCase()]??[];e.addCommand(he.SYSTEMT_COMMAND_GROUP_NAME,n,s,r,this.resolveCommandAliases(n,a))};t("arc","arc",new ao),t("circle","circle",new po),t("cdxf","cdxf",new Vr),t("pngout","pngout",new Kr),t("ellipse","ellipse",new vo),t("erase","erase",new oa),t("dimlinear","dimlinear",new fo),t("measuredistance","measuredistance",new ra),t("measurearea","measurearea",new Qo),t("measureangle","measureangle",new Xo),t("measurearc","measurearc",new ia),t("clearmeasurements","clearmeasurements",new ts),t("-hatch","-hatch",new $i),t("-layer","-layer",new to),t("laycur","laycur",new $r),t("laydel","laydel",new Ur),t("layfrz","layfrz",new Oi),t("layiso","layiso",new Fi),t("laylck","laylck",new Yr),t("layon","layon",new Xr),t("layoff","layoff",new Ri),t("laythw","laythw",new Zr),t("layuniso","layuniso",new Jr),t("layulk","layulk",new Qr),t("layerp","layerp",new qr),t("layerclose","layerclose",new eo),t("line","line",new Ze),t("mline","mline",new So),t("mtext","mtext",new Ao),t("copy","copy",new Ji),t("move","move",new ca),t("offset","offset",new Gt),t("rotate","rotate",new Kt),t("log","log",new xa),t("open","open",new Sa),t("pan","pan",new Ta),t("point","point",new Co),t("polygon","polygon",new Hi),t("pline","pline",new To),t("qnew","qnew",new Aa),t("ray","ray",new Eo),t("rectang","rectang",new Yi),t("regen","regen",new Ca),t("revcircle","revcircle",new pa),t("revcloud","revcloud",new ga),t("revrect","revrect",new fa),t("revvis","revvis",new ya),t("select","select",new Pa),t("sketch","sketch",new va),t("spline","spline",new Mo),t("switchbg","switchbg",new La),t("xline","xline",new Ro),t("zoom","zoom",new Qe),u.AcDbSysVarManager.instance().getAllDescriptors().forEach(n=>{e.addCommand(he.SYSTEMT_COMMAND_GROUP_NAME,n.name,n.name,new _a,this.resolveCommandAliases(n.name,[]))})}normalizeCommandAliasConfig(e){const t=new Map;return e&&Object.entries(e).forEach(([i,n])=>{const s=i.trim().toUpperCase();if(!s)return;const r=Array.isArray(n)?n:[n],a=new Set;r.forEach(c=>{const l=c.trim().toUpperCase();l&&l!==s&&a.add(l)}),t.set(s,[...a])}),t}resolveCommandAliases(e,t){const i=e.trim().toUpperCase(),n=this._commandAliasOverrides.get(i);if(n)return[...n];const s=new Set;return t.forEach(r=>{const a=r.trim().toUpperCase();a&&a!==i&&s.add(a)}),[...s]}sendStringToExecute(e){this.executeCommandString(e).catch(t=>{const i=t instanceof Error?t.message:String(t);this.editor.showMessage(i,"error"),u.log.error(`[AcApDocManager] Command failed: ${e}`,t)})}async executeCommandString(e){const t=this.splitCommandScript(e);if(!t.length)throw new Error("Command string is empty");const[i,...n]=t,s=this.context.doc.openMode;let r=this._commandManager.lookupGlobalCmd(i)??this._commandManager.lookupLocalCmd(i,s);if(r||await this._pluginManager.loadByTrigger(i)&&(r=this._commandManager.lookupGlobalCmd(i)??this._commandManager.lookupLocalCmd(i,s)),!r)throw new Error(`Command '${i}' not found`);if(s<r.mode)throw new Error(`Command '${i}' requires mode '${R[r.mode]}' but document is in mode '${R[s]}'!`);this.editor.clearScriptInputs(),this.editor.enqueueScriptInputs(n),await r.trigger(this.context).finally(()=>{this.editor.clearScriptInputs()})}splitCommandScript(e){const i=(e.includes(`
|
|
896
877
|
`)||e.includes("\r")?e:e.replace(/\\n/g,`
|
|
897
878
|
`)).replace(/\r\n/g,`
|
|
898
879
|
`).split(`
|
|
899
|
-
`);if(!i.length)return[];const n=i[0].trim();return n?[n,...i.slice(1)]:[]}setActiveLayout(){const e=this.curView,t=this.curDocument.database;e.activeLayoutBtrId=t.currentSpaceId,e.modelSpaceBtrId=t.tables.blockTable.modelSpace.objectId}onBeforeOpenDocument(e){this.events.documentToBeOpened.dispatch({doc:this.context.doc,mode:this.getDocumentEventMode(e)}),this.curView.clear()}onAfterOpenDocument(e,t){if(e){const i=this.context.doc;this.events.documentActivated.dispatch({doc:i,mode:this.getDocumentEventMode(t)}),this.setActiveLayout();const n=i.database,s=n.tables.blockTable.modelSpace.objectId,r=n.currentSpaceId!==s,o=u.acdbHostApplicationServices().layoutManager.getActiveLayout(n),c=o==null?void 0:o.limits;r&&c&&!c.isEmpty()?this.curView.zoomTo(c):!r&&!n.extents.isEmpty()?this.curView.zoomTo(new u.AcGeBox2d(n.extmin,n.extmax)):this.curView.zoomToFitDrawing(),this.curView.markLayoutAsInitialized(n.currentSpaceId)}}setOptions(e){return e==null?e={fontLoader:this._fontLoader}:e.fontLoader==null&&(e.fontLoader=this._fontLoader),e}getDocumentEventMode(e){return(e==null?void 0:e.mode)??j.Read}showBusyIndicator(){this._busyProgress.setMessage(""),this._busyProgress.show()}hideBusyIndicator(){this._busyProgress.hide()}resetOpenFileProgress(){this._openFileProgressPeak=0,this._openFileProgressStage=void 0}normalizeOpenFileProgress(e){const t=e.stage;return t!==this._openFileProgressStage&&(this._openFileProgressStage==="FETCH_FILE"&&t==="CONVERSION"&&(this._openFileProgressPeak=0),this._openFileProgressStage=t),this._openFileProgressPeak=Math.max(this._openFileProgressPeak,e.percentage),{...e,percentage:this._openFileProgressPeak}}isOpenFileProgressComplete(e){return e.percentage>=100&&e.subStage==="END"&&e.subStageStatus==="END"}updateProgress(e){if(e.stage==="CONVERSION"){if(e.subStage){const t="main.progress."+e.subStage.replace(/_/g,"").toLowerCase();this._progress.setMessage(p.t(t))}}else e.stage==="FETCH_FILE"&&this._progress.setMessage(p.t("main.message.fetchingDrawingFile"));this.isOpenFileProgressComplete(e)?(this._progress.hide(),this.resetOpenFileProgress()):this._progress.show()}registerConverters(e){try{const t=new u.AcDbDxfConverter({convertByEntityType:!1,useWorker:!0,parserWorkerUrl:e&&e.dxfParser?e.dxfParser:"./assets/dxf-parser-worker.js"});u.AcDbDatabaseConverterManager.instance.register(u.AcDbFileType.DXF,t)}catch(t){u.log.error("Failed to register dxf converter: ",t)}try{const t=new Sc({convertByEntityType:!1,useWorker:!0,parserWorkerUrl:e&&e.dwgParser?e.dwgParser:"./assets/libredwg-parser-worker.js"});u.AcDbDatabaseConverterManager.instance.register(u.AcDbFileType.DWG,t)}catch(t){u.log.error("Failed to register dwg converter: ",t)}}registerWorkers(e){this.registerConverters(e),Ye.getInstance().initialize(e&&e.mtextRender?e.mtextRender:"./assets/mtext-renderer-worker.js")}async loadPlugins(e){if(e){if(e.fromConfig&&e.fromConfig.length>0)try{const t=await this._pluginManager.loadPluginsFromConfig(e.fromConfig,{continueOnError:!0});t.loaded.length>0&&u.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from config:`,t.loaded),t.failed.length>0&&u.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s):`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){u.log.error("[AcApDocManager] Error loading plugins from config:",t)}if(e.fromFolder)try{const t=await this._pluginManager.loadPluginsFromFolder(e.fromFolder.folderPath,{pluginList:e.fromFolder.pluginList,continueOnError:e.fromFolder.continueOnError??!0});t.loaded.length>0&&u.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from folder:`,t.loaded),t.failed.length>0&&u.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s) from folder:`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){u.log.error("[AcApDocManager] Error loading plugins from folder:",t)}}}}const au={isDebug:!1,isShowCommandLine:!0,isShowCoordinate:!0,isShowEntityInfo:!1,isShowFileName:!0,isShowLanguageSelector:!0,isShowMainMenu:!0,isShowToolbar:!0,isShowStats:!1,fontMapping:{},osnapModes:u.acdbOsnapModesToMask([u.AcDbOsnapMode.EndPoint,u.AcDbOsnapMode.MidPoint,u.AcDbOsnapMode.Center,u.AcDbOsnapMode.Quadrant,u.AcDbOsnapMode.Nearest])},wa="settings";class ye{constructor(){this.events={modified:new u.AcCmEventManager}}static get instance(){return this._instance||(this._instance=new ye),this._instance}set(e,t){const i=this.settings;i[e]=t,localStorage.setItem(wa,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 isShowEntityInfo(){return this.get("isShowEntityInfo")}set isShowEntityInfo(e){this.set("isShowEntityInfo",e)}get isShowFileName(){return this.get("isShowFileName")}set isShowFileName(e){this.set("isShowFileName",e)}get isShowLanguageSelector(){return this.get("isShowLanguageSelector")}set isShowLanguageSelector(e){this.set("isShowLanguageSelector",e)}get isShowMainMenu(){return this.get("isShowMainMenu")}set isShowMainMenu(e){this.set("isShowMainMenu",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 osnapModes(){return this.get("osnapModes")}set osnapModes(e){this.set("osnapModes",e)}get settings(){const e=localStorage.getItem(wa),t=e==null?{}:JSON.parse(e);return Ue.defaults(t,au)}}class cu extends N{async execute(e){u.log.info("Hello from ExamplePlugin!"),u.log.info("Current document:",e.doc),u.log.info("Current view:",e.view)}}class lu{constructor(){this.name="ExamplePlugin",this.version="1.0.0",this.description="An example plugin demonstrating the plugin system",this.registeredCommands=[]}onLoad(e,t){t.addCommand("USER","HELLO","Hello",new cu),this.registeredCommands.push({group:"USER",name:"HELLO"}),u.log.info(`[${this.name}] Plugin loaded successfully`),u.log.info(`[${this.name}] Registered command: HELLO`)}onUnload(e,t){for(const i of this.registeredCommands)t.removeCmd(i.group,i.name);this.registeredCommands=[],u.log.info(`[${this.name}] Plugin unloaded`)}}Object.defineProperty(P,"AcGiTextParagraphAlignment",{enumerable:!0,get:()=>B.MTextParagraphAlignment}),Object.defineProperty(P,"MTextColor",{enumerable:!0,get:()=>B.MTextColor}),Object.defineProperty(P,"MTextParagraphAlignment",{enumerable:!0,get:()=>B.MTextParagraphAlignment}),Object.defineProperty(P,"ShxParserFont",{enumerable:!0,get:()=>B.ShxParserFont}),P.AcApAnnotation=we,P.AcApArcCmd=Zr,P.AcApBaseRevCmd=gt,P.AcApCircleCmd=no,P.AcApCircleJig=ji,P.AcApClearMeasurementsCmd=Xn,P.AcApContext=as,P.AcApConvertToDxfCmd=fr,P.AcApConvertToPngCmd=br,P.AcApConvertToSvgCmd=xr,P.AcApCopyCmd=Hi,P.AcApDimJig=so,P.AcApDimLinearCmd=ro,P.AcApDocManager=S,P.AcApDocument=zs,P.AcApDxfConvertor=yr,P.AcApEllipseCmd=lo,P.AcApEraseCmd=Vo,P.AcApExamplePlugin=lu,P.AcApExportHtmlCmd=Dr,P.AcApFontUtil=Ei,P.AcApHatchCmd=Gi,P.AcApHtmlConvertor=Br,P.AcApHtmlSnapshotBuilder=Ir,P.AcApI18n=p,P.AcApLayerCloseCmd=Kr,P.AcApLayerCmd=Ur,P.AcApLayerCurCmd=Or,P.AcApLayerDelCmd=Mr,P.AcApLayerFreezeCmd=Bi,P.AcApLayerIsoCmd=Di,P.AcApLayerLockCmd=Nr,P.AcApLayerOnCmd=Rr,P.AcApLayerPCmd=zr,P.AcApLayerThawCmd=Vr,P.AcApLayerUnisoCmd=Gr,P.AcApLayerUnlockCmd=$r,P.AcApLayoffCmd=Mi,P.AcApLineCmd=Ze,P.AcApLineJig=Ni,P.AcApLogCmd=ia,P.AcApMLineCmd=uo,P.AcApMLineJig=ho,P.AcApMTextCmd=po,P.AcApMeasureAngleCmd=Eo,P.AcApMeasureArcCmd=jo,P.AcApMeasureAreaCmd=Mo,P.AcApMeasureDistanceCmd=zo,P.AcApMeasureDistanceJig=Ro,P.AcApMoveCmd=$o,P.AcApOffsetCmd=Nt,P.AcApOpenCmd=na,P.AcApPanCmd=la,P.AcApPluginManager=ha,P.AcApPngConvertor=wr,P.AcApPointCmd=go,P.AcApPolygonCmd=Ki,P.AcApPolylineCmd=wo,P.AcApPolylineJig=fo,P.AcApQNewCmd=sa,P.AcApRayCmd=xo,P.AcApRectCmd=Ui,P.AcApRectJig=So,P.AcApRegenCmd=ra,P.AcApRevCircleCmd=Xo,P.AcApRevCloudCmd=Yo,P.AcApRevCloudJig=Ho,P.AcApRevRectCmd=Zo,P.AcApRevVisibilityCmd=Jo,P.AcApRotateCmd=Rt,P.AcApSelectCmd=oa,P.AcApSettingManager=ye,P.AcApSketchCmd=ta,P.AcApSketchJig=ea,P.AcApSplineCmd=Co,P.AcApSplineJig=Ao,P.AcApSwitchBgCmd=ca,P.AcApSysVarCmd=aa,P.AcApXLineCmd=Lo,P.AcApZoomCmd=Je,P.AcEdBaseView=js,P.AcEdCommand=N,P.AcEdCommandLine=ps,P.AcEdCommandStack=le,P.AcEdConditionWaiter=mn,P.AcEdCorsorType=be,P.AcEdCursorManager=cs,P.AcEdHoverController=Os,P.AcEdInputManager=li,P.AcEdKeyword=sn,P.AcEdKeywordCollection=ls,P.AcEdMTextEditor=Re,P.AcEdMarker=ai,P.AcEdMarkerManager=fs,P.AcEdOpenMode=j,P.AcEdPreviewJig=$,P.AcEdPromptAngleOptions=xe,P.AcEdPromptBoxOptions=ti,P.AcEdPromptBoxResult=ii,P.AcEdPromptDistanceOptions=he,P.AcEdPromptDoubleOptions=X,P.AcEdPromptDoubleResult=ie,P.AcEdPromptEntityOptions=Le,P.AcEdPromptEntityResult=si,P.AcEdPromptIntegerOptions=on,P.AcEdPromptIntegerResult=ri,P.AcEdPromptKeywordOptions=Y,P.AcEdPromptNumericalOptions=ni,P.AcEdPromptNumericalResult=rn,P.AcEdPromptOptions=Pe,P.AcEdPromptPointOptions=D,P.AcEdPromptPointResult=oi,P.AcEdPromptResult=ae,P.AcEdPromptSelectionOptions=je,P.AcEdPromptSelectionResult=xt,P.AcEdPromptStateMachine=Te,P.AcEdPromptStatus=v,P.AcEdPromptStringOptions=ce,P.AcEdSelectionFilter=mc,P.AcEdSelectionSet=ei,P.AcEdViewMode=se,P.AcEditor=Ms,P.AcTrGeometryUtil=ki,P.AcTrView2d=fa,P.DEFAULT_VIEW_2D_OPTIONS=ns,P.acedAlert=wc,P.applyUiTheme=Ns,P.applyUiThemeFromBackground=Rs,P.captureLayerStateBeforeOperation=Vl,P.clearAllMeasurements=Yn,P.cmdDescription=an,P.colorToCssAlpha=Tn,P.cssColor=de,P.eventBus=J,P.geBox2dToThreeBox2d=Pr,P.geBox2dToThreeBox3d=Tr,P.geBox3dToGeBox2d=Ar,P.geBox3dToThreeBox3d=Cr,P.getLayerPreviousStateManager=zl,P.makeBadge=Bt,P.makeDot=Be,P.makeLiveBadge=Dt,P.makeLiveDot=vr,P.makeOverlayCanvas=qe,P.makeSnapIndicator=In,P.measurementColor=kt,P.registerMeasurementCleanup=pt,P.resolvePointerSelectionAction=Fs,P.resolveSelectionActionFromEvent=gn,P.sysCmdDescription=Ma,P.threeBox2dToGeBox2d=_r,P.threeBox3dToGeBox2d=Lr,P.threeBox3dToGeBox3d=Sr,P.userCmdDescription=Oa,P.yieldToMain=pe,Object.defineProperty(P,Symbol.toStringTag,{value:"Module"})});
|
|
880
|
+
`);if(!i.length)return[];const n=i[0].trim();return n?[n,...i.slice(1)]:[]}setActiveLayout(){const e=this.curView,t=this.curDocument.database;e.activeLayoutBtrId=t.currentSpaceId,e.modelSpaceBtrId=t.tables.blockTable.modelSpace.objectId}onBeforeOpenDocument(e){this.events.documentToBeOpened.dispatch({doc:this.context.doc,mode:this.getDocumentEventMode(e)}),this.curView.clear()}onAfterOpenDocument(e,t){if(e){const i=this.context.doc;this.events.documentActivated.dispatch({doc:i,mode:this.getDocumentEventMode(t)}),this.setActiveLayout(),this.curView.syncDisplaySysVars(i.database);const n=i.database,s=n.tables.blockTable.modelSpace.objectId,r=n.currentSpaceId!==s,a=u.acdbHostApplicationServices().layoutManager.getActiveLayout(n),c=a==null?void 0:a.limits;r&&c&&!c.isEmpty()?this.curView.zoomTo(c):!r&&!n.extents.isEmpty()?this.curView.zoomTo(new u.AcGeBox2d(n.extmin,n.extmax)):this.curView.zoomToFitDrawing(),this.curView.markLayoutAsInitialized(n.currentSpaceId)}}setOptions(e){return e==null?e={fontLoader:this._fontLoader}:e.fontLoader==null&&(e.fontLoader=this._fontLoader),e}getDocumentEventMode(e){return(e==null?void 0:e.mode)??R.Read}showBusyIndicator(){this._busyProgress.setMessage(""),this._busyProgress.show()}hideBusyIndicator(){this._busyProgress.hide()}resetOpenFileProgress(){this._openFileProgressPeak=0,this._openFileProgressStage=void 0}normalizeOpenFileProgress(e){const t=e.stage;return t!==this._openFileProgressStage&&(this._openFileProgressStage==="FETCH_FILE"&&t==="CONVERSION"&&(this._openFileProgressPeak=0),this._openFileProgressStage=t),this._openFileProgressPeak=Math.max(this._openFileProgressPeak,e.percentage),{...e,percentage:this._openFileProgressPeak}}updateProgress(e){if(e.stage==="CONVERSION"){if(e.subStage){const t="main.progress."+e.subStage.replace(/_/g,"").toLowerCase();this._progress.setMessage(g.t(t))}}else e.stage==="FETCH_FILE"&&this._progress.setMessage(g.t("main.message.fetchingDrawingFile"));ja(e)?(this._progress.hide(),this.resetOpenFileProgress()):this._progress.show()}registerConverters(e){try{const t=new u.AcDbDxfConverter({convertByEntityType:!1,useWorker:!0,parserWorkerUrl:e&&e.dxfParser?e.dxfParser:"./assets/dxf-parser-worker.js"});u.AcDbDatabaseConverterManager.instance.register(u.AcDbFileType.DXF,t)}catch(t){u.log.error("Failed to register dxf converter: ",t)}try{const t=new Ql({convertByEntityType:!1,useWorker:!0,parserWorkerUrl:e&&e.dwgParser?e.dwgParser:"./assets/libredwg-parser-worker.js"});u.AcDbDatabaseConverterManager.instance.register(u.AcDbFileType.DWG,t)}catch(t){u.log.error("Failed to register dwg converter: ",t)}}registerWorkers(e){this.registerConverters(e),Xe.getInstance().initialize(e&&e.mtextRender?e.mtextRender:"./assets/mtext-renderer-worker.js")}async loadPlugins(e){if(e){if(e.fromConfig&&e.fromConfig.length>0)try{const t=await this._pluginManager.loadPluginsFromConfig(e.fromConfig,{continueOnError:!0});t.loaded.length>0&&u.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from config:`,t.loaded),t.failed.length>0&&u.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s):`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){u.log.error("[AcApDocManager] Error loading plugins from config:",t)}if(e.fromFolder)try{const t=await this._pluginManager.loadPluginsFromFolder(e.fromFolder.folderPath,{pluginList:e.fromFolder.pluginList,continueOnError:e.fromFolder.continueOnError??!0});t.loaded.length>0&&u.log.info(`[AcApDocManager] Loaded ${t.loaded.length} plugin(s) from folder:`,t.loaded),t.failed.length>0&&u.log.warn(`[AcApDocManager] Failed to load ${t.failed.length} plugin(s) from folder:`,t.failed.map(i=>`${i.name}: ${i.error.message}`))}catch(t){u.log.error("[AcApDocManager] Error loading plugins from folder:",t)}}}}const Tu={isDebug:!1,isShowCommandLine:!0,isShowCoordinate:!0,isShowEntityInfo:!1,isShowFileName:!0,isShowLanguageSelector:!0,isShowMainMenu:!0,isShowToolbar:!0,isShowStats:!1,fontMapping:{},osnapModes:u.acdbOsnapModesToMask([u.AcDbOsnapMode.EndPoint,u.AcDbOsnapMode.MidPoint,u.AcDbOsnapMode.Center,u.AcDbOsnapMode.Quadrant,u.AcDbOsnapMode.Nearest])},Na="settings";class me{constructor(){this.events={modified:new u.AcCmEventManager}}static get instance(){return this._instance||(this._instance=new me),this._instance}set(e,t){const i=this.settings;i[e]=t,localStorage.setItem(Na,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 isShowEntityInfo(){return this.get("isShowEntityInfo")}set isShowEntityInfo(e){this.set("isShowEntityInfo",e)}get isShowFileName(){return this.get("isShowFileName")}set isShowFileName(e){this.set("isShowFileName",e)}get isShowLanguageSelector(){return this.get("isShowLanguageSelector")}set isShowLanguageSelector(e){this.set("isShowLanguageSelector",e)}get isShowMainMenu(){return this.get("isShowMainMenu")}set isShowMainMenu(e){this.set("isShowMainMenu",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 osnapModes(){return this.get("osnapModes")}set osnapModes(e){this.set("osnapModes",e)}get settings(){const e=localStorage.getItem(Na),t=e==null?{}:JSON.parse(e);return Ke.defaults(t,Tu)}}class Iu extends j{async execute(e){u.log.info("Hello from ExamplePlugin!"),u.log.info("Current document:",e.doc),u.log.info("Current view:",e.view)}}class Eu{constructor(){this.name="ExamplePlugin",this.version="1.0.0",this.description="An example plugin demonstrating the plugin system",this.registeredCommands=[]}onLoad(e,t){t.addCommand("USER","HELLO","Hello",new Iu),this.registeredCommands.push({group:"USER",name:"HELLO"}),u.log.info(`[${this.name}] Plugin loaded successfully`),u.log.info(`[${this.name}] Registered command: HELLO`)}onUnload(e,t){for(const i of this.registeredCommands)t.removeCmd(i.group,i.name);this.registeredCommands=[],u.log.info(`[${this.name}] Plugin unloaded`)}}Object.defineProperty(_,"AcGiTextParagraphAlignment",{enumerable:!0,get:()=>B.MTextParagraphAlignment}),Object.defineProperty(_,"MTextColor",{enumerable:!0,get:()=>B.MTextColor}),Object.defineProperty(_,"MTextParagraphAlignment",{enumerable:!0,get:()=>B.MTextParagraphAlignment}),Object.defineProperty(_,"ShxParserFont",{enumerable:!0,get:()=>B.ShxParserFont}),_.AcApAnnotation=fe,_.AcApArcCmd=ao,_.AcApBaseRevCmd=mt,_.AcApCircleCmd=po,_.AcApCircleJig=zi,_.AcApClearMeasurementsCmd=ts,_.AcApContext=ys,_.AcApConvertToDxfCmd=Vr,_.AcApConvertToPngCmd=Kr,_.AcApCopyCmd=Ji,_.AcApDimJig=mo,_.AcApDimLinearCmd=fo,_.AcApDocManager=A,_.AcApDocument=Or,_.AcApDxfConvertor=zr,_.AcApEllipseCmd=vo,_.AcApEraseCmd=oa,_.AcApExamplePlugin=Eu,_.AcApFontUtil=Xi,_.AcApHatchCmd=$i,_.AcApI18n=g,_.AcApLayerCloseCmd=eo,_.AcApLayerCmd=to,_.AcApLayerCurCmd=$r,_.AcApLayerDelCmd=Ur,_.AcApLayerFreezeCmd=Oi,_.AcApLayerIsoCmd=Fi,_.AcApLayerLockCmd=Yr,_.AcApLayerOnCmd=Xr,_.AcApLayerPCmd=qr,_.AcApLayerThawCmd=Zr,_.AcApLayerUnisoCmd=Jr,_.AcApLayerUnlockCmd=Qr,_.AcApLayoffCmd=Ri,_.AcApLineCmd=Ze,_.AcApLineJig=Vi,_.AcApLogCmd=xa,_.AcApMLineCmd=So,_.AcApMLineJig=xo,_.AcApMTextCmd=Ao,_.AcApMeasureAngleCmd=Xo,_.AcApMeasureArcCmd=ia,_.AcApMeasureAreaCmd=Qo,_.AcApMeasureDistanceCmd=ra,_.AcApMeasureDistanceJig=sa,_.AcApMoveCmd=ca,_.AcApOffsetCmd=Gt,_.AcApOpenCmd=Sa,_.AcApPanCmd=Ta,_.AcApPluginManager=Ia,_.AcApPngConvertor=Gr,_.AcApPointCmd=Co,_.AcApPolygonCmd=Hi,_.AcApPolylineCmd=To,_.AcApPolylineJig=Lo,_.AcApQNewCmd=Aa,_.AcApRayCmd=Eo,_.AcApRectCmd=Yi,_.AcApRectJig=Bo,_.AcApRegenCmd=Ca,_.AcApRevCircleCmd=pa,_.AcApRevCloudCmd=ga,_.AcApRevCloudJig=da,_.AcApRevRectCmd=fa,_.AcApRevVisibilityCmd=ya,_.AcApRotateCmd=Kt,_.AcApSelectCmd=Pa,_.AcApSettingManager=me,_.AcApSketchCmd=va,_.AcApSketchJig=ba,_.AcApSplineCmd=Mo,_.AcApSplineJig=Do,_.AcApSwitchBgCmd=La,_.AcApSysVarCmd=_a,_.AcApXLineCmd=Ro,_.AcApZoomCmd=Qe,_.AcEdBaseView=Mr,_.AcEdCommand=j,_.AcEdCommandLine=hr,_.AcEdCommandStack=he,_.AcEdConditionWaiter=Mn,_.AcEdCorsorType=be,_.AcEdCursorManager=qs,_.AcEdHoverController=Br,_.AcEdInputManager=Pi,_.AcEdKeyword=An,_.AcEdKeywordCollection=or,_.AcEdMTextEditor=Ne,_.AcEdMarker=Ai,_.AcEdMarkerManager=pr,_.AcEdOpenMode=R,_.AcEdPreviewJig=$,_.AcEdPromptAngleOptions=ve,_.AcEdPromptBoxOptions=yi,_.AcEdPromptBoxResult=wi,_.AcEdPromptDistanceOptions=ue,_.AcEdPromptDoubleOptions=q,_.AcEdPromptDoubleResult=se,_.AcEdPromptEntityOptions=Le,_.AcEdPromptEntityResult=vi,_.AcEdPromptIntegerOptions=Pn,_.AcEdPromptIntegerResult=xi,_.AcEdPromptKeywordOptions=X,_.AcEdPromptNumericalOptions=bi,_.AcEdPromptNumericalResult=Cn,_.AcEdPromptOptions=_e,_.AcEdPromptPointOptions=D,_.AcEdPromptPointResult=Si,_.AcEdPromptResult=ce,_.AcEdPromptSelectionOptions=Re,_.AcEdPromptSelectionResult=It,_.AcEdPromptStateMachine=Te,_.AcEdPromptStatus=S,_.AcEdPromptStringOptions=le,_.AcEdSelectionFilter=$l,_.AcEdSelectionSet=fi,_.AcEdViewMode=oe,_.AcEditor=kr,_.AcTrGeometryUtil=qi,_.AcTrScene=Ma,_.AcTrView2d=Ra,_.DARK_THEME_FOREGROUND=Vs,_.DEFAULT_VIEW_2D_OPTIONS=ds,_.LIGHT_THEME_FOREGROUND=Gs,_.MODEL_SPACE_BACKGROUND=qe,_.PAPER_SPACE_BACKGROUND=zs,_.POLARMODE_ADDITIONAL_ANGLES=Qs,_.POLARMODE_POLAR_TRACKING=at,_.acedAlert=Yl,_.applyUiTheme=ql,_.canvasBackgroundFromColor=Ys,_.captureLayerStateBeforeOperation=oh,_.clearAllMeasurements=es,_.cmdDescription=_n,_.colorToCssAlpha=ns,_.constrainToOrtho=Js,_.constrainToTracking=rr,_.contrastingForegroundColor=vn,_.cssColor=pe,_.cursorColorForBackground=pi,_.eventBus=ee,_.foregroundColorForBackground=xn,_.foregroundColorFromColorTheme=Xc,_.geBox2dToThreeBox2d=Uo,_.geBox2dToThreeBox3d=Wo,_.geBox3dToGeBox2d=Vo,_.geBox3dToThreeBox3d=Go,_.getDrawingExportBaseName=jo,_.getLayerPreviousStateManager=rh,_.getPolaraddang=ir,_.getPolarang=tr,_.getPolarmode=mi,_.isLightBackground=Lt,_.isLightColorTheme=qc,_.isModelSpaceDatabase=Hs,_.isOpenFileProgressComplete=ja,_.isOrthoModeEnabled=Zs,_.isPolarTrackingEnabled=nr,_.layoutBackgroundSysVar=Sn,_.makeBadge=zt,_.makeDot=Ee,_.makeLiveBadge=Vt,_.makeLiveDot=No,_.makeOverlayCanvas=Je,_.makeSnapIndicator=ss,_.measurementColor=Nt,_.readLayoutBackgroundColor=gi,_.registerMeasurementCleanup=pt,_.resetExportDownloadNamesForTests=$h,_.resolveExportDownloadName=Uh,_.resolvePointerSelectionAction=Dr,_.resolveSelectionActionFromEvent=Dn,_.sysCmdDescription=hl,_.threeBox2dToGeBox2d=Ko,_.threeBox3dToGeBox2d=$o,_.threeBox3dToGeBox3d=zo,_.toggleBlackWhiteBackgroundColor=Xs,_.togglePolarTracking=nl,_.userCmdDescription=ul,_.yieldToMain=Wh,Object.defineProperty(_,Symbol.toStringTag,{value:"Module"})});
|