@maqiuyao/dxf-viewer 0.2.1 → 0.2.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/dist/dxf-viewer.cjs +1 -1
- package/dist/dxf-viewer.js +188 -170
- package/package.json +1 -1
package/dist/dxf-viewer.cjs
CHANGED
|
@@ -793,7 +793,7 @@ void main() {
|
|
|
793
793
|
`&&s++,i=s+1}}return e.push(t.substring(i,t.length)),e}}function Pe(h,t,e){return h.code===t&&h.value===e}function Qe(h){S.trace("unhandled group "+Cn(h))}function Cn(h){return h.code+":"+h.value}const Sn="0.4.0",On="VERSION",Jl=()=>window.localStorage.getItem(On),Ql=()=>{window.localStorage.setItem(On,Sn)},eh=()=>Jl()!==Sn?(Ql(),!0):!1,Tt=class Tt{constructor(){p(this,"DATABASE_NAME","x_viewer");p(this,"DEFAULT_TABLES",[{name:"dxf_data",options:{keyPath:"dxfDataId",autoIncrement:!1}},{name:"fonts",options:{keyPath:"fileName",autoIncrement:!0}}]);p(this,"db");p(this,"tables");this.db=void 0,this.tables=this.DEFAULT_TABLES}static instance(){return!Tt._instance&&(Tt._instance=new Tt),Tt._instance}setTables(t){this.tables=t}getTables(){return this.tables}async getDatabase(){let t=await this.getDB(this.DATABASE_NAME);return this.db||(t.close(),eh()&&await this.deleteDataBase(this.DATABASE_NAME),t=await this.getUpgradedDB(t)),t.onclose=()=>{this.db=void 0,S.debug("[DB] Db "+t.name+" is closed.")},t.onerror=e=>{this.db=void 0,S.debug("[DB] Db "+t.name+" encountered error.",e)},t.onabort=e=>{this.db=void 0,S.debug("[DB] Db "+t.name+" aborted.",e)},t.onversionchange=e=>{S.debug("onversionchange",e)},this.db=t,Promise.resolve(this.db)}closeDatabase(){this.db&&this.db.close()}deleteDataBase(t){return new Promise((e,i)=>{const s=window.indexedDB.deleteDatabase(t);s.onerror=r=>{S.debug(r),i(r)},s.onsuccess=r=>{const n=r.target;S.debug("[DB] Db "+t+" delete old version "+r.oldVersion+"."),e(n)}})}async getDB(t){return new Promise((e,i)=>{const s=window.indexedDB.open(t);s.onerror=i,s.onsuccess=r=>{const n=r.target.result;S.debug("[DB] Db "+n.name+" opened (version "+n.version+")."),e(n)}})}async getUpgradedDB(t){return new Promise((e,i)=>{S.debug("[DB] Upgrading db "+t.name+" (version "+t.version+")");const s=window.indexedDB.open(t.name,t.version+1);s.onerror=i,s.onblocked=r=>{S.debug("onblocked",r)},s.onupgradeneeded=r=>{const n=r.target.transaction;n.oncomplete=()=>{S.debug("[DB] Upgrade is done (new version: "+a.version+").")};const a=r.target.result,o=[];for(let l=0;l<this.tables.length;++l){const c=this.tables[l];if(!a.objectStoreNames.contains(c.name)){S.debug("[DB] Creating table "+c.name+"...");const u=this.createTable(a,c.name,c.options,c.indexArray);o.push(u)}}o.length>0&&Promise.all(o).then(()=>{S.debug("[DB] All("+o.length+") tables created.")})},s.onsuccess=r=>{const n=r.target.result;S.debug("[DB] Db "+n.name+" opened (version "+n.version+")."),e(n)}})}async createTable(t,e,i,s){return new Promise(r=>{const n=t.createObjectStore(e,i);s&&s.forEach(a=>{n.createIndex(a.name,a.fields,{unique:a.unique})}),S.debug("[DB] Table "+e+" created."),r(t)})}};p(Tt,"_instance");let ae=Tt;class En{constructor(){p(this,"db");p(this,"isCreatingTable");if(this.db=void 0,this.isCreatingTable=!1,ae.instance().getTables().findIndex(i=>i.name===this.tableName())===-1)throw new Error("Failed to find table '"+this.tableName()+"' from indexeddb!")}tableName(){throw new Error("Derived class have to override 'tableName', and set a proper table name!")}add(t,e,i){const s=this.tableName();ae.instance().getDatabase().then(r=>{const n=r.transaction([s],"readwrite").objectStore(s),a=n.add(t);a.onsuccess=e,a.onerror=i}).finally(()=>{ae.instance().closeDatabase()}).catch(r=>{i&&i(r)})}save(t,e,i){const s=this.tableName();ae.instance().getDatabase().then(r=>{const n=r.transaction([s],"readwrite").objectStore(s),a=n.put(t);a.onsuccess=e,a.onerror=i}).finally(()=>{ae.instance().closeDatabase()})}delete(t,e,i){const s=this.tableName();ae.instance().getDatabase().then(r=>{const n=r.transaction([s],"readwrite").objectStore(s),a=n.delete(t);a.onsuccess=e,a.onerror=i}).finally(()=>{ae.instance().closeDatabase()})}update(){ae.instance().getDatabase().then(()=>{})}query(t,e){const i=this.tableName();ae.instance().getDatabase().then(s=>{const r=s.transaction([i],"readonly").objectStore(i),n=r.openCursor();n.onsuccess=a=>{const o=a.target.result;o&&o.continue(),t&&t(o)},n.onerror=e}).finally(()=>{ae.instance().closeDatabase()})}queryByIndex(t,e,i,s){const r=this.tableName();ae.instance().getDatabase().then(n=>{const a=n.transaction([r],"readonly").objectStore(r),o=a.index(t).get(e);o.onerror=s,o.onsuccess=function(l){const c=l.target?.result;i&&i(c)}}).finally(()=>{ae.instance().closeDatabase()})}queryAll(t,e){const i=this.tableName();ae.instance().getDatabase().then(s=>{const r=s.transaction([i],"readonly").objectStore(i),n=r.getAll();n.onsuccess=a=>{t&&t(a.target.result)},n.onerror=e}).finally(()=>{ae.instance().closeDatabase()})}clearAll(t,e){const i=this.tableName();ae.instance().getDatabase().then(s=>{const r=s.transaction([i],"readwrite").objectStore(i),n=r.clear();n.onsuccess=a=>{t&&t(a)},n.onerror=a=>{e&&e(a)}}).finally(()=>{ae.instance().closeDatabase()})}}const Ct=class Ct extends En{tableName(){return"dxf_data"}static instance(){return!Ct._instance&&(Ct._instance=new Ct),Ct._instance}query(t,e,i){const s=[],r=this.tableName();ae.instance().getDatabase().then(n=>{const a=n.transaction([r],"readonly").objectStore(r),o=a.get(t);o.onerror=l=>{i&&i(l),S.info("[DxfDataTable] Failed to query !",l)},o.onsuccess=()=>{o.result&&s.push(o.result),e&&e(s)}}).finally(()=>{ae.instance().closeDatabase()})}};p(Ct,"_instance");let Yi=Ct;const Ae=new d.Vector3(1,0,0),ds=new d.Vector3(0,1,0),Et=new d.Vector3(0,0,1),Cr=new d.Vector3(0,0,0),ct=16777215,th="CONTINUOUS",Ei=new d.PointsMaterial({color:ct}),le=new d.LineBasicMaterial({color:ct}),_t=new d.MeshBasicMaterial({color:ct}),Sr=new d.BufferGeometry().setFromPoints([new d.Vector3]),Or=new d.Matrix4,Fe=new d.Matrix4,ne=new d.Matrix4,j=new d.Vector3,Z=new d.Vector3,ze=new d.Vector3,Qt=new d.Vector2,he=new d.Quaternion,_i=new d.Object3D,We=new d.Box3,Er=new d.PointsMaterial({color:65280,size:5,depthTest:!1}),_r=new d.PointsMaterial({color:65280,depthTest:!1}),Pr=new d.PointsMaterial({color:65280,depthTest:!1}),ih=h=>h.viewDirectionFromTarget!==void 0,sh=h=>{if(h){const t=h.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);if(t&&t.length>0){const e=t[1],i=h.replace("data:"+e+";","").split(",");if(i&&i.length===2&&i[0]==="base64"){const s=i[1];return qa.decode(s)}}}return null},Ar=(h,t)=>{const e=new d.Vector2(h.x,h.y),i=new d.Vector2(t.x,t.y);return i.sub(e),i.normalize(),i.y<0?-Math.acos(i.x):Math.acos(i.x)},Ir=(h,t,e)=>({x:h.x+t*Math.cos(e),y:h.y+t*Math.sin(e)}),rh=(h,t,e,i)=>{const s=h?new d.Vector2(h.x,h.y):new d.Vector2(0,0),r=t?new d.Vector2(t.x,t.y):new d.Vector2(1,0);e=e||1;const n=4*Math.atan(e),a=s.distanceTo(r)/2/Math.sin(n/2),o=Ir(h,a,Ar(s,r)+(Math.PI/2-n/2));i=i||Math.max(Math.abs(Math.ceil(n/(Math.PI/18))),6);const l=Ar(o,s),c=n/i,u=[];u.push(new d.Vector3(s.x,s.y,0));for(let f=1;f<=i-1;f++){const m=Ir(o,Math.abs(a),l+c*f);u.push(new d.Vector3(m.x,m.y,0))}return u},kr=(h,t,e,i=h.length*2,s)=>{const r=[];if(!h||h.length<t+1||t<1)return r;const n=h.map(a=>[a.x,a.y]);try{for(let a=0;a<1;a+=1/i){const o=mn(a,t,n,e,s);r.push(new d.Vector3(o[0],o[1],0))}}catch{if(r.length===0)return r}return r},us=(h,t=!1)=>{const e=[],i=h.length;for(let s=0;s<i;s++){const r=h[s];if(r.bulge&&(s!==i-1||t)){const n=r.bulge,a=s+1<i?h[s+1]:e[0],o=rh(r,a,n);e.push(...o)}else e.push(new d.Vector3(r.x,r.y,0))}return e},nh=h=>{const t=[];return h.faceA&&t.push(h.faceA),h.faceB&&t.push(h.faceB),h.faceC&&t.push(h.faceC),h.faceD&&t.push(h.faceD),t},ah=h=>{const t=[],e=[];h.forEach(s=>{s.polyfaceMeshVertex&&(s.threeDPolylineMesh?t.push(new d.Vector3(s.x,s.y,s.z)):e.push(nh(s)))});const i=[];for(let s=0;s<e.length;s++){const r=e[s];if(r.length===0)continue;const n=[];let a=!0;for(let o=0;o<r.length;o++){const l=r[o]-1;if(l>=t.length||l<0){a=!1;break}n.push(t[l])}!a||n.length===0||(n.push(n[0]),i.push(n))}return i},V=class V extends d.Loader{constructor(e,i){super(e);p(this,"timer");p(this,"ignorePaperSpace");p(this,"font");p(this,"encoding");p(this,"overrideColor");p(this,"overrideHatchPatternLineThickness");p(this,"angBase");p(this,"angDir");p(this,"header");p(this,"pointsMaterials");p(this,"lineBasicMaterials");p(this,"lineShaderMaterials");p(this,"meshBasicMaterials");p(this,"meshTextureMaterials");p(this,"hatchShaderMaterials");p(this,"entityCount");p(this,"curveCount");p(this,"averageCurveSize");p(this,"enableRenderOrder");p(this,"enableLocalCache");p(this,"enableReleaseData");p(this,"enableMerge");p(this,"enableRTC");p(this,"enablePlineWidth");p(this,"dxfDataId");p(this,"compareContext");p(this,"statsInfo");p(this,"llbDatas");p(this,"mtextDatas");p(this,"requestHeader");p(this,"blockReferencesCache");p(this,"blockRecordsCache");p(this,"entitiesCache");p(this,"blocksCache");p(this,"dictionaryOwnerHandleAndSpatialFilterHandlesCache");p(this,"spatialFiltersCache");p(this,"entityThreejsCache");p(this,"entityTypesAndTimes");p(this,"nonSnapableTypes");p(this,"layoutsSnapObjectsMap");p(this,"aborted");p(this,"entityHandlesWithRenderOrder");p(this,"addViewport");this.timer=Date.now(),this.ignorePaperSpace=!1,this.encoding="UTF-8",this.angBase=0,this.angDir=0,this.header=void 0,this.pointsMaterials={},this.lineBasicMaterials={},this.lineShaderMaterials={},this.meshBasicMaterials={},this.meshTextureMaterials={},this.hatchShaderMaterials=[],this.entityCount=0,this.curveCount=0,this.averageCurveSize=0,this.enableRenderOrder=!1,this.enableLocalCache=!1,this.enableReleaseData=!0,this.enableMerge=!0,this.enableRTC=!0,this.enablePlineWidth=!0,this.dxfDataId=void 0,this.compareContext=void 0,this.statsInfo={unsupportedEntity:{},unsupportedEntityTypes:{},unsupportedTextStyles:{},unsupportedHatchPatterns:{},unsupportedPolylineCount:0,invisibleEntities:{},ignoredFrozenLayersAndEntityCount:{},ignoredInserts:{},entityTypesAndMeshCount:{},ignoredPaperSpaceEntityTypesAndCount:{},rebasedEntityCount:0,requestHeader:{}},this.llbDatas=[],this.mtextDatas=[],this.blockReferencesCache={},this.blockRecordsCache=void 0,this.entitiesCache=void 0,this.blocksCache=void 0,this.dictionaryOwnerHandleAndSpatialFilterHandlesCache=void 0,this.spatialFiltersCache=void 0,this.entityThreejsCache=void 0,this.entityTypesAndTimes=void 0,this.nonSnapableTypes=new Set(["ATTDEF","ATTRIB","LEADER","MTEXT","MULTILEADER","OLE2FRAME","TEXT"]),this.layoutsSnapObjectsMap={},this.aborted=!1,this.entityHandlesWithRenderOrder={},this.addViewport=(s,r)=>{if(s.type==="VIEWPORT"){!r[s.ownerHandle]&&(r[s.ownerHandle]=[]);const n=s;r[s.ownerHandle].push(n)}},i&&(this.ignorePaperSpace=i.ignorePaperSpace===!0,this.enableLocalCache=i.enableLocalCache===!0,this.enableMerge=V.LOADLLDATA?!1:i.enableMerge!==!1,this.encoding=i.encoding||"UTF-8",i.overrideColor!=null&&(this.overrideColor=qt.rgb2Hex(i.overrideColor)),i.overrideHatchPatternLineThickness!=null&&(this.overrideHatchPatternLineThickness=i.overrideHatchPatternLineThickness)),this.pointsMaterials[ct]=Ei,this.lineBasicMaterials[ct]=le,this.meshBasicMaterials[ct]=_t}setRequestHeader(e){this.requestHeader=e}setFont(e){this.font=e}async download(e,i){let s=sh(e);if(!s){const r=Date.now(),n=new d.FileLoader(this.manager),a=V.REQUWSTHEADER;a&&n.setRequestHeader(a),n.setResponseType("arraybuffer"),n.setPath(this.path),s=await n.loadAsync(e,i),S.info("[Dxf] "+e+" dxf file downloaded in "+(Date.now()-r)/1e3+"s")}return s}async loadEx(e,i,s){return this.enableLocalCache&&i&&(i=i.trim()).length>0&&(this.dxfDataId=i),this.loadAsync(e,s)}async loadAsync(e,i){const s=z.getUpdateSubProgressFunc(0,50,i),r=z.getUpdateSubProgressFunc(50,100,i),n=z.getUpdateSubProgressFunc(10,100,i);if(be.isBrowser&&this.enableLocalCache&&this.dxfDataId){let l;try{if(this.timer=Date.now(),l=await this.getDxfDataFromIndexedDb(this.dxfDataId),l){this.tryFixDxfData(l),S.info("[Dxf] Loaded DxfData from indexedDb in "+(Date.now()-this.timer)/1e3+"s");const c=await this.loadEntities(l,n);return Promise.resolve(c)}}catch(c){S.warn("[Dxf] Failed to parse data from indexedDb",c)}}const a=await this.parse(e,s);return this.tryFixDxfData(a),await this.loadEntities(a,r)}async parse(e,i){const s=z.getUpdateProgressFunc(i),r=z.getUpdateSubProgressFunc(0,40,i),n=await this.download(e,r);if(!n)return Promise.reject("[Dxf] Failed to download "+e);if(this.aborted)return Promise.reject("[Dxf] Job aborted");this.timer=Date.now(),S.info("[Dxf] Start parsing...");const a=new Tn(this.encoding).parseSync(n);if(this.tryFixDxfData(a),s(80),S.info("[Dxf] Parsed in "+(Date.now()-this.timer)/1e3+"s, creating entities..."),this.aborted)return Promise.reject("[Dxf] Job aborted");if(a&&be.isBrowser&&this.enableLocalCache&&this.dxfDataId){const o=Date.now();try{await this.setDxfDataToIndexedDb(this.dxfDataId,a),S.info("[Dxf] Saved to indexedDb in "+(Date.now()-o)/1e3+"s")}catch(l){S.warn("[Dxf] Failed to save '"+this.dxfDataId+"' to indexedDb!",l)}}return s(100),a}abort(){this.aborted=!0}isAborted(){return this.aborted}parseHeader(e){if(!e){S.error("[Dxf]: Invalid header!");return}this.header=e;const i=e.$ACADVER.toString();i!=="AC1032"&&S.warn("[Dxf] Unexpected version: "+i+". But we'll try to continue."),this.angBase=e.$ANGBASE||0,this.angDir=e.$ANGDIR||0}tryFixDxfData(e){e&&(!e.objects&&(S.warn("[Dxf] No objects found, Will add one."),e.objects={}),!e.objects.LAYOUT&&(S.warn("[Dxf] No layout defined! Will add a default 'Model' layout!"),e.objects.LAYOUT=[{layoutName:V.MODEL_LAYOUT_NAME}]),!e.tables&&(S.warn("[Dxf] No tables found, Will add one."),e.tables={}),!e.tables.layer&&(e.tables.layer={}),!e.tables.layer.layers&&(e.tables.layer.layers={}))}async loadEntities(e,i){const s=Date.now();this.parseHeader(e.header),this.enableRenderOrder&&(this.initRenderOrderInfo(e),this.enableMerge=!1),this.getFontFilesFromDxf(e);let r=0;const n=e.entities.length;this.entityCount=n,Object.keys(e.blocks).forEach(b=>{this.entityCount+=e.blocks[b].entities?.length||0});const a=z.getUpdateProgressFuncForLoop(n,i);let o={};const l=b=>{const E=b.userData.layerName;let O=o[E];!O&&(O=[],o[E]=O),O.push(b)},c={},u={},f=new F;for(let b=0;b<n&&!this.aborted;b++){const E=e.entities[b];this.addViewport(E,c);const O=this.loadEntity(E,e);if(!O&&await a(b),!O)continue;const _=this.getLayout(e,E),C=_.layoutName;let w=f.children.find(M=>M.name===C);if(!w&&(w=new F,w.name=C,w.userData.isLayoutLevelObject=!0,f.add(w)),O.traverse(M=>{M.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[C]&&(this.layoutsSnapObjectsMap[C]=[]),this.layoutsSnapObjectsMap[C].push(M))}),this.enableMerge){et.merge(O,!1),!u[C]&&(u[C]={object:w,layerObjects:{}});const P=u[C];if(O.geometry){const A=O.userData.layerName;!P.layerObjects[A]&&(P.layerObjects[A]=[]),P.layerObjects[A].push(O),O.children.forEach(I=>{I.userData.isSnapObject&&l(I)})}else O.children.length>0&&(w.add(O),O.traverse(A=>{A.geometry&&l(A)}))}else w.add(O),O.traverse(M=>{M.geometry&&l(M)});r++,await a(b)}e.objects.LAYOUT.forEach(b=>{const E=b,O=E.layoutName;if(this.ignorePaperSpace&&O!==V.MODEL_LAYOUT_NAME)return;const _=E.associatedBlockName,C=e.blocks[_];C&&this.loadLayout(C,e,E,f,o,c)}),S.debug("[Dxf] Drew entities in "+(Date.now()-s)/1e3+"s");for(const b in this.layoutsSnapObjectsMap){const E=f.children.find(C=>C.name===b),O=new F;O.name=V.SNAP_GROUP_NAME,O.userData.isSnapGroup=!0,E.add(O);const _=this.layoutsSnapObjectsMap[b];for(let C=0;C<_.length;C++){const w=_[C],M=w.userData.layerName;this.getLayerVisible(e,M)===!1&&w.layers.disable(Ce),V.SHOW_SNAP_OBJECT&&(w.layers.enableAll(),w.material instanceof d.PointsMaterial?w.material=Er:w.material instanceof d.LineBasicMaterial?w.material=_r:w.material instanceof d.MeshBasicMaterial&&(w.material=Pr));let P=w;const A=ne.identity();for(;P&&P.userData.isLayoutLevelObject!==!0;)A.premultiply(P.matrix),P=P.parent;w.matrix.copy(A),O.add(w)}}if(this.enableMerge)for(const b in u){const E=u[b],O=E.object;for(const _ in E.layerObjects){const C=E.layerObjects[_],w=et.deepMerge(C,void 0,!1,!1,!0),M=w.added,P=w.removed;if(P.length!==C.length){let A=P;P.length>=100&&(A=new Set(P));const I=k=>Array.isArray(A)?A.indexOf(k)>=0:A.has(k);for(let k=0,B=C.length;k<B;k++){const L=C[k];!I(L)&&(O.add(L),l(L))}}for(let A=0;A<M.length;A++){const I=M[A];O.add(I),l(I)}E.layerObjects[_]=[]}}this.printStatsInfo(),this.enableReleaseData&&(this.releaseCachedData(),this.releaseDxfData(e)),this.enableMerge&&V.mergeDxfObjects({root:f,layersAndObjects:o});const g=f.convertToThreejsObject();f.clear(),o={};const x={};e.objects.LAYOUT.forEach(b=>{const E=b;x[E.layoutName]=E});const y={},T=b=>{const E=b.userData.layerName;let O=y[E];!O&&(O=[],y[E]=O),O.push(b)};g.children.forEach(b=>{if($.setSharedVariablesOfObject(b),!b.userData.isLayoutLevelObject)return;const E=b.name;let O;if(E!==V.MODEL_LAYOUT_NAME){const _=x[E];!_.directAssociatedLeafObjectSet&&(_.directAssociatedLeafObjectSet=new Set),O=_.directAssociatedLeafObjectSet}b.traverse(_=>{if($.setSharedVariablesOfObject(_),_.userData.isSnapGroup&&(_.visible=V.SHOW_SNAP_OBJECT),_.geometry){const C=_.userData.layerName;this.getLayerVisible(e,C)===!1&&(_.visible=!1,_.userData.layerVisible=!1),T(_),O&&O.add(_)}})}),S.info("[Dxf] loadEntities() done in "+(Date.now()-s)/1e3+"s");const v=Object.assign(Object.assign({},e),{threejsObject:g,layersAndThreejsObjects:y,loadedEntityCount:r,layoutViewportsMap:c});if(V.LOADLLDATA){const b=g.children[0].children,E=[];for(let O=0;O<b.length;O++){const _=b[O];if(_?.userData?.llbData){const C=new d.Box3().setFromObject(_);C.getSize(new d.Vector3);const w=C.getCenter(new d.Vector3);E.push({..._,boundingBox:{max:C.max,min:C.min,center:w}})}else if(_.children&&_.children.some(C=>C.userData?.llbData))for(let C=0;C<_.children.length;C++){const w=_.children[C];if(w.userData?.llbData){w.updateWorldMatrix(!0,!0);const M=new d.Box3().setFromObject(w);M.getSize(new d.Vector3);const P=M.getCenter(new d.Vector3);E.push({...w,boundingBox:{max:M.max,min:M.min,center:P}})}}}v.llbMesh=E}return Promise.resolve(v)}getFontFilesFromDxf(e){const i=new Set,s=e.tables?.style?.styles;if(s)for(const r in s){const n=s[r],a=n.fontFile,o=n.bigFontFile;a&&i.add(a),o&&i.add(o)}S.info("[Dxf] Fonts used by dxf: "+Array.from(i).join())}async loadEntitiesForCompare(e,i,s,r=!0,n){const a=e.entities.length,o=i.entities.length,l=async()=>{const u=this.compareContext,f=u.isTheFirstFile,m=f?e:i,g=new F,x=f?a:o;this.entityCount=x,Object.keys(m.blocks).forEach(w=>{this.entityCount+=m.blocks[w].entities?.length||0});const y=Math.round(Math.pow(x,.5));let T=Date.now();const v=async w=>{if(n&&(w%y===0||w===x-1)){let M=w+1;!f&&(M+=a),n(new ProgressEvent("parseProgress",{loaded:M,total:a+o}));const P=500,A=Date.now();(A-T>P||w===x-1)&&(await z.sleep(0),T=A)}};this.parseHeader(m.header);let b={};for(let w=0;w<x;w++){if(this.aborted)return;const M=m.entities[w],P=this.getLayout(m,M);if(P.layoutName!==V.MODEL_LAYOUT_NAME){await v(w);continue}const A=this.loadEntity(M,m);if(!A){await v(w);continue}let I=g.children.find(k=>k.name===V.MODEL_LAYOUT_NAME);!I&&(I=new F,I.name=V.MODEL_LAYOUT_NAME,I.userData.isLayoutLevelObject=!0,g.add(I)),I.add(A),A.traverse(k=>{if(k.geometry){const B=k.userData.layerName,L=this.getLayerVisible(m,B);k.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[P.layoutName]&&(this.layoutsSnapObjectsMap[P.layoutName]=[]),this.layoutsSnapObjectsMap[P.layoutName].push(k),L===!1&&A.layers.disable(Ce));let q=b[B];!q&&(q=[],b[B]=q),q.push(k)}}),await v(w)}r&&f&&!u.preservedHandles&&(u.preservedHandles=new Set);for(const w in s){const M=s[w];f&&(M.type===Te.Added||M.type===Te.Modified)&&(u.preservedHandles?.add(M.handle),M.parentHandles&&M.parentHandles.forEach(A=>u.preservedHandles?.add(A)));let P=this.entityThreejsCache&&this.entityThreejsCache[M.handle];if(M.parentHandles&&(P=this.entityThreejsCache&&this.entityThreejsCache[M.parentHandles[M.parentHandles.length-1]]),P){if(P.parent&&P.parent.userData.originalType){this.setObjectColorByChange(P,{type:Te.NoChange});continue}P=this.setObjectColorByChange(P,M)}if(M.type!==Te.NoChange&&P){let A=P.parent;const I=ne.identity();for(;A&&A.userData.isLayoutLevelObject!==!0;)I.premultiply(A.matrix),A=A.parent;We.makeEmpty();const k=F.getBox(P,We);k.applyMatrix4(I),M.type===Te.Added?!f&&(M.box=new d.Box3().copy(k)):M.type===Te.Removed?f&&(M.box=new d.Box3().copy(k)):M.type===Te.Modified&&(M.box?M.box.union(k):M.box=new d.Box3().copy(k))}}for(const w in this.layoutsSnapObjectsMap){const M=g.children.find(I=>I.name===w),P=new F;P.name=V.SNAP_GROUP_NAME,M.add(P);const A=this.layoutsSnapObjectsMap[w];for(let I=0;I<A.length;I++){const k=A[I];V.SHOW_SNAP_OBJECT&&(k.layers.enableAll(),k.material instanceof d.PointsMaterial?k.material=Er:k.material instanceof d.LineBasicMaterial?k.material=_r:k.material instanceof d.MeshBasicMaterial&&(k.material=Pr));let B=k;const L=ne.identity();for(;B&&B.userData.isLayoutLevelObject!==!0;)L.premultiply(B.matrix),B=B.parent;k.matrix.copy(L),P.add(k)}}this.enableMerge&&V.mergeDxfObjects({root:g,layersAndObjects:b});const E=g.convertToThreejsObject();g.clear(),b={};const O={},_=w=>{const M=w.userData.layerName;let P=O[M];!P&&(P=[],O[M]=P),P.push(w)};E.children.forEach(w=>{$.setSharedVariablesOfObject(w),w.userData.isLayoutLevelObject&&w.traverse(M=>{if($.setSharedVariablesOfObject(M),M.userData.isSnapGroup&&(M.visible=V.SHOW_SNAP_OBJECT),M.geometry){const P=M.userData.layerName;this.getLayerVisible(m,P)===!1&&(M.visible=!1,M.userData.layerVisible=!1),_(M)}})});const C=m;C.threejsObject=E,C.layersAndThreejsObjects=O,C.layoutViewportsMap={}};let c=Date.now();this.compareContext={changes:s,isTheFirstFile:!0},z.printMemory("Before loading entities for first dxf"),await l(),S.info("[Dxf] loadEntities for first dxf in "+(Date.now()-c)/1e3+"s"),z.printMemory("After loading entities for first dxf"),this.releaseCachedData(!1),this.releaseDxfData(e),z.printMemory("Before loading entities for second dxf"),c=Date.now(),this.compareContext.isTheFirstFile=!1,await l(),S.info("[Dxf] loadEntities for second dxf in "+(Date.now()-c)/1e3+"s"),this.printStatsInfo();for(const u of Object.values(s))!u.box&&delete s[u.id];this.compareContext.preservedHandles=void 0,this.enableReleaseData&&(this.releaseCachedData(),this.releaseDxfData(i)),z.printMemory("After loading entities for second dxf")}setObjectColorByChange(e,i){const s=a=>{let o=Ue.ENTITY_COLOR_NO_CHANGE;return a.type===Te.Added?o=Ue.ENTITY_COLOR_ADDED:a.type===Te.Removed?o=Ue.ENTITY_COLOR_REMOVED:a.type===Te.Modified&&(o=this.compareContext?.isTheFirstFile?Ue.ENTITY_COLOR_REMOVED:Ue.ENTITY_COLOR_ADDED),o},r=(a,o)=>{a.traverse(l=>{if(l.material){if(l.material instanceof d.LineBasicMaterial)l.material=this.getLineBasicMaterial(o);else if(l.material instanceof d.MeshBasicMaterial)l.material=this.getMeshBasicMaterial(o);else if(l.material instanceof d.PointsMaterial)l.material=this.getPointsMaterial(o);else if(l.material instanceof d.ShaderMaterial){const c=l.material.clone();V.updateMaterialUniforms(c),c.uniforms.u_color.value.set(o),l.material=c}}})},n=s(i);return e.traverse(a=>{i.parentHandles?a.userData&&a.userData.handle&&a.userData.handle===i.handle&&(r(a,n),e=a):r(a,n)}),e}releaseCachedData(e=!0){e&&(this.pointsMaterials={},this.lineBasicMaterials={},this.lineShaderMaterials={},this.meshBasicMaterials={},this.meshTextureMaterials={},this.hatchShaderMaterials=[]),this.header=void 0,this.blockReferencesCache={},this.blockRecordsCache=void 0,this.blocksCache=void 0,this.entitiesCache=void 0,this.dictionaryOwnerHandleAndSpatialFilterHandlesCache=void 0,this.spatialFiltersCache=void 0,this.entityThreejsCache=void 0,this.entityTypesAndTimes=void 0,this.entityHandlesWithRenderOrder={},this.layoutsSnapObjectsMap={},this.statsInfo={unsupportedEntity:{},unsupportedEntityTypes:{},unsupportedTextStyles:{},unsupportedHatchPatterns:{},unsupportedPolylineCount:0,invisibleEntities:{},ignoredFrozenLayersAndEntityCount:{},ignoredInserts:{},entityTypesAndMeshCount:{},ignoredPaperSpaceEntityTypesAndCount:{},rebasedEntityCount:0}}releaseEntity(e){e.vertices&&(e.vertices=void 0),e.knotValues&&(e.knotValues=void 0),e.controlPoints&&(e.controlPoints=void 0),e.binaryData&&(e.binaryData=void 0),e.text&&(e.text=void 0),e.extendedData&&(e.extendedData=void 0),e.contextData&&(e.contextData=void 0);const i=e;i.boundaryPaths&&(i.boundaryPaths=[]),i.patternLines&&(i.patternLines=void 0)}releaseDxfData(e){delete e.objects.DICTIONARY,delete e.objects.SORTENTSTABLE,delete e.objects.XRECORD,e.tables&&(delete e.tables.dimStyle,delete e.tables.lineType,delete e.tables.style,delete e.tables.blockRecord),e.entities=[],e.blocks={}}loadEntity(e,i,s,r=!1){if(this.compareContext&&this.compareContext.preservedHandles&&this.compareContext.preservedHandles.has(e.handle)&&oi.includes(e.type)&&(r=!0),!r&&this.compareContext&&this.compareContext.preservedHandles&&!oi.includes(e.type)&&!this.compareContext.preservedHandles.has(e.handle)&&(!s||s&&!this.compareContext.preservedHandles.has(s.handle)))return;if(this.getLayerFrozen(i,e)===!0){const m=e.layer;return!this.statsInfo.ignoredFrozenLayersAndEntityCount[m]&&(this.statsInfo.ignoredFrozenLayersAndEntityCount[m]=0),this.statsInfo.ignoredFrozenLayersAndEntityCount[m]++,void 0}if(e.visible===!1||e.invisible)return!this.statsInfo.invisibleEntities[e.type]&&(this.statsInfo.invisibleEntities[e.type]=0),this.statsInfo.invisibleEntities[e.type]++,void 0;if(this.ignorePaperSpace&&e.inPaperSpace)return!this.statsInfo.ignoredPaperSpaceEntityTypesAndCount[e.type]&&(this.statsInfo.ignoredPaperSpaceEntityTypesAndCount[e.type]=0),this.statsInfo.ignoredPaperSpaceEntityTypesAndCount[e.type]++,void 0;!this.entityThreejsCache&&(this.entityThreejsCache={});const a=Date.now();let o,l=!1;if(!this.compareContext&&this.entityThreejsCache[e.handle])o=this.entityThreejsCache[e.handle].clone(),l=!0;else if(!this.statsInfo.unsupportedEntity[e.handle]){const m=e.isTable;if(e.type==="CIRCLE"||e.type==="ARC")o=this.loadArc(e,i,s);else if(e.type==="LINE"||e.type==="POLYLINE")o=this.loadLine(e,i);else if(e.type==="XLINE")o=this.loadXLine(e);else if(e.type!=="SEQEND"){if(e.type==="RAY")o=this.loadRay(e);else if(e.type==="LWPOLYLINE")o=this.loadLWPolyline(e,i,s);else if(e.type==="3DFACE")o=this.load3DFace(e);else if(e.type==="TEXT")o=this.loadText(e,i,s);else if(e.type==="SOLID")o=this.loadSolid(e,i,s);else if(e.type==="POINT")o=this.loadPoint(e,i,s);else if(e.type==="IMAGE")o=this.loadImage(e,i,s);else if(e.type==="INSERT")o=this.loadInsert(e,i,s,r);else if(e.type==="SPLINE")o=this.loadSpline(e,s);else if(e.type==="MTEXT")m?o=this.loadTableMText(e,i,s):o=this.loadMText(e,i,s);else if(e.type==="ELLIPSE")o=this.loadEllipse(e,i,s);else if(e.type==="DIMENSION")o=this.loadDimension(e,i);else if(e.type!=="REGION")if(e.type==="ATTDEF")o=this.loadAttDef(e,i,s);else if(e.type==="ATTRIB"){if(!s)for(let g=0;g<i.entities.length;g++){const x=i.entities[g];if(e.ownerHandle===x.handle&&(s=x,s.attributesFollow))break}o=this.loadAttrib(e,i,s)}else e.type==="HATCH"?o=this.loadHatch(e,i,s):e.type==="VIEWPORT"?o=this.loadViewport(e,i,s):e.type==="LEADER"?o=this.loadLeader(e,i,s):e.type==="MULTILEADER"?o=this.loadMLeader(e,i,s):e.type==="OLE2FRAME"?o=this.loadOle2frame(e,i):e.type==="ACAD_TABLE"&&(o=this.loadTable(e,i))}o&&(this.entityThreejsCache[e.handle]=o),this.enableReleaseData&&!this.compareContext&&this.releaseEntity(e)}if(o){const m=this.getLayerName(e,i,s);o.userData.handle=e.handle,e.type!=="INSERT"&&e.type!=="DIMENSION"&&o.traverse(g=>{g.geometry&&(g.userData.layerName=m,g.userData.handle=e.handle,g.userData.dxfType=e.type,this.setMaterial(g,e,i,s))}),!l&&(this.nonSnapableTypes.has(e.type)&&o.traverse(g=>{g.layers.disable(Ce)}),this.enableRenderOrder&&(this.entityHandlesWithRenderOrder[e.handle]?o.renderOrder=parseInt(this.entityHandlesWithRenderOrder[e.handle],16)+.1:o.renderOrder=parseInt(e.handle,16)))}const c=e.type,u=e.handle,f=oi.includes(c);if(!f){this.entityTypesAndTimes||(this.entityTypesAndTimes={}),this.entityTypesAndTimes[c]||(this.entityTypesAndTimes[c]={createCount:0,totalTime:0,averageTime:0});const m=this.entityTypesAndTimes[c];m.createCount++,m.totalTime+=Date.now()-a}return o?this.statsInfo.entityTypesAndMeshCount[c]?this.statsInfo.entityTypesAndMeshCount[c]++:this.statsInfo.entityTypesAndMeshCount[c]=1:(this.statsInfo.unsupportedEntityTypes[c]?this.statsInfo.unsupportedEntityTypes[c]++:this.statsInfo.unsupportedEntityTypes[c]=1,f||(this.statsInfo.unsupportedEntity[u]?this.statsInfo.unsupportedEntity[u]++:this.statsInfo.unsupportedEntity[u]=1)),o}loadEllipse(e,i,s){if(!e.majorAxisEndPoint||!e.center||e.axisRatio===void 0||e.startAngle===void 0||e.endAngle===void 0)return;let r=e.startAngle,n=e.endAngle;if(e.extrusionDirection&&e.extrusionDirection.z<0&&(r=Math.PI*2-e.endAngle,n=Math.PI*2-e.startAngle),R.areNumbersEqual(r,n,1e-5))return S.warn("[Dxf] Ellipse entity (handle '%s') contains the same start and end angle, ignored!",e.handle),void 0;let a=n-r;for(;a>Math.PI*2;)a-=Math.PI*2;Math.abs(a)<=1e-5&&(n=R.floorNumber(r+Math.PI*2,5));const o=Math.sqrt(Math.pow(e.majorAxisEndPoint.x,2)+Math.pow(e.majorAxisEndPoint.y,2)),l=o*e.axisRatio,c=Math.atan2(e.majorAxisEndPoint.y,e.majorAxisEndPoint.x),u=new d.EllipseCurve(e.center.x,e.center.y,o,l,r,n,!1,c);let f=1;const m=s;m?.xScale&&m?.yScale&&(f=Math.max(Math.abs(m.xScale),Math.abs(m.yScale)));const g=this.getDivision(r,n,Math.max(o,l)*f),x=u.getPoints(g),y=[],T=x.length;for(let C=0;C<T-1;C++)R.areVector2sEqual(x[C],x[C+1],1e-9)||y.push(x[C]);if(y.push(x[T-1]),y.length<2)return S.warn("[Dxf] Ellipse entity (handle '%s') contains less than 2 points, ignored!",e.handle),void 0;const v=new d.Vector3;let b=!1;this.enableRTC&&(b=U.checkAndRebasePositionsOnRTC(y,v));const E=new d.BufferGeometry().setFromPoints(y),O=new F(H.Line);O.geometry=E,O.material=le;const _=new F(H.Point);return _.geometry=Sr,_.material=Ei,_.matrix.setPosition(e.center.x,e.center.y,e.center.z),_.userData.isSnapObject=!0,_.userData.type="CircleCenter",_.layers.set(Ce),O.add(_),b&&(this.setRTCUserData(O),O.matrix.setPosition(v.x,v.y,0)),O.layers.enableAll(),O}loadMText(e,i,s){if(!e.text)return;if(!this.font)return S.info("[Dxf] Font file not set, ignoring text entity."),void 0;const r=this.getTextStyle(i,e),n=li(e.text,{encoding:this.getTextEncoding(r)}),a=this.getMTextGroup(n,e,r,i,s),o=a&&a.object;if(!o)return;o.matrix.decompose(Z,he,ze),e.position&&(Z.x+=e.position.x,Z.y+=e.position.y,o.matrix.compose(Z,he,ze)),We.makeEmpty();const l=F.getBox(o,We),c=l.getSize(j),u=e.width||c.x,f=e.height||c.y,m=e.lineSpaceFactor||1.657,g=e.text;let x=0,y=0;switch(document.createElement("canvas").getContext("2d"),e.attachmentPoint){case 1:x=0,y=0;break;case 2:x-=u/2,y=0;break;case 3:x-=u,y=0;break;case 4:x=0,y+=f/2;break;case 5:x-=u/2,y+=f/2;break;case 6:x-=u,y+=f/2;break;case 7:x=0;const k=g.split("\\P").length-1;k>0?y+=f*(k+1)+f*m*.8*k:y+=f;break;case 8:x-=u/2,y+=f;break;case 9:x-=u,y+=f;break;default:return}switch(e.drawingDirection){case 1:break;case 2:break;case 3:y+=f;break;case 4:break;case 5:const I=g.split("\\P");let k=0;I>1&&(k=I-1),k>1?y+=f*(k-1):y-=f/4;break;default:return}o.traverse(I=>{I.geometry&&I.geometry.translate(x,y,0),I.layers.enableAll()});let v=0;if(e.rotation&&(v=e.rotation*Math.PI/180),e.directionVector){const I=e.directionVector,k=new d.Vector3(I.x,I.y,I.z),B=k.clone().cross(Ae),L=Ae.angleTo(k);v=B.z>0?-L:L}U.shouldRebasePositionOnRTC(Z)&&this.setRTCUserData(o),o.matrix.compose(Z,he,ze);const b=e.position?Z.clone().sub(e.position):Z;Fe.makeTranslation(-b.x,-b.y,0),ne.makeRotationZ(v),o.matrix.multiply(Fe),o.matrix.multiply(ne),o.matrix.multiply(Fe.invert()),o.userData||(o.userData={});const E=o.matrix.elements,O=E&&E[12]||0,_=E&&E[13]||0,C=E&&E[14]||0,w=new d.Box3;F.getBox(o,w);const M=new d.Vector3;w.getCenter(M);const P=new d.Vector3;w.getSize(P),o.userData.renderArea={position:{x:O,y:_,z:C},bbox:{min:{x:w.min.x,y:w.min.y,z:w.min.z},max:{x:w.max.x,y:w.max.y,z:w.max.z},center:{x:M.x,y:M.y,z:M.z},width:P.x,height:P.y,depth:P.z},textSize:{width:u,height:f},rotation:v,attachmentPoint:e.attachmentPoint||0,drawingDirection:e.drawingDirection||0};const A=this;return o.userData.textContent=e.text||"",o.userData.cleanText=A.cleanMTextContent?A.cleanMTextContent(e.text):e.text,o.userData.dxfType="MTEXT",o.userData.isMText=!0,o.userData.layer=e.layer||"0",o.userData.handle=e.handle||"",o.traverse(I=>{I.geometry&&(I.userData.textContent=e.text||"",I.userData.dxfType="MTEXT",I.userData.layer=e.layer||"0",I.userData.handle=e.handle||"")}),o.userData.entityId=e.entityId||e.handle,o}loadTableMText(e,i,s){if(!e.text)return;if(!this.font)return S.info("[Dxf] Font file not set, ignoring text entity."),void 0;const r=this.getTextStyle(i,e),n=li(e.text,{encoding:this.getTextEncoding(r)}),a=this.getMTextGroup(n,e,r,i,s),o=a&&a.object;if(!o)return;o.matrix.decompose(Z,he,ze),e.position&&(Z.x+=e.position.x,Z.y+=e.position.y,o.matrix.compose(Z,he,ze)),We.makeEmpty();const l=F.getBox(o,We),c=l.getSize(j),u=e.width||c.x,f=e.height||c.y,m=e.lineSpaceFactor||1.657,g=e.text;let x=0,y=0;switch(e.attachmentPoint){case 1:x=0,y=0;break;case 2:x-=u/2,y=0;break;case 3:x-=u,y=0;break;case 4:x=0,y+=f/2;break;case 5:x-=u/2,y+=f/2;break;case 6:x-=u,y+=f/2;break;case 7:x=0;const E=g.split("\\P").length-1;E>0?y+=f*(E+1)+f*m*.8*E:y+=f;break;case 8:x-=u/2,y+=f;break;case 9:x-=u,y+=f;break;default:return}switch(e.drawingDirection){case 1:break;case 2:break;case 3:y+=f;break;case 4:break;case 5:break;default:return}o.traverse(b=>{b.geometry&&b.geometry.translate(x,y,0),b.layers.enableAll()});let T=0;if(e.rotation&&(T=e.rotation*Math.PI/180),e.directionVector){const b=e.directionVector,E=new d.Vector3(b.x,b.y,b.z),O=E.clone().cross(Ae),_=Ae.angleTo(E);T=O.z>0?-_:_}U.shouldRebasePositionOnRTC(Z)&&this.setRTCUserData(o),o.matrix.compose(Z,he,ze);const v=e.position?Z.clone().sub(e.position):Z;return Fe.makeTranslation(-v.x,-v.y,0),ne.makeRotationZ(T),o.matrix.multiply(Fe),o.matrix.multiply(ne),o.matrix.multiply(Fe.invert()),o}getMTextGroup(e,i,s,r,n,a=0,o=0,l=[]){if(e.length===0)return;let c=i.height||i.contextData&&i.contextData.textHeight||0;if(i.textStyle){if(s&&s.fontFile&&s.fontFile.endsWith(".shx")){const O=s.fontFile+"_"+s.styleName;!this.statsInfo.unsupportedTextStyles[O]&&(this.statsInfo.unsupportedTextStyles[O]=0),this.statsInfo.unsupportedTextStyles[O]++}c=c||s.textHeight}let u="Left";i.width&&i.attachmentPoint&&([1,4,7].includes(i.attachmentPoint)?u="Left":[2,5,8].includes(i.attachmentPoint)?u="Center":[3,6,9].includes(i.attachmentPoint)&&(u="Right"));const f=i.width||0,m=new F;let g,x=s.fontFile,y=1,T=1,v=256,b=c*.8,E=b+c;for(let O=0;O<e.length;O++){const _=e[O];if(typeof _=="string"){const C=[],w=A=>{let I;if(A.forEach((k,B)=>{!k.boundingBox&&k.computeBoundingBox(),B===0?I=k.boundingBox:I.union(k.boundingBox)}),I){const k=I.getSize(j);switch(u){case"Left":break;case"Center":A.forEach(B=>B.translate((f-k.x)/2,0,0));break;case"Right":A.forEach(B=>B.translate(f-k.x,0,0));break}}C.push(...A)};let M;for(let A=0;A<_.length;A++){const I=_[A];if(I===`
|
|
794
794
|
`){a=0,o-=E,l.length>0&&w(l),l=[];continue}if(b=c*.8,E=b+c,M=this.font?.getCharShape(I,x,c),s.bigFontFile&&!M&&(M=this.font?.getCharShape(I,s.bigFontFile,c)),!M&&(M=this.font?.getCharShape(I,"",c)),!M&&(M=this.font?.getNotFoundTextShape(c)),!M){a+=c+T*(c/3.5);continue}a>(f||1/0)&&(l.length>0&&w(l),a=0,o-=E,l=[]),M.translate(a,o,0),M.scale(y,1,1),M.boundingBox||M.computeBoundingBox(),_.T&&(T=_.T);const k=Uo(I,M,c,T,x);a+=k,l.push(M)}l.length>0&&(w(l),l=[]);const P=new F;if(C.length>0){!g&&(g=i.colorIndex),v!==void 0&&v!==256?(i.color=Nt(v),i.colorIndex=v):i.colorIndex=g;const A=this.getColor(i,r,n),I=C.filter(B=>B instanceof d.ExtrudeGeometry),k=C.filter(B=>!(B instanceof d.ExtrudeGeometry));if(I.length>0){const B=new F(H.Mesh);B.geometry=xe.mergeGeometries(I),B.material=this.getMeshBasicMaterial(A),P.add(B)}if(k.length>0){const B=new F(H.LineSegment);B.geometry=xe.mergeGeometries(k),B.material=this.getLineBasicMaterial(A),P.add(B)}}P.matrix.makeTranslation(0,-c,0),m.add(P),y=1,T=1,v=256}else if(Array.isArray(_)){const C=this.getMTextGroup(_,i,s,r,n,a,o,l);C&&(m.add(C.object),a=C.hOffset,o=C.vOffset)}else typeof _=="object"&&(_.f&&(x=_.f,x&&x.includes(".shx")&&S.info("[Dxf] Doesn't support custom fonts: "+x)),_.C&&(v=_.C),_.W&&(_.W[1]==="x"?y=_.W[0]*i.width:y=_.W[0]),_.H&&(_.H[1]==="x"?c=_.H[0]*i.height:c=_.H[0]),_.T&&(T=_.T))}if(m.children.length!==0)return et.merge(m,!1),g&&(i.colorIndex=g),m.children.length===1?{object:m.children[0],hOffset:a,vOffset:o}:{object:m,hOffset:a,vOffset:o}}mtextContentAndFormattingToTextAndStyle(e,i){const s={horizontalAlignment:"",textHeight:i.height||i.contextData&&i.contextData.textHeight},r={};let n=1;const a=[];for(let o=0;o<e.length;o++){const l=e[o];if(typeof l=="string"){if(l.startsWith("\\pxq")&&l.endsWith(";"))l.indexOf("c")!==-1?s.horizontalAlignment="center":l.indexOf("l")!==-1?s.horizontalAlignment="left":l.indexOf("r")!==-1?s.horizontalAlignment="right":l.indexOf("j")!==-1&&(s.horizontalAlignment="justify");else if(!l.startsWith("pi")){if(!l.startsWith("pxt")){if(!l.startsWith("pt")){const c=this.getTextLineNum(l);a.push({font:r.f,colorIndex:r.C,text:l,lineNum:n}),n+=c}}}}else if(Array.isArray(l)){const c=this.mtextContentAndFormattingToTextAndStyle(l,i);c.text.forEach(u=>{a.push(u)}),n=c.lineLength}else if(typeof l=="object")if(l.S&&l.S.length===3){const c=l.S[0]+"/"+l.S[2],u=this.getTextLineNum(c);a.push({text:l.S[0]+"/"+l.S[2],lineNum:n}),n+=u}else l.C!==void 0?r.C=l.C:l.W!==void 0?r.W=l.W:l.H!==void 0?r.H=l.H:l.f!==void 0&&(r.f=l.f)}return{text:a,lineLength:n,style:s}}getTextLineNum(e){const i=e.match(new RegExp("\\n","g"));return i?i.length:0}load3DFace(e){if(!e.vertices||e.vertices.length===0)return S.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=e.vertices.map(o=>new d.Vector3(o.x,o.y,o.z));if(i.length===0)return;!R.areVector3sEqual(i[0],i[i.length-1])&&i.push(i[0]);const s=new d.Vector3;let r=!1;this.enableRTC&&(r=U.checkAndRebasePositionsOnRTC(i,s));const n=new d.BufferGeometry().setFromPoints(i),a=new F(H.Line);return a.geometry=n,a.material=le,r&&(this.setRTCUserData(a),a.matrix.setPosition(s.x,s.y,0)),a.layers.enableAll(),a}loadSpline(e,i){if(!e.controlPoints||!e.degreeOfSplineCurve||!e.knotValues)return;if(e.controlPoints.length<e.degreeOfSplineCurve+1)return S.warn("[Dxf] Spline entity (handle '%s') has degree (%s) >= point count (%s), ignored!",e.handle,e.degreeOfSplineCurve,e.controlPoints.length),void 0;let s=1/0,r=1/0,n=-1/0,a=-1/0;for(const v of e.controlPoints)v.x<s&&(s=v.x),v.y<r&&(r=v.y),v.x>n&&(n=v.x),v.y>a&&(a=v.y);let o=1;const l=i;l?.xScale&&l?.yScale&&(o=Math.max(Math.abs(l.xScale),Math.abs(l.yScale)));const c=Math.max(n-s,a-r),u=this.getBSplineInterpolationsPerSplineSegment(e.controlPoints.length,c*o),f=kr(e.controlPoints,e.degreeOfSplineCurve,e.knotValues,u),m=new d.Vector3;let g=!1;this.enableRTC&&(g=U.checkAndRebasePositionsOnRTC(f,m));const x=U.getAdjacentNonRepeatPoints(f);if(x.length<2)return S.warn("[Dxf] Spline entity (handle '%s') contains less than 2 points, ignored!",e.handle),void 0;const y=new d.BufferGeometry().setFromPoints(x),T=new F(H.Line);return T.geometry=y,T.material=le,g&&(this.setRTCUserData(T),T.matrix.setPosition(m.x,m.y,0)),T.layers.enableAll(),T}loadXLine(e){if(!e.vertices||e.vertices.length===0)return S.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=z.arrayOrObjectToVector3(e.directionVector),s=new d.Vector3(e.vertices[0].x,e.vertices[0].y,0),r=[];if(r.push(i.clone().multiplyScalar(-1e6).add(s)),r.push(i.clone().multiplyScalar(1e6).add(s)),r.length===0)return;const n=new d.Vector3;let a=!1;this.enableRTC&&(a=U.checkAndRebasePositionsOnRTC(r,n));const o=new d.BufferGeometry().setFromPoints(r),l=new F(H.Line);return l.geometry=o,l.material=le,a&&(this.setRTCUserData(l),l.matrix.setPosition(n.x,n.y,0)),l.layers.enableAll(),l}loadRay(e){if(!e.vertices||e.vertices.length===0)return S.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=z.arrayOrObjectToVector3(e.directionVector),s=e.vertices.map(l=>new d.Vector3(l.x,l.y,0));if(s.push(i.multiplyScalar(1e6).add(s[0])),s.length===0)return;const r=new d.Vector3;let n=!1;this.enableRTC&&(n=U.checkAndRebasePositionsOnRTC(s,r));const a=new d.BufferGeometry().setFromPoints(s),o=new F(H.Line);return o.geometry=a,o.material=le,n&&(this.setRTCUserData(o),o.matrix.setPosition(r.x,r.y,0)),o.layers.enableAll(),o}loadLine(e,i){if(!e.vertices||e.vertices.length===0){S.warn("[Dxf] Entity is missing vertices:",e.handle);return}let s=[];if(e.isPolyfaceMesh)s=ah(e.vertices);else{const c=us(e.vertices,e.shape);e.shape&&c.length>0&&c.push(c[0]),c.length>0&&(s=[c])}if(s.length===0)return;const r=[];for(let c=0;c<s.length;){const[u,f]=s[c];R.areVector3sEqual(u,f)&&s[c].length<=2?(r.push(u.clone()),s.splice(c,1)):c++}const n=new d.Vector3;let a=!1,o=0;s.forEach(c=>{c.forEach(u=>n.add(u)),o+=c.length}),o>0&&(n.divideScalar(o),a=this.enableRTC&&U.shouldRebasePositionOnRTC(n));let l=null;if(s.length>0){let c=function(v){return Array.isArray(v.pattern)&&v.pattern.length>0};const u=[],f=[];let m=0;s.forEach(v=>{v.forEach(b=>{a?u.push(new d.Vector3(b.x-n.x,b.y-n.y,b.z-n.z)):u.push(b.clone())});for(let b=1;b<v.length;b++)f.push(m+b-1,m+b);m+=v.length});const g=this.getLineType(e,i),x=i.tables?.lineType?.lineTypes?.[g],y=new d.BufferGeometry().setFromPoints(u);let T=le;if(x&&c(x)){let v=function(_){const C=_.attributes.position,w=C.count,M=new Float32Array(w);for(let P=0;P<w;P+=2){const A=P*3,I=(P+1)*3,k=C.array[I]-C.array[A],B=C.array[I+1]-C.array[A+1],L=C.array[I+2]-C.array[A+2],q=Math.sqrt(k*k+B*B+L*L);M[P]=P===0?0:M[P-1],M[P+1]=M[P]+q}_.setAttribute("lineDistance",new d.Float32BufferAttribute(M,1))};const b=x.pattern?.[0]||.5,E=x.pattern?.[1]||.5,O=.1;T=new d.LineDashedMaterial({color:le.color,linewidth:le.linewidth||1,dashSize:b*O,gapSize:E*O,scale:O}),v(y)}else y.setIndex(f);l=new F(H.LineSegment),l.geometry=y,l.material=T}if(r.length>0){a&&U.checkAndRebasePositionsOnRTC(r,n);const c=new d.BufferGeometry().setFromPoints(r),u=new F(H.Point);u.geometry=c,u.material=Ei,l?console.warn("Line has both segments and points – consider using a Group"):l=u}if(l)return a&&(this.setRTCUserData(l),l.matrix.setPosition(n.x,n.y,n.z)),l.layers.enableAll(),l}loadLWPolyline(e,i,s){if(!e.vertices||e.vertices.length<2){S.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}const r=[...e.vertices];if(e.extrusionDirectionX!==void 0&&e.extrusionDirectionY!==void 0&&e.extrusionDirectionZ!==void 0){j.set(e.extrusionDirectionX,e.extrusionDirectionY,e.extrusionDirectionZ);const g=V.getOcsMatrix(j).invert(),x=e.elevation!==void 0?e.elevation:0;r.forEach(y=>{j.set(y.x,y.y,x).applyMatrix4(g),y.x=j.x,y.y=j.y})}let n=us(r,e.shape);if(e.shape&&n.length>0&&!R.areVector3sEqual(n[0],n[n.length-1])&&n.push(n[0]),n.length<2){S.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}let a=new F;const o=e.extendedData;if(o?.outlines){const g=o.outlines,x=[];g.forEach(v=>{const b=new d.Shape;v.forEach((E,O)=>{O===0?b.moveTo(E[0],E[1]):b.lineTo(E[0],E[1])}),b.closePath(),x.push(new d.ShapeGeometry(b))});const y=xe.mergeGeometries(x),T=new F(H.Mesh);T.geometry=y,T.material=_t,T.layers.enableAll(),T.layers.disable(Ce),a.add(T)}let l=!1;const c=new d.Vector3;this.enableRTC&&(l=U.checkAndRebasePositionsOnRTC(n,c));const u=U.getAdjacentNonRepeatPoints(n);if(u.length<2){S.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}const f=e.constantWidth;if(this.enablePlineWidth){const g=r.some(x=>x.startWidth!==void 0||x.endWidth!==void 0);if(g||f!==void 0&&f>0){let x;const y=i.tables?.lineType?.lineTypes,T=this.getLineType(e,i,s),v=y?.[T];if(!v||!v.pattern||v.pattern.length===0)if(this.statsInfo.unsupportedPolylineCount++,g?x=this.createTaperedPolylineGeometry(r):x=U.convertWidthLineToMeshGeometry(u,f),!x)S.warn("[Dxf] Failed to convert line with width to mesh geometry: %s",e.handle);else{const b=new F(H.Mesh);b.geometry=x,b.material=_t,b.layers.enableAll(),b.layers.disable(Ce),a.add(b);const E=$.createOutline(x,le,b.matrix),O=new F(H.LineSegment);O.geometry=E.geometry,O.material=E.material,O.matrix=E.matrix,O.layers.enableAll(),O.layers.disable(Ce),a.add(O)}}}const m=new F(H.Line);return m.geometry=new d.BufferGeometry().setFromPoints(u),m.material=le,m.layers.enableAll(),a.children.length>0?a.add(m):a=m,l&&(this.setRTCUserData(a),a.matrix.setPosition(c)),a}createTaperedPolylineGeometry(e){if(!e||e.length<2)return null;const i=[],s=[],r=[],n=[];for(let l=0;l<e.length-1;l++){const c=e[l],u=e[l+1],f=u.x-c.x,m=u.y-c.y,g=Math.hypot(f,m);if(g===0)continue;const x=-m/g,y=f/g,T=l===0?c.startWidth:c.endWidth,v=u.startWidth,b=T/2,E=v/2;c.x+x*b,c.y+y*b,c.x-x*b,c.y-y*b;const O={x:u.x+x*E,y:u.y+y*E},_={x:u.x-x*E,y:u.y-y*E};r.push(O),n.push(_)}const a=r.length;for(let l=0;l<a;l++)i.push(r[l].x,r[l].y,0),i.push(n[l].x,n[l].y,0);for(let l=0;l<a-1;l++){const c=l*2;s.push(c,c+1,c+2),s.push(c+1,c+3,c+2)}const o=new d.BufferGeometry;return o.setAttribute("position",new d.Float32BufferAttribute(i,3)),o.setIndex(s),o}loadMLeader(e,i,s){const r=i.tables.dimStyle.dimStyles[e.dimensionStyle]||this.getDefaultDimensionStyle(i),n=e.contextData?.defaultTextContents;if(!n)return;const a=new F,o=li(n),l=this.getTextStyle(i,e),c=this.getMTextGroup(o,e,l,i,s),u=c&&c.object;if(u){u.matrix.decompose(Z,he,ze),e.contextData?.textLocation&&(Z.x+=e.contextData.textLocation.x,Z.y+=e.contextData.textLocation.y,u.matrix.compose(Z,he,ze)),We.makeEmpty();const f=F.getBox(u,We),m=f.getSize(j),g=m.x,x=m.y;let y=0,T=0;switch(e.contextData?.textAttachment){case 1:y=0,T=0;break;case 2:y-=g/2,T=0;break;case 3:y-=g,T=0;break;case 4:y=0,T+=x/2;break;case 5:y-=g/2,T+=x/2;break;case 6:y-=g,T+=x/2;break;case 7:y=0,T+=x;break;case 8:y-=g/2,T+=x;break;case 9:y-=g,T+=x;break;default:return}u.traverse(E=>{E.geometry&&E.geometry.translate(y,T,0)});let v=0;if(e.contextData?.textRotation&&(v=e.contextData.textRotation*Math.PI/180),e.contextData?.textDirection){const E=e.contextData.textDirection,O=new d.Vector3(E.x,E.y,E.z),_=O.clone().cross(Ae),C=Ae.angleTo(O);v+=_.z>0?-C:C}U.shouldRebasePositionOnRTC(Z)&&this.setRTCUserData(u),u.matrix.compose(Z,he,ze),e.contextData?.textLocation?j.set(e.contextData.textLocation.x,e.contextData.textLocation.y,0):j.set(0,0,0);const b=Z.clone().sub(j);Fe.makeTranslation(-b.x,-b.y,0),ne.makeRotationZ(v),u.matrix.multiply(Fe),u.matrix.multiply(ne),u.matrix.multiply(Fe.invert()),u.renderOrder=ge.Text,a.add(u)}if(e.leaderLineType!==0){const f=[],m=e.contextData?.leaders[0];if(!m)return a;const g=m.lastLeaderLinePoint;if(e.enableDogLeg){const E=new d.Vector3(g.x,g.y,g.z),O=m.doglegLength,_=new d.Vector3(m.doglegVector.x,m.doglegVector.y,m.doglegVector.z),C=_.multiplyScalar(O),w=E.clone().add(C);f.push(w,E)}const x=e.contextData?.leaders[0].leaderLines||[];for(let E=0;E<x.length;E++){const O=x[E].vertices[0],_=O.reverse().map(k=>new d.Vector3(k.x,k.y,k.z));let C=new d.Vector3(g.x,g.y,g.z);for(let k=0;k<_.length;k++)f.push(C,_[k]),C=_[k];const w=j.subVectors(f[0],f[1]).length(),M=e.arrowHeadSize||r.DIMASZ||2.5,P=e.arrowHeadScale||r.DIMSCALE||1,A=M*P;e.leaderLineType;let I="";if(e.arrowHeadId?I=e.arrowHeadId:r&&r.DIMLDRBLK&&(I=r.DIMLDRBLK),I){const k=this.getBlockByHandle(i.blocks,I);if(k&&k.entities)for(let B=0;B<k.entities.length;B++){const L=this.loadEntity(k.entities[B],i,e);if(L){const q=new d.Vector3(f[f.length-1].x,f[f.length-1].y,f[f.length-1].z),me=new d.Vector3(f[f.length-2].x,f[f.length-2].y,f[f.length-2].z),ue=Math.atan2(q.y-me.y,q.x-me.x);j.copy(q),Z.setScalar(A),he.setFromAxisAngle(Et,ue),L.matrix.compose(j,he,Z),a.add(L)}}}else this.loadDefaultLeadArrow(f[f.length-2],f[f.length-1],w/2e3,f)}const y=new d.Vector3;let T=!1;this.enableRTC&&(T=U.checkAndRebasePositionsOnRTC(f,y));const v=new d.BufferGeometry().setFromPoints(f),b=new F(H.LineSegment);b.geometry=v,b.material=le,b.renderOrder=ge.Line,T&&(this.setRTCUserData(b),b.matrix.setPosition(y.x,y.y,0)),a.add(b)}else return u?.traverse(f=>{f.layers.enableAll()}),u;return et.merge(a,!1),a.traverse(f=>{f.layers.enableAll()}),a.children.length===1?a.children[0]:a}loadLeader(e,i,s){const r=[];if(!e.vertices)return S.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;if(e.vertices.length<2)return S.warn("leader's vertices number must be greater than 2"),void 0;const n=i.tables.dimStyle.dimStyles[e.dimensionStyle]||this.getDefaultDimensionStyle(i);let a=e.vertices;if(e.pathType===1&&(a=new d.SplineCurve(e.vertices).getPoints(50)),e.textWidth){const T=e.textWidth,v=new d.Vector3(a[a.length-1].x,a[a.length-1].y,a[a.length-1].z);if(e.direction===0){const b=new d.Vector3(1,0,0).multiplyScalar(T);a.push(b.add(v))}else{const b=new d.Vector3(-1,0,0).multiplyScalar(T);a.push(b.add(v))}}for(let T=0;T<a.length-1;T++){const v=a[T],b=a[T+1];r.push(v,b)}const o=j.subVectors(r[0],r[1]).setZ(0).length(),l=e.arrowHeight||n.DIMASZ||2.5,c=e.arrowHeadScale||n.DIMSCALE||1,u=l*c,f=new F;if(e.arrowFlag===1){let T="";e.arrowHeadBlockHandle?T=e.arrowHeadBlockHandle:n&&n.DIMLDRBLK&&(T=n.DIMLDRBLK);const v=this.getBlockByHandle(i.blocks,T);if(v&&v.entities){n&&(e.colorIndex=n.DIMCLRD||256,e.color=Nt(e.colorIndex));for(let b=0;b<v.entities.length;b++){const E=this.loadEntity(v.entities[b],i,e);if(E){const O=new d.Vector3(r[0].x,r[0].y,r[0].z),_=new d.Vector3(r[1].x,r[1].y,r[1].z),C=Math.atan2(O.y-_.y,O.x-_.x);j.copy(O),Z.setScalar(u),he.setFromAxisAngle(Et,C),E.matrix.compose(j,he,Z),f.add(E)}}}else this.loadDefaultLeadArrow(r[1],r[0],u/o/2,r)}if(r.length===0)return;const m=new d.Vector3;let g=!1;this.enableRTC&&(g=U.checkAndRebasePositionsOnRTC(r,m));const x=new d.BufferGeometry().setFromPoints(r),y=new F(H.Line);return y.geometry=x,y.material=le,y.renderOrder=ge.Line,g&&(this.setRTCUserData(y),y.matrix.setPosition(m.x,m.y,0)),f.children.length>0?(f.add(y),et.merge(f,!1),f.traverse(T=>{T.layers.enableAll()}),f.children.length===1?f.children[0]:f):(y.layers.enableAll(),y)}getTableTextOffset(e,i,s){const r=new d.Vector3;switch(e){case 1:break;case 2:r.setX(i/2);break;case 3:r.setX(i);break;case 4:r.setY(-s/2);break;case 5:r.set(i/2,-s/2,0);break;case 6:r.set(i,-s/2,0);break;case 7:r.setY(-s);break;case 8:r.set(i/2,-s,0);break;case 9:r.set(i,-s,0);break}return r}loadTable(e,i,s){if(!e.startPoint){S.warn("[Dxf] Entity is missing startPoint:",e.handle);return}if(e.cells.length===0){S.warn("[Dxf] Entity is missing cells:",e.handle);return}if(e.rowHeightArr.length===0){S.warn("[Dxf] Entity is missing rowHeightArr:",e.handle);return}if(e.columnWidthArr.length===0){S.warn("[Dxf] Entity is missing columnWidthArr:",e.handle);return}const r=new F,{cells:n,rowCount:a,columnCount:o,rowHeightArr:l,columnWidthArr:c}=e,u=[];let f=0;for(let y=0;y<a;y++){u[y]=[];for(let T=0;T<o;T++)u[y][T]=f<n.length?n[f++]:null}for(let y=0;y<a;y++)for(let T=0;T<o;T++){const v=u[y][T];if(!v||v.mergedValue!==0)continue;let b=1,E=1;for(;y+b<a&&u[y+b][T]&&u[y+b][T].mergedValue===1;)b++;for(;T+E<o&&u[y][T+E]&&u[y][T+E].mergedValue===1;)E++;v.rowSpan=b,v.colSpan=E}const m=[0];for(let y=0;y<a;y++)m.push(m[y]-l[y]);const g=[0];for(let y=0;y<o;y++)g.push(g[y]+c[y]);const x=[];for(let y=0;y<=a;y++){let T=g[0],v=!1;for(let b=0;b<o;b++){y>0&&u[y-1][b],y<a&&u[y][b];let E=!0;if(y===0||y===a)E=!0;else{const O=this._getMergeOwner(u,y-1,b,a,o),_=this._getMergeOwner(u,y,b,a,o);E=O!==_}E?v||(v=!0,T=g[b]):v&&(x.push(new d.Vector3(T,m[y],0),new d.Vector3(g[b],m[y],0)),v=!1)}v&&x.push(new d.Vector3(T,m[y],0),new d.Vector3(g[o],m[y],0))}for(let y=0;y<=o;y++){let T=m[0],v=!1;for(let b=0;b<a;b++){y>0&&u[b][y-1],y<o&&u[b][y];let E=!0;if(y===0||y===o)E=!0;else{const O=this._getMergeOwner(u,b,y-1,a,o),_=this._getMergeOwner(u,b,y,a,o);E=O!==_}E?v||(v=!0,T=m[b]):v&&(x.push(new d.Vector3(g[y],T,0),new d.Vector3(g[y],m[b],0)),v=!1)}v&&x.push(new d.Vector3(g[y],T,0),new d.Vector3(g[y],m[a],0))}if(x.length>0){const y=new d.BufferGeometry().setFromPoints(x),T=new F(H.LineSegment);T.geometry=y,T.material=le,T.layers.enableAll(),r.add(T)}for(let y=0;y<a;y++)for(let T=0;T<o;T++){const v=u[y][T];if(!v||v.mergedValue!==0)continue;const b=g[T],E=m[y];let O=0;for(let M=0;M<(v.colSpan||1);M++)O+=c[T+M];let _=0;for(let M=0;M<(v.rowSpan||1);M++)_+=l[y+M];v.colorIndex=e.colorIndex,v.height=v.textHeight||2.5;const C=this.getTableTextOffset(v.attachmentPoint||1,O,_);j.set(b,E,0),j.add(C),v.position=j.clone();const w=this.loadMText(v,i,s);w&&r.add(w)}if(e.blockRecordHandle){const y=this.getBlockByHandle(i.blocks,e.blockRecordHandle);if(y&&y.entities)for(const T of y.entities){T.isTable=!0;const v=this.loadEntity(T,i,e);v&&r.add(v)}}return r.matrix.decompose(j,he,ze),j.x+=e.startPoint.x,j.y+=e.startPoint.y,r.matrix.compose(j,he,ze),r}_getMergeOwner(e,i,s,r,n){let a=i,o=s;for(;a>=0&&e[a][o]&&e[a][o].mergedValue===1;){if(a>0&&e[a-1][o]&&e[a-1][o].mergedValue!==1){a--;break}if(o>0&&e[a][o-1]&&e[a][o-1].mergedValue!==1){o--;break}if(a>0)a--;else if(o>0)o--;else break}return e[a]?.[o]||null}loadDefaultLeadArrow(e,i,s,r){const n=s*(e.x-i.x),a=s*(e.y-i.y),o=a,l=-n,c=new d.Vector3(i.x+n+o/6,i.y+a+l/6,0),u=new d.Vector3(i.x+n-o/6,i.y+a-l/6,0);r.push(i,c),r.push(i,u),r.push(c,u)}getBlockByHandle(e,i){if(!this.blocksCache){this.blocksCache={};for(const s in e){const r=e[s];!this.blocksCache[r.ownerHandle]&&(this.blocksCache[r.ownerHandle]=r)}}return this.blocksCache[i]}static updateMaterialUniforms(e){e instanceof d.ShaderMaterial&&(e.uniforms.u_cameraZoom&&(e.uniforms.u_cameraZoom=V.CameraZoomUniform),e.uniforms.u_viewportScale&&(e.uniforms.u_viewportScale=V.ViewportScaleUniform))}static transformAngleByOcsMatrix(e,i){const s=j.set(Math.cos(i)*1,Math.sin(i)*1,0),r=s.applyMatrix4(e);return Math.atan2(r.y,r.x)}static getArcAnglesByOcsMatrix(e,i,s){let r=R.getArcAngleSpanInRadian(i,s);const n=V.transformAngleByOcsMatrix(e,i),a=V.transformAngleByOcsMatrix(e,s);let o;if(R.areNumbersClose(r,Math.PI)){r=1;const l=V.transformAngleByOcsMatrix(e,i+r);o=R.getArcAngleSpanInRadian(n,l)}else{if(R.areNumbersClose(r,Math.PI*2))return[n,n+Math.PI*2];o=R.getArcAngleSpanInRadian(n,a)}return R.areNumbersClose(r,o,1e-5)?[n,a]:[a,n]}loadArc(e,i,s){if(!e.radius||e.radius<.001)return S.warn("[Dxf] The radius of arc (handle '"+e.handle+"') is undefined, ignored!"),void 0;if(!e.radius||e.radius<.001)return S.warn("[Dxf] The radius of arc (handle '"+e.handle+"') is too small, ignored!"),void 0;const r=new d.Vector3(0,0,1);e.extrusionDirectionX!==void 0&&e.extrusionDirectionY!==void 0&&e.extrusionDirectionZ!==void 0&&r.set(e.extrusionDirectionX,e.extrusionDirectionY,e.extrusionDirectionZ);const n=V.getOcsMatrix(r);let a,o;if(e.type==="CIRCLE")a=e.startAngle||0,o=a+2*Math.PI;else{if(e.startAngle==null||e.endAngle==null||(a=e.startAngle,o=e.endAngle,R.areNumbersEqual(a,o,1e-6)))return;if(!R.areNumbersClose(R.getArcAngleSpanInRadian(a,o),Math.PI*2)){const _=V.getArcAnglesByOcsMatrix(n,a,o);a=_[0],o=_[1]}}const l=new d.ArcCurve(0,0,e.radius,a,o,this.angBase!==0);let c=1;const u=s;u?.xScale&&u?.yScale&&(c=Math.max(Math.abs(u.xScale),Math.abs(u.yScale)));const f=this.getDivision(a,o,e.radius*c),m=l.getPoints(f),g=new d.Vector3;let x=!1;this.enableRTC&&(x=U.checkAndRebasePositionsOnRTC(m,g));const y=new d.BufferGeometry().setFromPoints(m),T=new F(H.Line);T.geometry=y,T.material=le;const v=new d.Vector3;e.center&&(v.x=e.center.x,v.y=e.center.y);const b=new d.Vector3(e.center?.x,e.center?.y,e.center?.z).applyMatrix4(n.invert());v.x=b.x,v.y=b.y;const E=v,O=new F(H.Point);return O.geometry=Sr,O.material=Ei,O.userData.handle=e.handle,O.userData.isSnapObject=!0,O.userData.type="CircleCenter",O.layers.set(Ce),T.add(O),x?(this.setRTCUserData(T),E.x+=g.x,E.y+=g.y):U.shouldRebasePositionOnRTC(E)&&this.setRTCUserData(T),T.matrix.setPosition(E),T.layers.enableAll(),T}addTriangleFacingCamera(e,i,s,r){const n=new d.Vector3,a=new d.Vector3;n.subVectors(s,i),a.subVectors(r,i),n.cross(a);const o=new d.Vector3(i.x,i.y,i.z),l=new d.Vector3(s.x,s.y,s.z),c=new d.Vector3(r.x,r.y,r.z);n.z<0?e.push(c,l,o):e.push(o,l,c)}loadSolid(e,i,s){const r=e.points;if(!r||r.length<4)return;if(e.extrusionDirection&&e.extrusionDirection.z){j.set(0,0,e.extrusionDirection.z);const f=V.getOcsMatrix(j).invert();r.forEach(m=>{const g=j.set(m.x,m.y,0).applyMatrix4(f);m.x=g.x,m.y=g.y})}const n=[],a=[];this.addTriangleFacingCamera(n,r[0],r[1],r[2]),a.push(0,1,2),this.addTriangleFacingCamera(n,r[1],r[2],r[3]),a.push(3,4,5);const o=new d.Vector3;let l=!1;this.enableRTC&&(l=U.checkAndRebasePositionsOnRTC(n,o));const c=new d.BufferGeometry().setFromPoints(n);c.setIndex(a);const u=new F(H.Mesh);return u.geometry=c,u.material=_t,l&&(this.setRTCUserData(u),u.matrix.setPosition(o.x,o.y,0)),u.layers.enableAll(),u}getTextStyle(e,i){const s=e.tables?.style?.styles;return s?s[i.textStyle]||s.STANDARD||s.Standard||{}:{}}getDefaultDimensionStyle(e){return e.tables.dimStyle.dimStyles.STANDARD||e.tables.dimStyle.dimStyles.Standard||{}}getTextEncoding(e){return e?.bigFontFile&&e.bigFontFile.toUpperCase().startsWith("GB")?"gbk":"utf8"}getTextMesh(e,i,s,r){if(!e)return;const n=s?.styleName||"";if(s&&s.fontFile&&s.fontFile.endsWith(".shx")){const c=s.fontFile+"_"+s.styleName;!this.statsInfo.unsupportedTextStyles[c]&&(this.statsInfo.unsupportedTextStyles[c]=0),this.statsInfo.unsupportedTextStyles[c]++}let a=.8;const o={_TCH_DIM:1.45,ROMANS:1};n&&o[n]&&(a=o[n]),r.xScale&&(a*=r.xScale),a>1&&n&&(a*=s?.xScale||1,i=i||s?.textHeight||0),i===0&&(n?i=1:i=.2);const l=this.createTextMeshByText(e,s,i,0,i/12,a);return l.traverse(c=>{c.geometry&&c.geometry.scale(a,1,1)}),l}createTextMeshByText(e,i,s=12,r=0,n=0,a=1,o=1/0,l=0){const c=new F,u=[];let f=0,m=0;i?.xScale;const g=r+s,x=i?.fontFile||"",y=typeof x=="string"&&x.toLowerCase().endsWith(".shx"),T=y?s*.06:s*.04,v=[];for(let O=0;O<e.length;O++){const _=e[O];_!==" "&&_!==`
|
|
795
795
|
`&&v.push(O)}const b=v.length;let E=0;for(let O=0;O<e.length;O++){const _=e[O];if(_===" "){f+=s*(y?.4:.33);continue}if(_===`
|
|
796
|
-
`){f=0,m-=g*.5;continue}let C=this.font?.getCharShape?.(_,i?.fontFile,s);if(!C&&i?.bigFontFile&&(C=this.font?.getCharShape?.(_,i.bigFontFile,s)),!C&&this.font?.fileNames){const w=this.font.fileNames.filter(M=>M!==i?.fontFile);for(let M=w.length-1;M>=0&&(i.fontFile=w[M],i.styleName="Standard",C=this.font?.getCharShape?.(_,i.fontFile,s),!C);M--);}if(C||(C=this.font?.getNotFoundTextShape?.(s)),!!C){if(C.translate(f,m,0),f>o)f=0,m-=g;else{!C.boundingBox&&C.computeBoundingBox();const w=C.boundingBox.getSize(j).x,M=_.charCodeAt(0),A=M>=19968&&M<=40959||M>=13312&&M<=19903||M>=63744&&M<=64255||M>=12288&&M<=12351||M>=65280&&M<=65519||[8216,8217,8220,8221].includes(M)?Math.max(w,s):w+T;E++,f+=A+(E===b?0:l)}u.push(C)}}if(u.length>0){const O=u.filter(C=>C instanceof d.ExtrudeGeometry),_=u.filter(C=>!(C instanceof d.ExtrudeGeometry));if(O.length>0){const C=new F(H.Mesh);C.geometry=xe.mergeGeometries(O),C.material=_t,c.add(C)}if(_.length>0){const C=new F(H.LineSegment);C.geometry=xe.mergeGeometries(_),C.material=le,c.add(C)}}return c}transformTextMesh(e,i){We.makeEmpty();const s=F.getBox(i,We),r=s.getSize(j),{halign:n,valign:a}=e;i.matrix.decompose(_i.position,_i.quaternion,_i.scale);const o=_i,l=e.width||e.textWidth||r.x,c=e.height||e.textHeight||r.y;if(n===void 0&&a===void 0&&e.startPoint||[3,5].includes(n)&&e.startPoint?(o.position.x+=e.startPoint.x,o.position.y+=e.startPoint.y,o.position.z+=e.startPoint.z):e.endPoint&&(o.position.x+=e.endPoint.x,o.position.y+=e.endPoint.y,o.position.z+=e.endPoint.z),n!==3&&n!==5){if(e.rotation){const u=e.rotation*Math.PI/180;o.rotateZ(u)}e.mirrored&2&&o.rotateY(Math.PI),e.mirrored&4&&o.rotateX(Math.PI)}switch(n){case 0:break;case 1:o.translateX(-l/2);break;case 2:o.translateX(-l);break;case 3:if(e.startPoint&&e.endPoint){const u=new d.Vector3(e.startPoint.x,e.startPoint.y,e.startPoint.z),f=new d.Vector3(e.endPoint.x,e.endPoint.y,e.endPoint.z),m=new d.Vector3().subVectors(u,f),g=m.length(),x=g/l;o.scale.multiplyScalar(x);const y=m.clone().cross(Ae),T=m.angleTo(Ae);o.rotateZ(y.z>0?Math.PI-T:T-Math.PI),(e.mirrored===2||e.mirrored===4)&&o.rotateX(Math.PI)}break;case 4:o.translateX(-l/2),o.translateY(-c/12);break;case 5:if(e.startPoint&&e.endPoint){const u=new d.Vector3(e.startPoint.x,e.startPoint.y,e.startPoint.z),f=new d.Vector3(e.endPoint.x,e.endPoint.y,e.endPoint.z),m=new d.Vector3().subVectors(u,f),g=m.length(),x=g/l,T=(e.text||"").length;if(T>1){const E=(g-l)/(T-1);o.userData.letterSpacing=E}else x<3&&o.scale.setX(x);const v=m.clone().cross(Ae),b=m.angleTo(Ae);o.rotateZ(v.z>0?Math.PI-b:b-Math.PI)}break}switch(a){case 0:break;case 1:break;case 2:o.translateY(-c/2);break;case 3:o.translateY(-c);break}return o.position.z=0,o.updateMatrix(),i.matrix.copy(o.matrix),i}loadText(e,i,s){const r=e.text;if(!r)return;if(!this.font){S.info("[Dxf] Font file not set, ignoring text entity.");return}const n=this.getTextStyle(i,e),o=Ni(r,{encoding:this.getTextEncoding(n)}).map(u=>u.text).join(""),l=this.getTextMesh(o,e.textHeight,n,e);if(!l||l.children.length===0)return;this.transformTextMesh(e,l),j.set(l.matrix.elements[12],l.matrix.elements[13],l.matrix.elements[14]);const c=U.shouldRebasePositionOnRTC(j);return c&&this.setRTCUserData(l),l.userData={...l.userData,textContent:r,dxfType:"TEXT",isMText:!1,layer:e.layer||"0",handle:e.handle,entityId:e.entityId||e.handle},l.traverse(u=>{const f=u.geometry;if(f){if(u.userData.textContent=r,u.userData.dxfType="TEXT",u.userData.layer=e.layer||"0",u.userData.handle=e.handle,u instanceof d.Mesh&&!f.getIndex()){const m=f.getAttribute("position"),g=[];for(let x=0;x<m.count;x+=3)g.push(x,x+1,x+2);f.setIndex(g)}if(f.hasAttribute("uv")&&f.deleteAttribute("uv"),f.hasAttribute("normal")&&f.deleteAttribute("normal"),!c){const m=U.caculateGeometryCenter(f);m&&U.shouldRebasePositionOnRTC(m)&&this.setRTCUserData(u)}}}),l.layers.enableAll(),l}loadAttDef(e,i,s){let r=e.tag||e.text||e.prompt;if(!r||!this.font)return;const n=this.getTextStyle(i,e);r=Ni(r).map(c=>c.text).join();const o=this.getTextMesh(r,e.textHeight,n,e);if(!o||o.children.length===0)return;this.transformTextMesh(e,o),j.set(o.matrix.elements[12],o.matrix.elements[13],o.matrix.elements[14]);const l=U.shouldRebasePositionOnRTC(j);return l&&this.setRTCUserData(o),o.traverse(c=>{const u=c.geometry;if(u){if(c instanceof d.Mesh&&!u.getIndex()){const f=u.getAttribute("position"),m=[];for(let g=0;g<f.count;g+=3)m.push(g,g+1,g+2);u.setIndex(m)}if(u.hasAttribute("uv")&&u.deleteAttribute("uv"),u.hasAttribute("normal")&&u.deleteAttribute("normal"),!l){const f=U.caculateGeometryCenter(u);f&&U.shouldRebasePositionOnRTC(f)&&this.setRTCUserData(c)}}}),o.layers.enableAll(),o}loadAttrib(e,i,s){let r=e.text;if(!r||!this.font)return;const n=this.getTextStyle(i,e);r=Ni(r).map(c=>c.text).join("");const o=this.getTextMesh(r,e.textHeight,n,e);if(!o||o.children.length===0)return;o.userData.llbData=s?.zdysx,o.userData.textContent=r||"",o.userData.dxfType="ATTRIB",o.userData.layer=e.layer||"0",o.userData.handle=e.handle||"",this.transformTextMesh(e,o),j.set(o.matrix.elements[12],o.matrix.elements[13],o.matrix.elements[14]);const l=U.shouldRebasePositionOnRTC(j);return l&&this.setRTCUserData(o),o.traverse(c=>{const u=c.geometry;if(u){if(c instanceof d.Mesh&&!u.getIndex()){const f=u.getAttribute("position"),m=[];for(let g=0;g<f.count;g+=3)m.push(g,g+1,g+2);u.setIndex(m)}if(u.hasAttribute("uv")&&u.deleteAttribute("uv"),u.hasAttribute("normal")&&u.deleteAttribute("normal"),c instanceof d.Mesh&&(c.entity=e,c.userData.entity=e),c.userData.textContent=r,c.userData.dxfType="ATTRIB",c.userData.layer=e.layer||"0",c.userData.handle=e.handle||"",!l){const f=U.caculateGeometryCenter(u);f&&U.shouldRebasePositionOnRTC(f)&&this.setRTCUserData(c)}}}),o.layers.enableAll(),o}loadPoint(e,i,s){if(!e.position)return;const r=new d.BufferGeometry,n=[new d.Vector3(e.position.x,e.position.y,e.position.z)];j.set(0,0,0);const a=j;let o=!1;this.enableRTC&&(o=U.checkAndRebasePositionsOnRTC(n,a)),r.setFromPoints(n);const l=new F(H.Point);return l.geometry=r,l.material=le,o&&(this.setRTCUserData(l),l.matrix.setPosition(a.x,a.y,0)),l.layers.enableAll(),l}loadDimension(e,i){if(!e.block)return;const s=i.blocks[e.block];if(!s||!s.entities)return;const r=i.tables.dimStyle.dimStyles[e.dimStyleName]||this.getDefaultDimensionStyle(i);r&&r.DIMCLRD>0&&(e.colorIndex=r.DIMCLRD,e.color=Nt(e.colorIndex));const n=new F;for(let o=0;o<s.entities.length;o++){const l=this.loadEntity(s.entities[o],i,e);l&&n.add(l)}if(n.children.length===0){const o=e.name||e.block;return!this.statsInfo.ignoredInserts[o]&&(this.statsInfo.ignoredInserts[o]=0),this.statsInfo.ignoredInserts[o]++,void 0}else{!this.blockReferencesCache[e.block]&&(this.blockReferencesCache[e.block]={referenceCount:0});const o=this.blockReferencesCache[e.block];o.referenceCount++}n.name=e.type+"<"+s.name+">",n.userData.entityType=e.type;const a=e.insertionPoint;return j.set(0,0,0),a&&j.set(a.x,a.y,0),U.shouldRebasePositionOnRTC(j)&&this.setRTCUserData(n),n.matrix.setPosition(j),n}loadImage(e,i,s){if(!e.imageSize||!i.objects.IMAGEDEF?.length)return;const r=i.objects.IMAGEDEF.filter(y=>y.handle===e.imageDefHandle)[0];if(!r)return;const n=e.imageSize.x,a=e.imageSize.y,o=new F;let l=!1;e.flags===Gi.ShowImageWhenNotAlignedWithScreen||e.flags===Gi.UseClippingBoundary||e.flags===Gi.TransparencyIsOn||(l=!0);const c=new d.PlaneGeometry(n,a);if(l){const y=new d.TextureLoader(this.manager).load(r.filename,void 0,void 0,()=>{console.warn("Please upload the pictures in the same folder, or use url link in the dxf file.")});y.colorSpace=d.SRGBColorSpace;const T=new d.MeshBasicMaterial({transparent:!0,side:d.FrontSide,map:y}),v=new F(H.Mesh);v.geometry=c,v.material=T,o.add(v)}const u=new d.EdgesGeometry(c),f=this.getColor(e,i,s),m=new F(H.Line);m.geometry=u,m.material=this.getLineBasicMaterial(f);const g=e.uPixel?new d.Vector3(e.uPixel.x,e.uPixel.y,e.uPixel.z):new d.Vector3(r.pixelSize.x,0,0),x=e.vPixel?new d.Vector3(e.vPixel.x,e.vPixel.y,e.vPixel.z):new d.Vector3(r.pixelSize.y,0,0);if(o.add(m),Z.set(g.x,x.y,1),j.set(0,0,0),e.position){const y=new d.Vector3(e.position.x,e.position.y,e.position.z);y.add(g.multiplyScalar(n/2)).add(x.multiplyScalar(a/2)),j.copy(y)}return U.shouldRebasePositionOnRTC(j)&&this.setRTCUserData(o),he.identity(),o.matrix.compose(j,he,Z),o}loadInsert(e,i,s,r=!1){if(!e||!e.block)return;const n=i.blocks[e.block];if(!n||!n.entities)return;s&&e.layer==="0"&&(e.layer=s.layer),e.blockPosition=n.position;const a=new F;for(let f=0;f<n.entities.length;f++){if(n.entities[f].type==="ATTDEF")continue;const m=this.loadEntity(n.entities[f],i,e,r);m&&(e&&e.zdysx&&V.LOADLLDATA&&(m.userData.llbData=e.zdysx),a.add(m))}if(a.children.length===0){const f=e.name||e.block;return!this.statsInfo.ignoredInserts[f]&&(this.statsInfo.ignoredInserts[f]=0),this.statsInfo.ignoredInserts[f]++,void 0}else{!this.blockReferencesCache[e.block]&&(this.blockReferencesCache[e.block]={referenceCount:0});const f=this.blockReferencesCache[e.block];f.referenceCount++}a.name=e.type+"<"+n.name+">",a.userData.entityType=e.type,e.extendedData?.originalType&&(a.userData.originalType=e.extendedData?.originalType),e?.blockPosition&&a.matrix.setPosition(-e.blockPosition.x,-e.blockPosition.y,0);const o=j.set(1,1,1);e.xScale&&(o.x=e.xScale),e.yScale&&(o.y=e.yScale);const l=new d.Euler;e.rotation&&(l.z=e.rotation*Math.PI/180),he.setFromEuler(l,!1);const c=Z.set(0,0,0);e.position&&(c.x=e.position.x,c.y=e.position.y),ne.compose(c,he,o),e.extrusionDirection&&e.extrusionDirection.z<0&&ne.premultiply(Or.identity().makeScale(-1,1,1)),Fe.copy(a.matrix),a.matrix.premultiply(ne),Z.set(a.matrix.elements[12],a.matrix.elements[13],a.matrix.elements[14]),U.shouldRebasePositionOnRTC(Z)&&this.setRTCUserData(a);const u=this.findSpatialFilterByHandle(e.handle,i);if(u){this.loadSpatialFilter(u);const f=u;f&&f.clipPolylines&&f.clipPolylines.length>0&&(a.userData.spatialFilterHandle=u.handle,this.cloneMaterialsForSpatialFilter(a),S.debug("[Dxf] Spatial filter:",e.associatedSpatialFilter))}return a}loadSpatialFilter(e){const i=e;if(i.threejsObject)return i.threejsObject.clone();const s=e.invertBlockMatrix;ne.set(s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11],0,0,0,1);const r=[];e.vertices.forEach(o=>{r.push(new d.Vector3(o.x,o.y,0))});const n={polyline:[],bConcave:!1,bReversed:!1};if(e.numberOfPointsOnClipBoundary===2)n.polyline=r;else{const o=e.numberOfPointsOnClipBoundary,l=3;if(o<l)return S.warn("[Dxf] Invalid clipBoundary: "+e.handle+" !"),void 0;let c=[],u=-1;for(let g=0;g<o;g++){const x=r[g];for(let y=o-1;y>g;y--){const T=r[y];if(R.areVector3sEqual(x,T)&&g+1<y-1&&g+1<o-1&&R.areVector3sEqual(r[g+1],r[y-1])){c.push(x),u=y;break}}if(u>0)break;c.push(x)}if(u>0)for(let g=u+1;g<o;g++)c.push(r[g]);if(c.length<l)return S.warn("[Dxf] Invalid clipBoundary: "+e.handle+"!"),void 0;const f=[],m=[];if(c.forEach(g=>{f.push(new d.Vector2(g.x,g.y)),m.push([g.x,g.y])}),!U.isConvex(f)){S.warn("[Dxf] Concave polygon is not supported for spatial filter (handle '"+e.handle+"'), converting to convex polygon!");const g=xa(m,1/0);c=[],g.forEach(x=>{c.push(new d.Vector3(x[0],x[1],0))})}!R.areVector3sEqual(c[0],c[c.length-1])&&c.push(c[0]),n.polyline=c,n.bReversed=u>0}let a;return this.enableReleaseData&&(e.vertices=[],e.matrix=[],e.invertBlockMatrix=[]),i.localMatrix=ne.clone(),i.clipPolylines=[],i.clipPolylines.push(n),a}loadLayout(e,i,s,r,n,a){if(!e.entities)return;const o=new F;for(let u=0;u<e.entities.length;u++){const f=e.entities[u];this.addViewport(f,a);const m=this.loadEntity(f,i);m&&(this.enableMerge&&et.merge(m,!1),o.add(m),m.traverse(g=>{if(g.geometry){const x=g.userData.layerName;let y=n[x];!y&&(y=[],n[x]=y),y.push(g),g.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[s.layoutName]&&(this.layoutsSnapObjectsMap[s.layoutName]=[]),this.layoutsSnapObjectsMap[s.layoutName].push(g))}}))}if(o.children.length===0)return;o.userData.layerName=e.layer;const l=s.layoutName;let c=r.children.find(u=>u.name===l);!c&&(c=new F,c.name=l,c.userData.isLayoutLevelObject=!0,r.add(c)),c.add(o),e.position&&o.matrix.setPosition(e.position.x,e.position.y,e.position.z||0)}convertEdgeToPoints(e){const i=[];if(!e)return i;switch(e.type){case Lt.Line:{const r=e;i.push(new d.Vector2(r.startPoint.x,r.startPoint.y)),i.push(new d.Vector2(r.endPoint.x,r.endPoint.y));break}case Lt.Arc:{const r=e;let n=r.startAngle*d.MathUtils.DEG2RAD,a=r.endAngle*d.MathUtils.DEG2RAD;!r.bCounterclockwise&&(n=Math.PI*2-n,a=Math.PI*2-a);const o=new d.ArcCurve(r.center.x,r.center.y,r.radius,n,a,!r.bCounterclockwise),l=this.getDivision(n,a,r.radius),c=o.getPoints(l);e.startPoint=c[0],e.endPoint=c[c.length-1],i.push(...c);break}case Lt.Ellipse:{const r=e,n=Math.sqrt(Math.pow(r.majorAxisEndPoint.x,2)+Math.pow(r.majorAxisEndPoint.y,2)),a=n*r.minorRatio,o=Math.atan2(r.majorAxisEndPoint.y,r.majorAxisEndPoint.x);let l=r.startAngle*d.MathUtils.DEG2RAD,c=r.endAngle*d.MathUtils.DEG2RAD;!r.bCounterclockwise&&(l=Math.PI*2-l,c=Math.PI*2-c);const u=new d.EllipseCurve(r.center.x,r.center.y,n,a,l,c,!r.bCounterclockwise,o),f=this.getDivision(l,c,Math.max(n,a)),m=u.getPoints(f);e.startPoint=m[0],e.endPoint=m[m.length-1],i.push(...m);break}case Lt.Spline:{const r=e,n=kr(r.controlPoints,r.degreeOfSplineCurve,r.knotValues);if(n.length===0)break;e.startPoint=n[0],e.endPoint=n[n.length-1],i.push(...n);break}case Lt.Polyline:{const r=e,n=us(r.points,r.isClosed);e.startPoint=n[0],e.endPoint=n[n.length-1],i.push(...n);break}}return i}loadHatch(e,i,s){const r=e;let n=[];function a(O,_){const{startPoint:C,endPoint:w}=O,{startPoint:M,endPoint:P}=_,A=w.x-C.x,I=w.y-C.y,k=P.x-M.x,B=P.y-M.y,L=A*B-I*k;if(Math.abs(L)<1e-10)return null;const q=C.x-M.x,me=C.y-M.y,ue=(k*me-B*q)/L,nt=(A*me-I*q)/L;return ue>=0&&ue<=1&&nt>=0&&nt<=1?{x:C.x+ue*A,y:C.y+ue*I}:null}function o(O){const{edges:_}=O,C=[],w=_.length;if({...O},w!==4)return[O];for(let M=0;M<w;M++)for(let P=M+2;P<w;P++){if(P===M+1||M===0&&P===w-1)continue;const A=a(_[M],_[P]);A&&C.push({edgeIndex1:M,edgeIndex2:P,point:{x:A.x,y:A.y}})}if(C.length&&C.length===1){const M={pathTypeFlag:O.pathTypeFlag,edges:[_[C[0].edgeIndex1-1],{startPoint:{..._[C[0].edgeIndex1].startPoint},endPoint:{x:C[0].point.x,y:C[0].point.y},type:_[C[0].edgeIndex1].type},{startPoint:{x:C[0].point.x,y:C[0].point.y},endPoint:{x:_[C[0].edgeIndex2].startPoint.x,y:_[C[0].edgeIndex2].startPoint.y},type:_[C[0].edgeIndex2].type}]},P={pathTypeFlag:O.pathTypeFlag,edges:[{startPoint:{x:C[0].point.x-1e-5,y:C[0].point.y-1e-5},endPoint:{..._[C[0].edgeIndex1].endPoint},type:_[C[0].edgeIndex1].type},{..._[C[0].edgeIndex2-1]},{startPoint:_[C[0].edgeIndex2].startPoint,endPoint:{x:C[0].point.x-1e-5,y:C[0].point.y-1e-5},type:_[C[0].edgeIndex2].type}]};return[M,P]}return[O]}if(r.boundaryPaths.length==0)return;for(let O=0;O<r.boundaryPaths.length;O++){const _=r.boundaryPaths[O],C=o(_);n=[...n,...C]}if(r.boundaryPaths=n,!r.solidFill&&!r.patternLines?.length){S.warn("[Dxf] Hatch entity(handle: '"+r.handle+"') doesn't have solid fill, nor patternLines, ignored!");return}const l=[],c=[],u=[],f=O=>{const _=[];let C=[];C.push(...this.convertEdgeToPoints(O[0]));for(let w=1;w<O.length;w++){const M=this.convertEdgeToPoints(O[w]);if(C.push(...M),C.length>2){const P=this.convertEdgeToPoints(O[w-1]);R.areVector2sEqual(P[P.length-1],M[0])?R.areVector2sEqual(C[0],M[M.length-1],1e-5)&&(_.push(C),C=[]):R.areVector2sEqual(P[0],M[M.length-1])?R.areVector2sEqual(C[1],M[0],1e-5)&&(_.push(C),C=[]):C=[]}}return _};if(r.boundaryPaths.forEach((O,_)=>{let C=[];if(this.IsfilteredByPathTypeFlag(O.pathTypeFlag)){S.info("[Dxf] The %d path type flag is filtered at the %dth boundrayPath (hatch handle '%s')",O.pathTypeFlag,_,r.handle);return}const w=O.edges;if(w.length===0)return;const M=[];for(let P=0;P<w.length;P++){const A=this.convertEdgeToPoints(w[P]);if(A.length<2){S.warn("[Dxf] The %dth edge of the %dth boundaryPath (hatch handle '%s') has less than 2 points, ignored!",P,_,r.handle);continue}M.push(...A)}if(M.length<3){S.warn("[Dxf] The %dth boundaryPath (hatch handle '%s') has less than 3 points, ignored!",_,r.handle);return}if(C.push(M),O.pathTypeFlag>Mn.MaxFlags&&(!(A=>{for(let I=1;I<A.length;++I){const k=A[I-1].endPoint,B=A[I].startPoint;if(!k||!B||!R.areVector2sEqual(k,B))return!1}return!0})(O.edges)||!r.associativity)&&(C=f(w),C.length<2)){S.warn("[Dxf] The %dth boundaryPath (hatch handle '%s') has unknown path, ignored!",_,r.handle);return}C.forEach(P=>{!R.areVector2sEqual(P[0],P[P.length-1])&&P.push(P[0]);const A=P.map(I=>new d.Vector2(z.roundNumber(I.x,7),z.roundNumber(I.y,7)));if(A?.length>0){l.push(A);const I=new d.Box2().setFromPoints(A);c.push(I);const k=I.getSize(Qt),B=k.x*k.y;u.push({area:B,index:l.length-1})}})}),l.length===0)return;const m=new d.Vector2,g=this.checkAndRebasePolygonsOnRTC(l,m);u.sort((O,_)=>O.area-_.area);const x=[];u.forEach(O=>{x.push(O.index)});const y=this.buildContainHierarchyTree(l,c,x),T=[];this.buildHatchGeometry(l,y,T);let v;if(T.length>0&&(v=xe.mergeGeometries(T)),!v||!v.getIndex()||v.getIndex()?.count===0)return S.warn("[Dxf] Failed to convert hatch boundaries!"),void 0;const b=new F(H.Mesh);b.geometry=v,b.material=_t,this.setHatchMaterial(b,r,i,m,s);const E=b;return g&&(this.setRTCUserData(E),E.matrix.setPosition(m.x,m.y,0)),E.traverse(O=>{O.layers.enableAll(),O.layers.disable(Ce)}),E}loadOle2frame(e,i){const{leftUpX:s,leftUpY:r,rightDownX:n,rightDownY:a}=e;if(!s||!r||!n||!a)return;const o=[new d.Vector2(s,r),new d.Vector2(s,a),new d.Vector2(n,a),new d.Vector2(n,r),new d.Vector2(s,r)],l=new d.Vector3;let c=!1;this.enableRTC&&(c=U.checkAndRebasePositionsOnRTC(o,l));const u=new d.BufferGeometry().setFromPoints(o),f=this.getLineBasicMaterial(16777215),m=new F(H.Line);m.geometry=u,m.material=f,m.layers.enableAll(),c&&(this.setRTCUserData(m),m.matrix.setPosition(l.x,l.y,0));const g=new F;g.add(m);let x;const y=i.objects.DICTIONARY;for(const v of y)for(const b in v.entries)if(v.entries[b]===e.handle){x=b;break}let T;if(x)if(this.meshTextureMaterials[x])T=this.meshTextureMaterials[x];else for(let v=0;v<i.objects.XRECORD.length;v++){const b=i.objects.XRECORD[v];if(b.handle===x){const E=b.binaryData,O=z.hexToBase64(E),_="data:image/jpg;base64,"+O,C=new d.TextureLoader(this.manager).load(_);C.colorSpace=d.SRGBColorSpace;const w=new d.MeshBasicMaterial({transparent:!0,map:C});this.meshTextureMaterials[x]=w,T=w;break}}if(T){const v=new d.Box2().setFromPoints(o),b=v.getSize(Qt),E=new d.PlaneGeometry(b.x,b.y),O=new F(H.Mesh);O.geometry=E,O.material=T;const _=v.getCenter(Qt);j.set(_.x,_.y,0),c&&(this.setRTCUserData(O),j.x+=l.x,j.y+=l.y),O.matrix.setPosition(j),O.layers.enableAll(),g.add(O)}return g.children.length>1?g:m}static getOcsMatrix(e){let i=Ae,s=ds,r=Et;const n=new d.Vector3(0,1,0),a=new d.Vector3(0,0,1);return R.areVectorsClose(e,a)?ne.identity():(r=e.clone().normalize(),!R.areVectorsClose(r,a)&&(Math.abs(r.x)<1/64&&Math.abs(r.y)<1/64?i=n.cross(r).normalize():i=a.cross(r).normalize(),s=r.clone().cross(i).normalize()),ne.set(i.x,i.y,i.z,0,s.x,s.y,s.z,0,r.x,r.y,r.z,0,0,0,0,1))}static getDcs2WcsMatrix(e,i){let s;ih(e)?s=e.viewDirectionFromTarget:s=e.viewDirection,s??(s={x:0,y:0,z:1});const r=e.viewTarget??{x:0,y:0,z:0},n=new d.Vector3(R.roundNumber(s.x,7),R.roundNumber(s.y,7),s.z),a=new d.Vector3(r.x,r.y,r.z),o=e.viewTwistAngle||0;let l,c,u;u=n.clone().normalize(),l=Et.clone().cross(n),l.length()>0?(l.normalize(),c=u.clone().cross(l)):u.z<0?(l=Ae.clone().negate(),c=ds,u=Et.clone().negate()):(l=Ae,c=ds,u=Et);const f=new d.Matrix4,m=ne.identity();return m.makeBasis(l,c,u),f.premultiply(m),f.premultiply(ne.identity().compose(a.clone(),new d.Quaternion().setFromAxisAngle(new d.Vector3(0,0,1),d.MathUtils.degToRad(i?o:-o)),new d.Vector3(1,1,1))),f}getViewportMsToPsMatrix(e){const i=e.centerPoint_dcs??{x:0,y:0},s=e.centerPoint??{x:0,y:0,z:0},r=new d.Vector3(i.x,i.y,0),n=new d.Vector3(s.x,s.y,s.z),a=e.viewHeight,o=e.height_paperSpace||1,l=(a||o)/o,c=V.getDcs2WcsMatrix(e,this.angDir),u=new d.Matrix4;u.setPosition(Cr.clone().sub(n));const f=Or.identity();f.scale(j.set(l,l,l));const m=Fe.identity().setPosition(Cr.clone().sub(n));f.premultiply(m.clone().invert()).multiply(m),u.multiply(f);const g=ne.identity();g.setPosition(r),c.multiply(g);const x=ne.identity();return u.invert().multiply(x).multiply(c.invert())}loadViewport(e,i,s){if(e.viewportId+""=="1"){e.psBBox=new d.Box3,e.msToPsMatrix=new d.Matrix4;return}const r=e.centerPoint;if(!r||!Number.isFinite(r.x)||!Number.isFinite(r.y)){e.psBBox=new d.Box3,e.msToPsMatrix=new d.Matrix4;return}const n=e.width_paperSpace/2,a=e.height_paperSpace/2,o=[new d.Vector3(r.x-n,r.y-a,0),new d.Vector3(r.x-n,r.y+a,0),new d.Vector3(r.x+n,r.y+a,0),new d.Vector3(r.x+n,r.y-a,0)];o.push(o[0]),e.psBBox=new d.Box3().setFromPoints([o[0],o[2]]),e.msToPsMatrix=this.getViewportMsToPsMatrix(e);let l=!1;const c=new d.Vector3;this.enableRTC&&(l=U.checkAndRebasePositionsOnRTC(o,c));const u=new d.BufferGeometry().setFromPoints(o),f=new F(H.Line);f.geometry=u,f.material=le,f.userData.entityType=e.type,f.layers.enableAll(),l&&(this.setRTCUserData(f),f.matrix.setPosition(c.x,c.y,0));const m=e.psBBox.clone();m.applyMatrix4(e.msToPsMatrix.clone().invert()),m.min.z=0,m.max.z=0;const g=[m.min,new d.Vector3(m.min.x,m.max.y,0),m.max,new d.Vector3(m.max.x,m.min.y,0)];g.push(g[0]);let x=!1;const y=new d.Vector3;this.enableRTC&&(x=U.checkAndRebasePositionsOnRTC(g,y));const T=new d.BufferGeometry().setFromPoints(g),v=new F(H.Line);v.geometry=T,v.material=le,v.userData.entityType=e.type,v.userData.inPaperSpace=[],v.layers.enableAll(),x&&(this.setRTCUserData(v),v.matrix.setPosition(y.x,y.y,0));const b=new F;return b.add(f),b.add(v),f}getColor(e,i,s){if(this.compareContext)return Ue.ENTITY_COLOR_NO_CHANGE;if(this.overrideColor!=null)return this.overrideColor;const r=e;if(r&&r.isGradientColor){const n=r.gradientColors;if(n&&n.length>=2){if(n[0]!==n[1]){const a="[Dxf] Gradient colors are not supported for hatch '"+e.handle+"', will use the first color!";S.warn(a)}return n[0]}}if(e.isTrueColor||e.colorIndex>0&&e.colorIndex<256)return e.color;if(e.colorIndex===0)return s?this.getColor(s,i):i.tables?.layer?.layers[0].color;if(e.colorIndex===256){const n=i.tables?.layer?.layers,a=n&&n[e.layer],o=n&&s&&n[s.layer];let l=ct;return a&&a.name!=="0"?l=a.color:o?l=o.color:a?l=a.color:n&&n[0].color&&(l=n[0].color),l}return S.warn("[Dxf] Unknown colorIndex"),ct}getLineType(e,i,s){if(s&&s.type==="DIMENSION")return this.getLineType(s,i);if(e.lineType!==Fs&&e.lineType!==mi)return e.lineType;if(e.lineType===mi)return s?this.getLineType(s,i):e.lineType;const r=i.tables?.layer?.layers,n=th;if(e.layer!=="0"){const a=r&&r[e.layer];if(a)return a.lineType}else if(s){const a=r&&r[s.layer];if(a)return a.lineType}return n}getLayerName(e,i,s){const r=c=>{n&&c&&!n[e.layer]&&(console.warn("[Dxf] Failed to find layer object for '"+c+"', adding a default one."),n[c]={name:c,handle:"",colorIndex:256,lineType:"",visible:!0})},n=i.tables?.layer?.layers;r(e.layer);const a=n&&n[e.layer];r(s?.layer);const o=n&&s&&n[s.layer];let l=a?.name||"";return a&&a.name==="0"&&o&&(l=o.name),l}setMaterial(e,i,s,r){const n=e;if(!n.geometry||(this.setRenderOrderByObjectType(e),i.type==="OLE2FRAME"))return;if(i.type==="MTEXT"){e.renderOrder=ge.Text;return}if(i.type==="HATCH"){Qt.set(0,0),this.setHatchMaterial(e,i,s,Qt,r);return}if(i.type==="IMAGE")return;let a;const o=this.getColor(i,s,r);if(i.type==="LWPOLYLINE"&&(n.isMesh?(a=this.getMeshBasicMaterial(o),e.renderOrder=ge.LineWithWidth):e.userData.isOutline&&(a=this.getLineBasicMaterial(o),e.renderOrder=ge.LineWithPattern),a)){n.material=a;return}if(i.type==="SOLID")a=this.getMeshBasicMaterial(o);else if(i.type==="TEXT"||i.type==="ATTDEF"||i.type==="ATTRIB")a=this.getLineBasicMaterial(o),e.renderOrder=ge.Text;else if(i.type==="LEADER"||i.type==="MULTILEADER"||i.type==="VIEWPORT")a=this.getLineBasicMaterial(o);else if(i.type==="POINT")a=this.getPointsMaterial(o);else{if(e.material instanceof d.PointsMaterial){a=this.getPointsMaterial(o),n.material=a;return}const l=s.tables?.lineType?.lineTypes,c=l&&l[this.getLineType(i,s,r)];if(c&&c.pattern&&c.pattern.length!==0){const u=i.lineTypeScale||1;a=this.getLineShaderMaterial(c,o,u),e.renderOrder=ge.LineWithPattern}else a=this.getLineBasicMaterial(o)}n.material=a}setHatchMaterial(e,i,s,r,n){const a=e;if(!a.geometry)return;const o=this.getColor(i,s,n);if(a.type===H.Line||a.type===H.LineSegment){a.material=this.getLineBasicMaterial(o);return}let l=ge.Mesh,c;if(i.solidFill)c=this.getMeshBasicMaterial(o);else{if(a.material instanceof d.ShaderMaterial){c=a.material;const u=new d.Color(o);!a.material.uniforms.u_color.value.equals(u)&&(c=a.material.clone(),V.updateMaterialUniforms(c),c.uniforms.u_color.value.set(o))}else c=this.getHatchShaderMaterial(i,o,r);l=ge.MeshWithPattern}!c&&(c=this.getMeshBasicMaterial(o),l=ge.Mesh),a.material=c,a.renderOrder=l}setRenderOrderByObjectType(e){const i=e;let s=0;i.isMesh?s=ge.Mesh:i.isLine?s=ge.Line:i.isPoints&&(s=ge.Point),e.renderOrder=s}getPointsMaterial(e){return!this.pointsMaterials[e]&&(this.pointsMaterials[e]=new d.PointsMaterial({size:.2,color:e})),this.pointsMaterials[e]}getLineBasicMaterial(e){return!this.lineBasicMaterials[e]&&(this.lineBasicMaterials[e]=new d.LineBasicMaterial({color:e})),this.lineBasicMaterials[e]}getLineShaderMaterial(e,i,s){const r=e.name+"_"+i+"_"+s;if(!this.lineShaderMaterials[r]){const n=this.getLineTypeScales(),a=n.ltScale*n.celtScale*s;this.lineShaderMaterials[r]=bn.createLineShaderMaterial(e.pattern,i,a,V.ViewportScaleUniform,V.CameraZoomUniform)}return this.lineShaderMaterials[r]}getMeshBasicMaterial(e){return!this.meshBasicMaterials[e]&&(this.meshBasicMaterials[e]=new d.MeshBasicMaterial({color:e})),this.meshBasicMaterials[e]}getHatchShaderMaterial(e,i,s){if(!e.patternLines||e.patternLines.length<1)return;const r=this.findMatchedHatchShaderMaterial(e,i);if(r)return r;const n=.005,a=.05;let o=2;e.patternLines.forEach(m=>{o=Math.max(m.dashPattern.length,o)});let l=0;const c=[],u=new d.Vector2;for(const m of e.patternLines){const g=new d.Vector2(m.origin.x,m.origin.y).sub(s).rotateAround(u,-d.MathUtils.degToRad(e.patternAngle)),x=new d.Vector2(m.delta.x,m.delta.y).rotateAround(u,-d.MathUtils.degToRad(m.angle));if(x.y===0)return S.warn("[Dxf] delta.y is equal to zero !"),void 0;const y=m.dashPattern.length;let T=!0,v=0;for(let w=0;w<y;++w){const M=m.dashPattern[w];M>0&&(T=!1),v+=Math.abs(M)}const b=T?a:n,E=[],O=[];let _=0;O[0]=_;for(let w=0;w<y;++w)E[w]=m.dashPattern[w],E[w]===0&&(E[w]=b*v),_+=Math.abs(E[w]),O[w+1]=_;for(let w=y;w<o;++w)E[w]=0;for(let w=O.length;w<o+1;++w)O[w]=_;const C={origin:g,delta:x,angle:m.angle-e.patternAngle,pattern:E,patternSum:O,patternLength:_};if(l+=4,l+=o,l+=o+1,l>V.MaxFragmentUniforms){S.warn("[Dxf] There will be warning in fragment shader when number of uniforms exceeds 1024, so extra hatch line patterns are ignored here!");break}c.push(C)}const f=vn(c,e.patternAngle,V.CameraZoomUniform,new d.Color(i),this.overrideHatchPatternLineThickness);return f.defines={MAX_PATTERN_SEGMENT_COUNT:o},this.hatchShaderMaterials.push({patternLines:e.patternLines,patternAngle:e.patternAngle,color:i,material:f}),f}getDivision(e,i,s){let r=Math.round(5e4/this.entityCount);r=Math.max(r,2),r=Math.min(r,10);const n=r*5;let o=r*2;if(this.averageCurveSize){const u=Math.pow(s/this.averageCurveSize,.5);o*=u,o=Math.max(o,r),o=Math.min(o,n)}let l=i-e;l<0&&(l+=Math.PI*2),o=Math.ceil(o*(l/Math.PI));let c=8;return l<.087?c=2:l<.174?c=3:l<.52?c=4:l<1.57?c=5:l<3.14?c=6:l<4.71&&(c=7),o=Math.max(o,c),this.averageCurveSize=(this.averageCurveSize*this.curveCount+s)/(this.curveCount+1),this.curveCount++,Math.max(o,12)}getBSplineInterpolationsPerSplineSegment(e,i){let s=1;this.averageCurveSize&&(s=Math.pow(i/this.averageCurveSize,.5),s=Math.max(s,.5),s=Math.min(s,2)),this.averageCurveSize=(this.averageCurveSize*this.curveCount+i)/(this.curveCount+1),this.curveCount++;let r=e*2*s;if(e>20){const n=Math.log10(e);r/=n}return r}async setDxfDataToIndexedDb(e,i){const s={dxfDataId:e,dxf:i};return new Promise((r,n)=>{Yi.instance().add(s,()=>{S.info("[Dxf] Saved '"+e+"' to indexedDb"),r()},a=>{n(a)})})}async getDxfDataFromIndexedDb(e){return new Promise((i,s)=>{Yi.instance().query(e,r=>{r&&r.length>0&&i(r[0].dxf),i(void 0)},()=>s())})}buildContainHierarchyTree(e,i,s){const r=new Map,n=s.length;for(let o=0;o<n;o++)r.set(s[o],{index:s[o],children:[]});const a={index:-1,children:[]};for(let o=0;o<n;o++){const l=s[o],c=e[l],u=i[l];let f=o+1;for(;f<n;f++){const m=s[f],g=e[m];if(i[m].containsBox(u)&&U.isPointInPolygon(c[z.generateRandomInt(0,c.length-1)],g)){r.get(m)?.children.push(r.get(l));break}}f===n&&a.children.push(r.get(l))}return a}buildHatchGeometry(e,i,s){if(i.children.length===0)return;const r=[],n=new Map;i.children.forEach(l=>{l.children.length===0?r.push(l.index):n.set(l.index,l.children.map(c=>c.index))});const a=l=>{try{const c=new d.ShapeGeometry(l);c.hasAttribute("uv")&&c.deleteAttribute("uv"),c.hasAttribute("normal")&&c.deleteAttribute("normal"),s.push(c)}catch{S.warn("[Dxf] triangulate shape error: "+l.getPoints().map(u=>u.toArray()).toString())}};r.forEach(l=>{const c=e[l];if(c.length===0)return;const u=new d.Shape(c);a(u)});const o=l=>l.map(c=>c.toArray());for(const l of n){const c=new d.Shape(e[l[0]]);let u={regions:[],inverted:!1};const f=this.findIntersectHole(e,l[1]);f.forEach(g=>{let x={regions:[],inverted:!1};try{g.forEach((y,T)=>{if(yt.epsilon(R.getVector2RelativeEps(e[y][0]),1e-6),T===0)x=yt.segments({regions:[o(e[y])],inverted:!1});else{const v=yt.segments({regions:[o(e[y])],inverted:!1}),b=yt.combine(x,v);u=yt.polygon(yt.selectUnion(b)),u.regions.length>0?u.regions.forEach(E=>{if(E.length===0)return;const O=E.map(_=>new d.Vector2(_[0],_[1]));c.holes.push(new d.Path(O))}):S.warn("[Dxf] mergedHoles.regions is empty")}})}catch(y){S.warn("[Dxf] polybooljs has error: "+y+", epsilon is "+yt.epsilon())}});const m=f.flat(2);for(let g=0;g<l[1].length;g++){const x=l[1][g];!m.includes(x)&&c.holes.push(new d.Path(e[x]))}a(c)}i.children.forEach(l=>{l.children.forEach(c=>{this.buildHatchGeometry(e,c,s)})})}findIntersectHole(e,i){const s=i.length,r=[];for(let n=0;n<s;n++){const a=e[i[n]];let o=!1;const l=[];for(let c=n+1;c<s;c++){const u=e[i[c]];U.arePolygonsIntersect(a,u)&&(o=!0,l.push(i[c]))}o&&(l.push(i[n]),r.push(l))}return r}checkAndRebasePolygonsOnRTC(e,i){if(!this.enableRTC||e.length===0)return!1;let s=0;e.forEach(n=>{n.forEach(a=>{i.add(a),s++})}),i.divideScalar(s);let r=!1;if(this.enableRTC&&U.shouldRebasePositionOnRTC(i)){r=!0;for(let n=0;n<e.length;n++){const a=e[n];for(let o=0;o<a.length;o++){const l=a[o].x-i.x,c=a[o].y-i.y;a[o]=new d.Vector2(l,c)}}}else i.set(0,0);return r}setRTCUserData(e){e.userData.relativeToCenter=!0,this.statsInfo.rebasedEntityCount++}IsfilteredByPathTypeFlag(e){return e<0}findSpatialFilterByHandle(e,i){const s=i.objects.DICTIONARY;if(!s)return;if(!this.dictionaryOwnerHandleAndSpatialFilterHandlesCache){this.dictionaryOwnerHandleAndSpatialFilterHandlesCache={};for(const n of s){const a=n;let o="";for(const l in a.entries)if(a.entries[l]==="ACAD_FILTER"){o=l;break}o&&(this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[n.ownerHandle]&&S.warn("[Dxf] Why this.dictionaryObjectsCache[obj.ownerHandle] already exist?",n.ownerHandle),this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[n.ownerHandle]=o)}}const r=this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[e];if(r){if(!this.spatialFiltersCache){this.spatialFiltersCache={};const n=i.objects.SPATIAL_FILTER||[];for(const a of n){const o=a;o.numberOfPointsOnClipBoundary<2||(this.spatialFiltersCache[o.ownerHandle]&&S.warn("[Dxf] Why this.spatialFiltersCache[spatialFilterObj.ownerHandle] already exist?",r),this.spatialFiltersCache[o.ownerHandle]=o)}}return this.spatialFiltersCache[r]}}initRenderOrderInfo(e){const i=new Set,s=e.objects.DICTIONARY;for(const n of s){const a=n;Object.keys(a.entries).forEach(o=>{a.entries[o]&&a.entries[o]==="ACAD_SORTENTS"&&i.add(o)})}if(i.size===0)return;const r=e.objects.SORTENTSTABLE;if(r)for(let n=0;n<r.length;++n){const a=r[n];if(i.has(a.handle)){for(let o=0;o<a.sortEntsObject.entityHandles.length;++o){const l=a.sortEntsObject.entityHandles[o];l.length===2&&!this.entityHandlesWithRenderOrder[l[0]]?this.entityHandlesWithRenderOrder[l[0]]=l[1]:S.warn("[Dxf] Failed to handle sortEntsTable: "+a.handle+".")}break}}}findMatchedHatchShaderMaterial(e,i){const s=e.patternLines;if(!s||s.length<1)return;const r=(c,u)=>Math.abs(c-u)<1e-5,n=(c,u)=>{if(c.length!==u.length)return!1;for(let f=0;f<c.length;++f)if(!r(c[f],u[f]))return!1;return!0},a=(c,u)=>r(c.angle,u.angle)&&r(c.delta.x,u.delta.x)&&r(c.delta.y,u.delta.y)&&r(c.origin.x,u.origin.x)&&r(c.origin.y,u.origin.y)&&n(c.dashPattern,u.dashPattern),o=(c,u)=>{if(c.length!==u.length)return!1;for(let f=0;f<c.length;++f)if(!a(c[f],u[f]))return!1;return!0};return this.hatchShaderMaterials.find(c=>c.color===i&&c.patternAngle===e.patternAngle&&o(c.patternLines,s))?.material}getLayout(e,i){if(!this.blockRecordsCache){this.blockRecordsCache={};const n=this.blockRecordsCache,a=e.tables?.blockRecord?.blockRecords;a&&Object.values(a).forEach(o=>{n[o.handle]=o.layoutHandle})}const s=this.blockRecordsCache[i.ownerHandle];if(s){const n=e.objects.LAYOUT,a=n.find(o=>o.handle===s);if(a)return a}if(!this.entitiesCache){this.entitiesCache={};const n=this.entitiesCache;Object.values(e.entities).forEach(a=>{n[a.handle]=a})}const r=this.entitiesCache[i.ownerHandle];return r?this.getLayout(e,r):e.objects.LAYOUT.find(n=>n.layoutName===V.MODEL_LAYOUT_NAME)}getLayerVisible(e,i){const s=e.tables?.layer?.layers;return s&&s[i]?.visible}getLayerFrozen(e,i){const s=e.tables?.layer?.layers;return s&&s[i.layer]?.frozen}cloneMaterialsForSpatialFilter(e){const i=new Map,s=r=>{let n;if(Array.isArray(r)){const a=[];n=a,r.forEach(o=>{if(i.has(o.id))a.push(i.get(o.id));else{const l=o.clone();V.updateMaterialUniforms(l),i.set(o.id,l),a.push(l)}})}else r&&(i.has(r.id)?n=i.get(r.id):(n=r.clone(),V.updateMaterialUniforms(n),i.set(r.id,n)));return n};e.traverse(r=>{r.material&&(r.material=s(r.material))})}getLineTypeScales(){const e={ltScale:1,celtScale:1};return this.header&&(e.ltScale=this.header.$LTSCALE||1,e.celtScale=this.header.$CELTSCALE||1),e}static getDxfUnits(e){switch(e||0){case 0:return De.Unitless;case 1:return De.Inches;case 2:return De.Feet;case 4:return De.Millimeters;case 5:return De.Centimeters;case 6:return De.Meters;default:S.warn("[Dxf] Unsupported $INSUNITS '"+e+"'");break}return De.Unitless}static computeLineDistance(e){const i=e.isLineSegments===!0;let s=e.geometry;const r=e.matrixWorld;if(s.index&&(S.debug("[Dxf] Line with id '"+e.id+"' contains index buffer, going to convert it to non-indexed."),s=U.convertGeometryWithIndexedToNonIndexed(s),e.userData.batches&&e.userData.batches.length>0)){S.debug("[Dxf] This line has been merged!");let n=0;e.userData.batches.forEach(a=>{a.positionStart=n,a.positionCount=a.indexCount,a.indexStart=0,a.indexCount=0,n+=a.positionCount})}if(s.index===null){const n=s.attributes.position;if(!n||n.count===0)return;const a=[];if(i)for(let o=0,l=n.count;o<l;o+=2)j.fromBufferAttribute(n,o).applyMatrix4(r),Z.fromBufferAttribute(n,o+1).applyMatrix4(r),a[o]=o===0?0:a[o-1],a[o+1]=a[o]+j.distanceTo(Z);else{a[0]=0;for(let o=1,l=n.count;o<l;o++)j.fromBufferAttribute(n,o-1).applyMatrix4(r),Z.fromBufferAttribute(n,o).applyMatrix4(r),a[o]=a[o-1],a[o]+=j.distanceTo(Z)}s.setAttribute("lineDistance",new d.Float32BufferAttribute(a,1)),e.geometry=s}else S.warn("[Dxf] computeLineDistances only possible with non-indexed BufferGeometry.")}static computeLineDistances(e){const i=Date.now();e.traverse(s=>{const r=s;r.isLine&&r.material instanceof d.ShaderMaterial&&V.computeLineDistance(r)}),S.debug("[Dxf] Computed line distances in "+(Date.now()-i)/1e3+"s")}static mergeDxfObjects(e){const i=Date.now(),s={},r={},n=15e3;let a=0,o=0;const l=()=>{const u=Date.now();for(const f in s){const m=s[f];V.removeEmptyObjectsFromRemovingMarkedObjects2(m.children,m.object),m.children=[]}a=0,o+=Date.now()-u};for(const u in e.layersAndObjects){const f=e.layersAndObjects[u];if(f.length<=1)continue;const m=Date.now(),g={},x=[];for(const y of f){if(y.userData.isSnapObject){x.push(y);continue}let T,v=y;for(;v;){if(v.userData.isLayoutLevelObject){T=v;break}v=v.parent}if(!T)continue;const b=T.name;!g[b]&&(g[b]={object:T,children:[]}),g[b].children.push(y)}for(const y in g){const T=g[y],v=et.deepMerge(T.children,T.object,!1,!1,!0),b=v.added,E=v.removed;!s[y]&&(s[y]={object:T.object,children:[]}),!r[y]&&(r[y]={object:T.object,children:[]});const O=E.length>n;if(O){const _=Date.now();V.removeEmptyObjectsFromRemovingMarkedObjects2(E,T.object),o+=Date.now()-_}else a+=E.length;if(E.length===T.children.length)!O&&E.forEach(_=>{s[y].children.push(_)});else{let _=E;E.length>=100&&(_=new Set(E));const C=w=>Array.isArray(_)?_.indexOf(w)>=0:_.has(w);for(let w=0;w<T.children.length;w++){const M=T.children[w];C(M)?!O&&s[y].children.push(M):x.push(M)}}for(let _=0;_<b.length;_++){const C=b[_];x.push(C),r[y].children.push(C)}a>n&&l()}e.layersAndObjects[u]=x,S.debug("[Dxf] Merged layer '"+u+"' in "+(Date.now()-m)/1e3+"s")}a>0&&l();for(const u in r){const f=r[u];!e.root.children.find(g=>g.name===u)&&e.root.add(f.object),f.children.forEach(g=>{f.object.add(g)}),f.children=[]}S.debug("[Dxf] MergeUtils.deepMerge took "+oe.MergeInfo.elapsedTime/1e3+"s"),S.debug("[Dxf] The remove operation of deep merge took "+o/1e3+"s"),S.debug("[Dxf] Deep merge totally took "+(Date.now()-i)/1e3+"s");const c=oe.MergeInfo;S.debug("[Dxf] Totally merged "+c.removedObjects+" objects to "+c.mergedMeshes+"meshes, "+c.mergedLines+"lines, "+c.mergedPoints+"points, "+(c.mergedUnknownTypeObjects?c.mergedUnknownTypeObjects+" unknown type,":" ")+" ")}static async merge(e,i){const s=z.getUpdateProgressFuncAsync(i),r={};e.objects.LAYOUT.forEach(y=>{const T=y;r[T.layoutName]=T,T.directAssociatedLeafObjectSet?.clear()});const n=Date.now(),a={},o={},l=15e3;let c=0,u=0;const f=()=>{const y=Date.now();for(const T in a){const v=a[T];V.removeEmptyObjectsFromRemovingMarkedObjects(v.children,v.object),v.children=[]}c=0,u+=Date.now()-y},m=Object.keys(e.layersAndThreejsObjects).length;let g=0;for(const y in e.layersAndThreejsObjects){const T=e.layersAndThreejsObjects[y];if(T.length<=1){await s(++g/m*100);continue}const v=Date.now(),b={},E=[];for(const C of T){if(C.userData.isSnapObject){E.push(C);continue}let w,M=C;for(;M;){if(M.userData.isLayoutLevelObject){w=M;break}M=M.parent}if(!w)continue;const P=w.name;!b[P]&&(b[P]={object:w,children:[]}),b[P].children.push(C)}const O=Object.keys(b).length;let _=0;for(const C in b){let w;if(C!==V.MODEL_LAYOUT_NAME){const B=r[C];!B.directAssociatedLeafObjectSet&&(B.directAssociatedLeafObjectSet=new Set),w=B.directAssociatedLeafObjectSet}const M=b[C],P=oe.deepMerge(M.children,M.object,!1,!1,!0),A=P.added,I=P.removed;!a[C]&&(a[C]={object:M.object,children:[]}),!o[C]&&(o[C]={object:M.object,children:[]});const k=I.length>l;if(k){const B=Date.now();V.removeEmptyObjectsFromRemovingMarkedObjects(I,M.object),u+=Date.now()-B}else c+=I.length;if(I.length===M.children.length)!k&&I.forEach(B=>{a[C].children.push(B)});else{let B=I;I.length>=100&&(B=new Set(I));const L=q=>Array.isArray(B)?B.indexOf(q)>=0:B.has(q);for(let q=0;q<M.children.length;q++){const me=M.children[q];L(me)?!k&&a[C].children.push(me):(E.push(me),w&&w.add(me))}}for(let B=0;B<A.length;B++){const L=A[B];$.setSharedVariablesOfObject(L),E.push(L),o[C].children.push(L),w&&w.add(L)}c>l&&f(),await s((g+ ++_/O)/m*100)}await s(++g/m*100),e.layersAndThreejsObjects[y]=E,S.debug("[Dxf] Merged layer '"+y+"' in "+(Date.now()-v)/1e3+"s")}c>0&&f();for(const y in o){const T=o[y],v=e.threejsObject.children.find(b=>b.name===y);if(v){const b=v.children.find(E=>E.name===V.SNAP_GROUP_NAME);if(b&&y!==V.MODEL_LAYOUT_NAME){const E=r[y];!E.directAssociatedLeafObjectSet&&(E.directAssociatedLeafObjectSet=new Set),b.children.forEach(O=>E.directAssociatedLeafObjectSet?.add(O))}}!v&&e.threejsObject.add(T.object),T.children.forEach(b=>{!b.visible&&(b.userData.layerVisible=!1),T.object.add(b),b.updateWorldMatrix(!1,!1)}),T.children=[]}S.debug("[Dxf] MergeUtils.deepMerge took "+oe.MergeInfo.elapsedTime/1e3+"s"),S.debug("[Dxf] The remove operation of deep merge took "+u/1e3+"s"),S.debug("[Dxf] Deep merge totally took "+(Date.now()-n)/1e3+"s");const x=oe.MergeInfo;S.debug("[Dxf] Totally merged "+x.removedObjects+" objects to "+x.mergedMeshes+"meshes, "+x.mergedLines+"lines, "+x.mergedPoints+"points, "+(x.mergedUnknownTypeObjects?x.mergedUnknownTypeObjects+" unknown type,":" ")+" "),s(100)}printStatsInfo(){const e=this.entityTypesAndTimes;for(const r in e)e[r].averageTime=e[r].totalTime/e[r].createCount;S.debug("[Dxf] Entity types and took how much time in ms:",e),S.debug("[Dxf] Entity types and mesh count:",this.statsInfo.entityTypesAndMeshCount);let i=0;if(Object.values(this.statsInfo.entityTypesAndMeshCount).forEach(r=>{i+=r}),this.enableRTC&&S.debug("[Dxf] Totally rebased "+this.statsInfo.rebasedEntityCount+"(out of "+i+") entities"),this.enableMerge){const r=oe.MergeInfo;S.debug("[Dxf] Inner merged "+r.removedObjects+" objects to "+r.mergedMeshes+"meshes, "+r.mergedLines+"lines, "+r.mergedPoints+"points, "+(r.mergedUnknownTypeObjects?r.mergedUnknownTypeObjects+" unknown type,":" ")+"in "+r.elapsedTime/1e3+"s")}const s=(r,n,...a)=>{Object.keys(n).length>0};s("[Dxf] Unsupported entity types and count:",this.statsInfo.unsupportedEntityTypes),s("[Dxf] Unsupported text style names and count:",this.statsInfo.unsupportedTextStyles,". Will use a default style."),s("[Dxf] Unsupported hatch pattern names and count:",this.statsInfo.unsupportedHatchPatterns,". Filling in solid lines instead."),this.statsInfo.unsupportedPolylineCount&&S.warn("[Dxf] Unsupported polyline (with both width and linetype) count: "+this.statsInfo.unsupportedPolylineCount+", linetype will be ignored."),s("[Dxf] Ignored invisible entity types and count:",this.statsInfo.invisibleEntities),s("[Dxf] Ignored frozen layers and entity count:",this.statsInfo.ignoredFrozenLayersAndEntityCount),s("[Dxf] Ignored inserts and count (may because they don't contain anything):",this.statsInfo.ignoredInserts),this.ignorePaperSpace&&s("[Dxf] Ignored paper space entity count:",this.statsInfo.ignoredPaperSpaceEntityTypesAndCount),this.font&&s("[Dxf] Unsupported chars and count:",this.font.getUnsupportedChar())}static statLayoutAndLayerObjects(e){const i=new WeakSet;let s=0;for(const a in e.layersAndThreejsObjects)e.layersAndThreejsObjects[a].forEach(l=>{l.geometry&&(s++,i.has(l)?console.warn(l):i.add(l))});const r=new WeakSet;let n=0;if(e.threejsObject.traverse(a=>{a.geometry&&(n++,r.has(a)?console.warn(a):r.add(a))}),s!=n)for(const a in e.layersAndThreejsObjects)e.layersAndThreejsObjects[a].forEach(l=>{l.geometry&&!r.has(l)&&console.warn(l)});S.info("[Dxf] The count of layer objects is "+s+",The count of layout objects is "+n+" ")}static removeEmptyObjectsFromRemovingMarkedObjects(e,i){if(e.length===0)return;const s=r=>{const n=[];for(const a of r){a.userData.validCount=0;const o=a.parent;o&&o!==i&&(o.userData.validCount===void 0&&(o.userData.validCount=o.children.length),--o.userData.validCount===0&&n.push(o))}n.length>0&&s(n)};s(e),this.removeEmptyObjectsFromMark(i)}static removeEmptyObjectsFromMark(e){if(e.userData.validCount===0||$.isEmptyObject(e))return e.removeFromParent(),!0;for(let i=0;i<e.children.length;)!this.removeEmptyObjectsFromMark(e.children[i])&&++i;return!1}static removeEmptyObjectsFromRemovingMarkedObjects2(e,i){if(e.length===0)return;const s=r=>{const n=[];for(const a of r){a.userData.validCount=0;const o=a.parent;o&&o!==i&&(o.userData.validCount===void 0&&(o.userData.validCount=o.children.length),--o.userData.validCount===0&&n.push(o))}n.length>0&&s(n)};s(e),this.removeEmptyObjectsFromMark2(i)}static removeEmptyObjectsFromMark2(e){if(e.userData.validCount===0||e.type===H.Object&&e.children.length===0)return e.removeFromParent(),!0;for(let i=0;i<e.children.length;)!this.removeEmptyObjectsFromMark2(e.children[i])&&++i;return!1}};p(V,"MODEL_LAYOUT_NAME","Model"),p(V,"SNAP_GROUP_NAME","InvisibleObjectGroupForOSnap"),p(V,"SHOW_SNAP_OBJECT",!1),p(V,"REQUWSTHEADER"),p(V,"CameraZoomUniform",{value:1}),p(V,"ViewportScaleUniform",{value:1}),p(V,"TransformMatrixUniform",{value:new d.Matrix4}),p(V,"ResolutionUniform",{value:new d.Vector2}),p(V,"LOADLLDATA",!1),p(V,"MaxFragmentUniforms",1024);let Y=V;class As extends mt{constructor(e){super();p(this,"viewer");p(this,"overlayRender");p(this,"drawableList");this.drawableList=new bi("compare"),this.viewer=e,this.overlayRender=this.viewer.getOverlayRender(),this.overlayRender?.addDrawableList(this.drawableList)}drawCompareDrawable(e){const i=[],s=[],r=[];for(const l of Object.values(e)){const c=l.box;c&&(l.type===Te.Added?i.push(c):l.type===Te.Removed?s.push(c):r.push(c))}const n=U.mergeBBoxes(i),a=U.mergeBBoxes(s),o=U.mergeBBoxes(r);this.drawableList.addDrawable(new Je(z.guid(),n,[.1,.9,.2,1])),this.drawableList.addDrawable(new Je(z.guid(),a,[1,.15,.15,1])),this.drawableList.addDrawable(new Je(z.guid(),o,[1,.85,.1,1])),this.viewer.enableRender()}setCompareDrawableVisible(e){this.drawableList.getDrawables().forEach(i=>i.visible=e),this.viewer.enableRender()}}class Ji{}const Pt=new d.Matrix4,fs=new d.Box3;class Wt extends Ji{constructor(e){super();p(this,"modelId");p(this,"modelData");p(this,"modelObject");p(this,"bbox");this.modelData=e,this.modelId=e.modelId,this.modelObject=e.dxfData?.threejsObject||e.pdfData?.threejsObject,this.modelObject.name=this.modelId,this.modelObject.userData.modelId=this.modelId}get pdfData(){return this.modelData.pdfData}get dxfData(){return this.modelData.dxfData}get msTransformMatrix(){return this.modelData.msTransformMatrix}set msTransformMatrix(e){this.modelData.msTransformMatrix=e}get loadedEntityCount(){return this.dxfData?.loadedEntityCount||this.pdfData?.loadedEntityCount||0}get header(){return this.dxfData?.header}get viewports(){return this.dxfData?.tables.viewport.viewports}get layers(){const e=this.dxfData||this.pdfData;return e.tables?.layer.layers||e.layers}get layoutViewportsMap(){return this.dxfData?.layoutViewportsMap}getModelObject(){const e=this.dxfData||this.pdfData;if(!e)throw new Error("Failed to find model by modelId '"+this.modelId+"'!");return e.threejsObject}getBBox(){if(!this.bbox){const e=new d.Box3,i=this.getModelObject();e.setFromObject(i),this.bbox=e}return this.bbox}getUnits(){if(!this.dxfData)return De.Unitless;const e=this.dxfData.header;if(!e)return S.warn("DxfData or its header is undefined!"),De.Unitless;const i=e.$INSUNITS;return Y.getDxfUnits(i)}getModelSpaceExtent(){const e=this.header,i=new d.Vector3,s=new d.Vector3;if(!e){S.error("Header is undefined in "+this.modelId+"!");return}const r=this.viewports;let n=e.$EXTMIN,a=e.$EXTMAX;const o=e.$ANGDIR;if(r&&r.length>0)for(let l=0;l<r.length;l++){const c=r[l];if(c.name.toLocaleUpperCase()==="*ACTIVE"){const{center:u,viewHeight:f,aspectRatio:m}=c,g=f*m,x=Y.getDcs2WcsMatrix(c,o),y=new d.Vector3(u.x,u.y,0);y.applyMatrix4(x),n={x:y.x-g/2,y:y.y-f/2,z:0},a={x:y.x+g/2,y:y.y+f/2,z:0};break}}return i.set(n.x,n.y,n.z),s.set(a.x,a.y,a.z),new d.Box3(i,s)}getLayer(e){if(this.layers)return this.layers[e]}getObjectsByLayer(e){const i=this.dxfData||this.pdfData;return i?.layersAndThreejsObjects&&i.layersAndThreejsObjects[e]}getLayouts(){const e=[];return this.dxfData?.objects.LAYOUT?.forEach(r=>{e.push(r)}),e}getLayoutByName(e){let i;const s=this.getLayouts();for(const r of s)if(r.layoutName===e){i=r;break}return i}getLayoutExtent(e){const i=this.header,s=new d.Vector3,r=new d.Vector3;if(!i)throw new Error("Header is undefined in "+this.modelId+"!");const n=this.getLayoutViewports(e);let a=i.$PEXTMIN,o=i.$PEXTMAX;const l=i.$ANGDIR;if(n&&n.length>0){const c=n.filter(T=>parseInt(T.viewportId)===1);let u;c.length>0?u=c[0]:u=n[0];const{centerPoint:f,width_paperSpace:m,height_paperSpace:g}=u,x=Y.getDcs2WcsMatrix(u,l),y=new d.Vector3(f.x,f.y,0);y.applyMatrix4(x),a={x:y.x-m/2,y:y.y-g/2,z:0},o={x:y.x+m/2,y:y.y+g/2,z:0}}return s.set(a.x,a.y,a.z),r.set(o.x,o.y,o.z),new d.Box3(s,r)}getLayoutViewports(e){const s=this.layoutViewportsMap[e.ownerHandle];return s||[]}getLayoutLevelObject(e){return this.getModelObject()?.children.find(s=>s.name===e)}setVisible(e){const i=this.getModelObject();i.visible=e}setLayerVisible(e,i,s,r){const n=this.getLayer(e);n?n.visible=i:S.warn("[Viewer] Layer '"+e+"' not found from modelData!");const a=this.getObjectsByLayer(e);if(a)for(let o=0;o<a.length;o++){const l=a[o];!(s&&i&&r&&l.userData.visibleMinZoom&&r<l.userData.visibleMinZoom)&&(l.visible=i),(i===!1||l.userData.layerVisible!=null)&&(l.userData.layerVisible=i),l.userData.isSnapObject&&(l.visible?Y.SHOW_SNAP_OBJECT?l.layers.enableAll():l.layers.set(Ce):Y.SHOW_SNAP_OBJECT?l.layers.disableAll():l.layers.disable(Ce))}else S.info("[Viewer] No object found for layer '"+e+"'")}setLayerOpacity(e,i){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const r=this.getObjectsByLayer(e);r?r.forEach(n=>{const a=n;if(a.material){!a.userData.originalMaterial&&(a.userData.originalMaterial=de.cloneMaterial(a.material));const o=de.cloneMaterial(a.material);de.setMaterialOpacity(o,i),Y.updateMaterialUniforms(o),a.material=o}}):S.info("[Viewer] No object found for layer '"+e+"'")}setLayerColor(e,i){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const r=this.getObjectsByLayer(e);r?r.forEach(n=>{const a=n;if(a.material){!a.userData.originalMaterial&&(a.userData.originalMaterial=de.cloneMaterial(a.material));const o=de.cloneMaterial(a.material);de.setMaterialColor(o,new d.Color(i)),Y.updateMaterialUniforms(o),a.material=o}}):S.info("[Viewer] No object found for layer '"+e+"'")}resetLayerColor(e){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const s=this.getObjectsByLayer(e);s?s.forEach(r=>{const n=r;n.material&&n.userData.originalMaterial&&(n.material.dispose(),n.material=n.userData.originalMaterial,delete n.userData.originalMaterial)}):S.info("[Viewer] No object found for layer '"+e+"'")}switchTransformMs(e){const i=this.msTransformMatrix;if(Pt.identity(),!i||!z.isMatrixValid(i)||i.equals(Pt))return;const s=this.getLayoutLevelObject(Y.MODEL_LAYOUT_NAME);s&&(e===Y.MODEL_LAYOUT_NAME?s.applyMatrix4(i):s.applyMatrix4(i.clone().invert()),s.updateMatrixWorld(!0))}activateLayout(e=Y.MODEL_LAYOUT_NAME,i){this.switchTransformMs(e);const s=this.getLayoutByName(e);if(s){if(!i){const r=this.getLayoutViewports(s);let n=[];r.length>0&&(n=r[0].frozenLayerHandles);const a=e!==Y.MODEL_LAYOUT_NAME,o=this.getLayoutLevelObject(e);if(o){const u=[];o.traverse(f=>{this.addSpatialFilterSection(f,this.dxfData);const m=f;if(a&&m.material&&m.geometry){const g=m.userData.layerName;if(this.isLayerFrozenForViewport(g,n))return;u.push(m);let x=-1;const y=this.getObjectsByLayer(g);y&&(x=y.indexOf(m),x>=0&&y.splice(x,1)),x<0&&S.warn("[Viewer] Failed to find object for modelId '"+this.modelId+"', layer '"+g+"', layout '"+e+"'")}}),u.forEach(f=>{f.removeFromParent()})}const l=this.getFilteredViewports(s);S.debug("[Viewer] Active layout:",e,", viewports:",l);const c=Date.now();l.forEach(u=>{this.generateObjectsByViewport(e,u,this)}),S.info("[Viewer] generateObjectsByViewport in "+(Date.now()-c)/1e3+"s")}this.showLayoutObjects(e)}}getFilteredViewports(e){const i=this.getLayoutViewports(e);let s=i.filter(r=>r.viewportId!=="1");return s.length===i.length&&(s=i.filter((r,n)=>n!==0)),s}generateObjectsByViewport(e,i,s,r=[]){const n=i;if(i.viewportId=="1")return;if(!n.psBBox||!n.msToPsMatrix)throw new Error("The bbox or matrix is invalid in the viewport!");Y.TransformMatrixUniform={value:n.msToPsMatrix},Y.ViewportScaleUniform={value:i.viewHeight/i.height_paperSpace};const a=n.psBBox.clone();a.applyMatrix4(n.msToPsMatrix.clone().invert()),a.min.setZ(-1),a.max.setZ(1);const o=this.getObjectsByBoundingBox(a);if(o.length===0)return;const l=n.psBBox.min,c=n.psBBox.max,u=new d.Box2(new d.Vector2(l.x,l.y),new d.Vector2(c.x,c.y)),f=dt.generateSectionPlanesByBox(u),m=[],g=M=>(!m[M.id]&&(m[M.id]=M.clone(),this.setMaterialUniforms(m[M.id],s.dxfData),dt.setMaterialSection(m[M.id],f)),m[M.id]),x=M=>{if(Array.isArray(M)){const P=[];return M.forEach(A=>{const I=g(A);P.push(I)}),P}else return g(M)},y=[...r,...i.frozenLayerHandles||[]];let T;if(e!==Y.MODEL_LAYOUT_NAME){const M=n;!M.associatedLeafObjectSet&&(M.associatedLeafObjectSet=new Set),T=M.associatedLeafObjectSet}const v=new d.Group;v.name=n.viewportId;const b=[];if(o.forEach(M=>{const P=M.clone();P.traverse(A=>{const I=A;if(I.material&&I.geometry){const k=I.userData.layerName;if(this.isLayerFrozenForViewport(k,y)){b.push(I);return}I.userData.layerVisible!==!1&&(I.visible=!0),I.material=x(I.material),T?.add(I);const B=s.getObjectsByLayer(k);B?B.push(I):S.warn("[Viewer] Failed to find object for modelId '"+this.modelId+"', layer '"+k+"', layout '"+e+"'")}}),v.add(P)}),T&&T.size===0)return;const E=s.getModelObject();let O=s.getLayoutLevelObject(e);!O&&(O=new d.Group,$.setSharedVariablesOfObject(O),O.name=e,E?.add(O)),O.add(v),v.applyMatrix4(n.msToPsMatrix),v.updateMatrixWorld(!0);let _=O.children.find(M=>M.name===Y.SNAP_GROUP_NAME);!_&&(_=new d.Group,_.visible=Y.SHOW_SNAP_OBJECT,_.name=Y.SNAP_GROUP_NAME,O.add(_));const C=s.getLayoutLevelObject(Y.MODEL_LAYOUT_NAME),w=C?.children.find(M=>M.name===Y.SNAP_GROUP_NAME);w&&w.traverse(M=>{if(!M.geometry)return;const P=M.userData.layerName;if(this.isLayerFrozenForViewport(P,y)||(fs.makeEmpty(),fs.expandByObject(M),!a.intersectsBox(fs)))return;const A=M.clone();$.setSharedVariablesOfObject(A);let I=A.parent;const k=Pt.identity();for(;I&&I.userData.isLayoutLevelObject!==!0;)k.premultiply(I.matrix),I=I.parent;k.premultiply(n.msToPsMatrix),A.applyMatrix4(k),_?.add(A),T?.add(A);const B=s.getObjectsByLayer(P);B&&B.push(A)}),b.length>0&&$.removeEmptyObjectsFromRemovingObjects(b,v),v.traverse(M=>{$.setSharedVariablesOfObject(M),this.addSpatialFilterSection(M,s.dxfData,!0)})}setMaterialUniforms(e,i){e instanceof d.ShaderMaterial&&(e.uniforms.u_cameraZoom&&(e.uniforms.u_cameraZoom=Y.CameraZoomUniform),e.uniforms.u_viewportScale&&i?.header.$PSLTSCALE===1&&(e.uniforms.u_viewportScale=Y.ViewportScaleUniform))}getObjectsByBoundingBox(e){const i=[];if(e.isEmpty())return S.warn("[Viewer] bbox is empty !"),i;const s=n=>{const a=rt.getBoundingBox(n,!1);e.intersectsBox(a)&&i.push(n)},r=this.getLayoutLevelObject(Y.MODEL_LAYOUT_NAME);return r&&r.children.forEach(n=>{n.name!==Y.SNAP_GROUP_NAME&&s(n)}),i}showLayoutObjects(e){let i=0,s=0;const r=this.getModelObject();r.children.forEach(n=>{const a=n.name===e;n.visible=a,a?i++:s++}),S.debug("[Viewer] showLayoutObjects('"+e+"') sets "+i+" layout level object(s) to visible and "+s+" to hidden for model '"+r?.name+"'")}isLayerFrozenForViewport(e,i){const s=this.getLayer(e);return s&&(s.flag&1)>0?!0:!i||i.length<=0?!1:s&&i.indexOf(s.handle)>=0}addSpatialFilterSection(e,i,s=!1){if(e.userData.entityType!=="INSERT"||!e.userData.spatialFilterHandle)return;const r=this.findSpatialFilter(e.userData.spatialFilterHandle,i);if(r){let n=s,a=!1;const o=this.getAnyMaterial(e);if(o&&(o.clippingPlanes&&(n=o.clippingPlanes.length>0),a=o.clipIntersection),n&&a!==r.clipPolylines[0].bReversed){S.warn("[Viewer] Material cannot set clipIntersection to different values at the same time. clipIntersection needs to be set to true here!");return}a=r.clipPolylines[0].bReversed;const l=this.generateSectionsBySpatialFilter(r,e.matrixWorld);if(l){const c=m=>{let g=0;return m.clippingPlanes&&(g=m.clippingPlanes.length),g+l.length>Y.MaxFragmentUniforms},u=new Set,f=m=>{u.has(m.id)||(u.add(m.id),!c(m)&&dt.setMaterialSection(m,l,n,a))};e.traverse(m=>{const g=m.material;Array.isArray(g)?g.forEach(x=>{f(x)}):g&&f(g)})}}}findSpatialFilter(e,i){const s=i.objects.SPATIAL_FILTER;if(!s)return;let r;for(const n of s)if(n.handle===e){r=n;break}return r}getAnyMaterial(e){const i=e;if(i.material)return Array.isArray(i.material)?i.material[0]:i.material;let s;for(let r=0;r<e.children.length&&(s=this.getAnyMaterial(e.children[r]),!s);r++);return s}generateSectionsBySpatialFilter(e,i){const s=e.clipPolylines[0];if(s.bConcave){S.warn("[Viewer] clipPolyline.bConcave = true is not supported yet in spatialFilter !");return}Pt.copy(i),e.localMatrix&&Pt.multiply(e.localMatrix);const r=s.polyline,n=[];r.forEach(l=>{const c=l.clone().applyMatrix4(Pt);n.push(new d.Vector2(c.x,c.y))});const a=d.ShapeUtils.isClockWise(n),o=!a&&!s.bReversed||a&&s.bReversed;return dt.generateSectionPlanesByPoints(n,o)}hasObject(e){return!!this.modelObject.getObjectById(e.id)}hasObjectWithId(e){return!!this.modelObject.getObjectById(e)}highlightObject(e){if(!this.hasObject(e))return;const i=de.clonedHighlightMaterials(e,{depthTest:!1});i&&(e.userData.originalMaterial=e.material,e.material=i)}unHighlightObject(e){if(!this.hasObject(e))return;const i=e.material;e.material=e.userData.originalMaterial,delete e.userData.originalMaterial,Array.isArray(i)?i.forEach(s=>s.dispose()):i instanceof d.Material&&i.dispose()}clearHighlight(){}}class zs extends Ji{constructor(e){super();p(this,"modelId");p(this,"bbox");p(this,"rootObject");p(this,"modelObject");p(this,"highlighUsage");p(this,"transparentUsage");p(this,"edges");p(this,"highlighedObject");this.modelId=e.modelId,this.bbox=e.bbox,this.modelObject=e.object,this.rootObject=new d.Group,this.rootObject.name="rootObject-"+this.modelId,this.rootObject.userData.modelId=this.modelId,this.highlighUsage=new d.Group,this.highlighUsage.name="highlighUsage-"+this.modelId,this.highlighUsage.layers.disable(ft),this.transparentUsage=new d.Group,this.transparentUsage.name="transparentUsage-"+this.modelId,this.transparentUsage.layers.disable(ft),this.rootObject.add(this.modelObject),this.rootObject.add(this.highlighUsage),this.rootObject.add(this.transparentUsage)}setDoubleSidedMaterials(){this.getModelObject().traverse(e=>{e instanceof d.Mesh&&$.setDoubleSidedMaterialToObject(e)})}revertDoubleSidedMaterials(){this.getModelObject().traverse(e=>{e instanceof d.Mesh&&$.revertDoubleSidedMaterialToObject(e)})}getModelObject(){return this.rootObject}getBBox(){return!this.bbox&&(this.bbox=new d.Box3,this.bbox.setFromObject(this.getModelObject())),this.bbox}async enableOutline(e,i){e&&!this.edges&&(this.edges=await $.createOutlines(this.getModelObject(),void 0,i)),this.edges&&this.edges.forEach(s=>s.visible=e)}setObjectColor(e,i){this.hasObject(e)&&e.material.color.set(i)}setObjectOpacity(e,i=.5,s,r){if(this.hasObject(e)){if(e instanceof d.InstancedMesh&&r){const n=this.createInstanceMeshById(e,r,{opacity:i});n.material.opacity*=i,e.userData.instanceId=r,e.userData.transparentedMesh=n,this.transparentUsage.add(n)}else if(oe.isMergedMesh(e)&&s){const n=this.createBatchMeshById(e,s,{opacity:i});n.material.opacity*=i,e.userData.batchId=s,e.userData.transparentedMesh=n,this.transparentUsage.add(n)}else{const n=new d.MeshBasicMaterial({color:0,transparent:!0,opacity:.05});n&&(e.userData.originalMaterial=e.material,e.material=n)}e.userData.isTransparent=!0}}clearObjectOpacity(e,i,s){if(!this.isObjectTransparent(e))return;const{transparentedMesh:r,originalMaterial:n}=e.userData;r&&(this.transparentUsage.remove(r),delete e.userData.batchId,delete e.userData.instanceId,delete e.userData.transparentedMesh),n&&(e.material=n),delete e.userData.isTransparent}isObjectTransparent(e){const{isTransparent:i}=e.userData;return!!i}setOpacity(e=.5){this.getModelObject().traverse(i=>{i instanceof d.Mesh&&this.setObjectOpacity(i,e)})}clearOpacity(){this.getModelObject().traverse(e=>{e instanceof d.Mesh&&this.clearObjectOpacity(e)})}highlightObjectById(e,i,s){if(!this.hasObjectWithId(e))return;const r=this.getModelObject().getObjectById(e);r&&this.highlightObject(r,i,s)}highlightObject(e,i,s){if(!this.hasObject(e))return;const r=new d.Color(Bs);if(e instanceof d.InstancedMesh&&s){const n=this.createInstanceMeshById(e,s,{depthTest:!1});n.material.opacity=.7,de.setMaterialColor(n.material,r),e.userData.instanceId=s,e.userData.clonedMesh=n,this.highlighUsage.add(n)}else if(oe.isMergedMesh(e)&&i){const n=this.createBatchMeshById(e,i,{depthTest:!1});n.material.opacity=.7,de.setMaterialColor(n.material,r),e.userData.batchId=i,e.userData.clonedMesh=n,this.highlighUsage.add(n)}else{const n=de.clonedHighlightMaterials(e,{depthTest:!1});n&&(e.userData.originalMaterial=e.material,e.material=n)}e.userData.isHighlight=!0,this.highlighedObject=e}clearHighlight(){if(this.highlighedObject&&this.highlighedObject.userData){const e=this.highlighedObject.userData,{clonedMesh:i,originalMaterial:s,instanceId:r,originalMatrix:n}=e;i&&(i.removeFromParent(),i.geometry.dispose(),delete e.clonedMesh),r&&n&&(this.highlighedObject.setMatrixAt(r,n),delete e.instanceId,delete e.originalMatrix),s&&(this.highlighedObject.material=s,delete e.originalMaterial),delete e.isHighlight}this.highlighUsage.clear(),this.highlighedObject=void 0}setObjectVisible(e,i){this.hasObject(e)&&(e.visible=i)}setVisible(e){this.getModelObject().traverse(i=>{i instanceof d.Mesh&&(i.visible=e)})}hasVisibleObject(){let e=0;return this.modelObject.traverseVisible(i=>{i instanceof d.Mesh&&e++}),e>0}hasInvisibleObject(){let e=0;return this.modelObject.traverse(i=>{i instanceof d.Mesh&&e++}),this.modelObject.traverseVisible(i=>{i instanceof d.Mesh&&e--}),e>0}createBatchMeshById(e,i,{opacity:s=1,depthTest:r=!0}){const n=oe.getBatchByBatchId(e,i);let a="[Viewer] Clicked on merged mesh(id: "+e.id+").";a+=" batchId: "+i+", object name: "+n?.name,n?.userData&&(a+=`
|
|
796
|
+
`){f=0,m-=g*.5;continue}let C=this.font?.getCharShape?.(_,i?.fontFile,s);if(!C&&i?.bigFontFile&&(C=this.font?.getCharShape?.(_,i.bigFontFile,s)),!C&&this.font?.fileNames){const w=this.font.fileNames.filter(M=>M!==i?.fontFile);for(let M=w.length-1;M>=0&&(i.fontFile=w[M],i.styleName="Standard",C=this.font?.getCharShape?.(_,i.fontFile,s),!C);M--);}if(C||(C=this.font?.getNotFoundTextShape?.(s)),!!C){if(C.translate(f,m,0),f>o)f=0,m-=g;else{!C.boundingBox&&C.computeBoundingBox();const w=C.boundingBox.getSize(j).x,M=_.charCodeAt(0),A=M>=19968&&M<=40959||M>=13312&&M<=19903||M>=63744&&M<=64255||M>=12288&&M<=12351||M>=65280&&M<=65519||[8216,8217,8220,8221].includes(M)?Math.max(w,s):w+T;E++,f+=A+(E===b?0:l)}u.push(C)}}if(u.length>0){const O=u.filter(C=>C instanceof d.ExtrudeGeometry),_=u.filter(C=>!(C instanceof d.ExtrudeGeometry));if(O.length>0){const C=new F(H.Mesh);C.geometry=xe.mergeGeometries(O),C.material=_t,c.add(C)}if(_.length>0){const C=new F(H.LineSegment);C.geometry=xe.mergeGeometries(_),C.material=le,c.add(C)}}return c}transformTextMesh(e,i){We.makeEmpty();const s=F.getBox(i,We),r=s.getSize(j),{halign:n,valign:a}=e;i.matrix.decompose(_i.position,_i.quaternion,_i.scale);const o=_i,l=e.width||e.textWidth||r.x,c=e.height||e.textHeight||r.y;if(n===void 0&&a===void 0&&e.startPoint||[3,5].includes(n)&&e.startPoint?(o.position.x+=e.startPoint.x,o.position.y+=e.startPoint.y,o.position.z+=e.startPoint.z):e.endPoint&&(o.position.x+=e.endPoint.x,o.position.y+=e.endPoint.y,o.position.z+=e.endPoint.z),n!==3&&n!==5){if(e.rotation){const u=e.rotation*Math.PI/180;o.rotateZ(u)}e.mirrored&2&&o.rotateY(Math.PI),e.mirrored&4&&o.rotateX(Math.PI)}switch(n){case 0:break;case 1:o.translateX(-l/2);break;case 2:o.translateX(-l);break;case 3:if(e.startPoint&&e.endPoint){const u=new d.Vector3(e.startPoint.x,e.startPoint.y,e.startPoint.z),f=new d.Vector3(e.endPoint.x,e.endPoint.y,e.endPoint.z),m=new d.Vector3().subVectors(u,f),g=m.length(),x=g/l;o.scale.multiplyScalar(x);const y=m.clone().cross(Ae),T=m.angleTo(Ae);o.rotateZ(y.z>0?Math.PI-T:T-Math.PI),(e.mirrored===2||e.mirrored===4)&&o.rotateX(Math.PI)}break;case 4:o.translateX(-l/2),o.translateY(-c/12);break;case 5:if(e.startPoint&&e.endPoint){const u=new d.Vector3(e.startPoint.x,e.startPoint.y,e.startPoint.z),f=new d.Vector3(e.endPoint.x,e.endPoint.y,e.endPoint.z),m=new d.Vector3().subVectors(u,f),g=m.length(),x=g/l,T=(e.text||"").length;if(T>1){const E=(g-l)/(T-1);o.userData.letterSpacing=E}else x<3&&o.scale.setX(x);const v=m.clone().cross(Ae),b=m.angleTo(Ae);o.rotateZ(v.z>0?Math.PI-b:b-Math.PI)}break}switch(a){case 0:break;case 1:break;case 2:o.translateY(-c/2);break;case 3:o.translateY(-c);break}return o.position.z=0,o.updateMatrix(),i.matrix.copy(o.matrix),i}loadText(e,i,s){const r=e.text;if(!r)return;if(!this.font){S.info("[Dxf] Font file not set, ignoring text entity.");return}const n=this.getTextStyle(i,e),o=Ni(r,{encoding:this.getTextEncoding(n)}).map(u=>u.text).join(""),l=this.getTextMesh(o,e.textHeight,n,e);if(!l||l.children.length===0)return;this.transformTextMesh(e,l),j.set(l.matrix.elements[12],l.matrix.elements[13],l.matrix.elements[14]);const c=U.shouldRebasePositionOnRTC(j);return c&&this.setRTCUserData(l),l.userData={...l.userData,textContent:r,dxfType:"TEXT",isMText:!1,layer:e.layer||"0",handle:e.handle,entityId:e.entityId||e.handle},l.traverse(u=>{const f=u.geometry;if(f){if(u.userData.textContent=r,u.userData.dxfType="TEXT",u.userData.layer=e.layer||"0",u.userData.handle=e.handle,u instanceof d.Mesh&&!f.getIndex()){const m=f.getAttribute("position"),g=[];for(let x=0;x<m.count;x+=3)g.push(x,x+1,x+2);f.setIndex(g)}if(f.hasAttribute("uv")&&f.deleteAttribute("uv"),f.hasAttribute("normal")&&f.deleteAttribute("normal"),!c){const m=U.caculateGeometryCenter(f);m&&U.shouldRebasePositionOnRTC(m)&&this.setRTCUserData(u)}}}),l.layers.enableAll(),l}loadAttDef(e,i,s){let r=e.tag||e.text||e.prompt;if(!r||!this.font)return;const n=this.getTextStyle(i,e);r=Ni(r).map(c=>c.text).join();const o=this.getTextMesh(r,e.textHeight,n,e);if(!o||o.children.length===0)return;this.transformTextMesh(e,o),j.set(o.matrix.elements[12],o.matrix.elements[13],o.matrix.elements[14]);const l=U.shouldRebasePositionOnRTC(j);return l&&this.setRTCUserData(o),o.traverse(c=>{const u=c.geometry;if(u){if(c instanceof d.Mesh&&!u.getIndex()){const f=u.getAttribute("position"),m=[];for(let g=0;g<f.count;g+=3)m.push(g,g+1,g+2);u.setIndex(m)}if(u.hasAttribute("uv")&&u.deleteAttribute("uv"),u.hasAttribute("normal")&&u.deleteAttribute("normal"),!l){const f=U.caculateGeometryCenter(u);f&&U.shouldRebasePositionOnRTC(f)&&this.setRTCUserData(c)}}}),o.layers.enableAll(),o}loadAttrib(e,i,s){let r=e.text;if(!r||!this.font)return;const n=this.getTextStyle(i,e);r=Ni(r).map(f=>f.text).join("");const o=this.getTextMesh(r,e.textHeight,n,e);if(!o||o.children.length===0)return;const l=s?.zdysx;o.userData.llbData=l;let c;if(l)try{c=JSON.parse(l)}catch{c=l}o.userData.textContent=r||"",o.userData.dxfType="ATTRIB",o.userData.layer=e.layer||"0",o.userData.handle=e.handle||"",this.transformTextMesh(e,o),j.set(o.matrix.elements[12],o.matrix.elements[13],o.matrix.elements[14]);const u=U.shouldRebasePositionOnRTC(j);return u&&this.setRTCUserData(o),o.traverse(f=>{const m=f.geometry;if(m){if(f instanceof d.Mesh&&!m.getIndex()){const g=m.getAttribute("position"),x=[];for(let y=0;y<g.count;y+=3)x.push(y,y+1,y+2);m.setIndex(x)}if(m.hasAttribute("uv")&&m.deleteAttribute("uv"),m.hasAttribute("normal")&&m.deleteAttribute("normal"),f instanceof d.Mesh&&(f.entity=e,f.userData.entity=e),f.userData.textContent=r,f.userData.dxfType="ATTRIB",f.userData.layer=e.layer||"0",f.userData.handle=e.handle||"",c!==void 0&&(f.userData.xdata=c),!u){const g=U.caculateGeometryCenter(m);g&&U.shouldRebasePositionOnRTC(g)&&this.setRTCUserData(f)}}}),o.layers.enableAll(),o}loadPoint(e,i,s){if(!e.position)return;const r=new d.BufferGeometry,n=[new d.Vector3(e.position.x,e.position.y,e.position.z)];j.set(0,0,0);const a=j;let o=!1;this.enableRTC&&(o=U.checkAndRebasePositionsOnRTC(n,a)),r.setFromPoints(n);const l=new F(H.Point);return l.geometry=r,l.material=le,o&&(this.setRTCUserData(l),l.matrix.setPosition(a.x,a.y,0)),l.layers.enableAll(),l}loadDimension(e,i){if(!e.block)return;const s=i.blocks[e.block];if(!s||!s.entities)return;const r=i.tables.dimStyle.dimStyles[e.dimStyleName]||this.getDefaultDimensionStyle(i);r&&r.DIMCLRD>0&&(e.colorIndex=r.DIMCLRD,e.color=Nt(e.colorIndex));const n=new F;for(let o=0;o<s.entities.length;o++){const l=this.loadEntity(s.entities[o],i,e);l&&n.add(l)}if(n.children.length===0){const o=e.name||e.block;return!this.statsInfo.ignoredInserts[o]&&(this.statsInfo.ignoredInserts[o]=0),this.statsInfo.ignoredInserts[o]++,void 0}else{!this.blockReferencesCache[e.block]&&(this.blockReferencesCache[e.block]={referenceCount:0});const o=this.blockReferencesCache[e.block];o.referenceCount++}n.name=e.type+"<"+s.name+">",n.userData.entityType=e.type;const a=e.insertionPoint;return j.set(0,0,0),a&&j.set(a.x,a.y,0),U.shouldRebasePositionOnRTC(j)&&this.setRTCUserData(n),n.matrix.setPosition(j),n}loadImage(e,i,s){if(!e.imageSize||!i.objects.IMAGEDEF?.length)return;const r=i.objects.IMAGEDEF.filter(y=>y.handle===e.imageDefHandle)[0];if(!r)return;const n=e.imageSize.x,a=e.imageSize.y,o=new F;let l=!1;e.flags===Gi.ShowImageWhenNotAlignedWithScreen||e.flags===Gi.UseClippingBoundary||e.flags===Gi.TransparencyIsOn||(l=!0);const c=new d.PlaneGeometry(n,a);if(l){const y=new d.TextureLoader(this.manager).load(r.filename,void 0,void 0,()=>{console.warn("Please upload the pictures in the same folder, or use url link in the dxf file.")});y.colorSpace=d.SRGBColorSpace;const T=new d.MeshBasicMaterial({transparent:!0,side:d.FrontSide,map:y}),v=new F(H.Mesh);v.geometry=c,v.material=T,o.add(v)}const u=new d.EdgesGeometry(c),f=this.getColor(e,i,s),m=new F(H.Line);m.geometry=u,m.material=this.getLineBasicMaterial(f);const g=e.uPixel?new d.Vector3(e.uPixel.x,e.uPixel.y,e.uPixel.z):new d.Vector3(r.pixelSize.x,0,0),x=e.vPixel?new d.Vector3(e.vPixel.x,e.vPixel.y,e.vPixel.z):new d.Vector3(r.pixelSize.y,0,0);if(o.add(m),Z.set(g.x,x.y,1),j.set(0,0,0),e.position){const y=new d.Vector3(e.position.x,e.position.y,e.position.z);y.add(g.multiplyScalar(n/2)).add(x.multiplyScalar(a/2)),j.copy(y)}return U.shouldRebasePositionOnRTC(j)&&this.setRTCUserData(o),he.identity(),o.matrix.compose(j,he,Z),o}loadInsert(e,i,s,r=!1){if(!e||!e.block)return;const n=i.blocks[e.block];if(!n||!n.entities)return;s&&e.layer==="0"&&(e.layer=s.layer),e.blockPosition=n.position;const a=new F,o=e.zdysx;let l;if(o)try{l=JSON.parse(o)}catch{l=o}for(let g=0;g<n.entities.length;g++){if(n.entities[g].type==="ATTDEF")continue;const x=this.loadEntity(n.entities[g],i,e,r);x&&(o&&V.LOADLLDATA&&(x.userData.llbData=o),l!==void 0&&x.traverse(y=>{y.geometry&&(y.userData.xdata=l)}),a.add(x))}if(a.children.length===0){const g=e.name||e.block;return!this.statsInfo.ignoredInserts[g]&&(this.statsInfo.ignoredInserts[g]=0),this.statsInfo.ignoredInserts[g]++,void 0}else{!this.blockReferencesCache[e.block]&&(this.blockReferencesCache[e.block]={referenceCount:0});const g=this.blockReferencesCache[e.block];g.referenceCount++}a.name=e.type+"<"+n.name+">",a.userData.entityType=e.type,l!==void 0&&(a.userData.xdata=l),e.extendedData?.originalType&&(a.userData.originalType=e.extendedData?.originalType),e?.blockPosition&&a.matrix.setPosition(-e.blockPosition.x,-e.blockPosition.y,0);const c=j.set(1,1,1);e.xScale&&(c.x=e.xScale),e.yScale&&(c.y=e.yScale);const u=new d.Euler;e.rotation&&(u.z=e.rotation*Math.PI/180),he.setFromEuler(u,!1);const f=Z.set(0,0,0);e.position&&(f.x=e.position.x,f.y=e.position.y),ne.compose(f,he,c),e.extrusionDirection&&e.extrusionDirection.z<0&&ne.premultiply(Or.identity().makeScale(-1,1,1)),Fe.copy(a.matrix),a.matrix.premultiply(ne),Z.set(a.matrix.elements[12],a.matrix.elements[13],a.matrix.elements[14]),U.shouldRebasePositionOnRTC(Z)&&this.setRTCUserData(a);const m=this.findSpatialFilterByHandle(e.handle,i);if(m){this.loadSpatialFilter(m);const g=m;g&&g.clipPolylines&&g.clipPolylines.length>0&&(a.userData.spatialFilterHandle=m.handle,this.cloneMaterialsForSpatialFilter(a),S.debug("[Dxf] Spatial filter:",e.associatedSpatialFilter))}return a}loadSpatialFilter(e){const i=e;if(i.threejsObject)return i.threejsObject.clone();const s=e.invertBlockMatrix;ne.set(s[0],s[1],s[2],s[3],s[4],s[5],s[6],s[7],s[8],s[9],s[10],s[11],0,0,0,1);const r=[];e.vertices.forEach(o=>{r.push(new d.Vector3(o.x,o.y,0))});const n={polyline:[],bConcave:!1,bReversed:!1};if(e.numberOfPointsOnClipBoundary===2)n.polyline=r;else{const o=e.numberOfPointsOnClipBoundary,l=3;if(o<l)return S.warn("[Dxf] Invalid clipBoundary: "+e.handle+" !"),void 0;let c=[],u=-1;for(let g=0;g<o;g++){const x=r[g];for(let y=o-1;y>g;y--){const T=r[y];if(R.areVector3sEqual(x,T)&&g+1<y-1&&g+1<o-1&&R.areVector3sEqual(r[g+1],r[y-1])){c.push(x),u=y;break}}if(u>0)break;c.push(x)}if(u>0)for(let g=u+1;g<o;g++)c.push(r[g]);if(c.length<l)return S.warn("[Dxf] Invalid clipBoundary: "+e.handle+"!"),void 0;const f=[],m=[];if(c.forEach(g=>{f.push(new d.Vector2(g.x,g.y)),m.push([g.x,g.y])}),!U.isConvex(f)){S.warn("[Dxf] Concave polygon is not supported for spatial filter (handle '"+e.handle+"'), converting to convex polygon!");const g=xa(m,1/0);c=[],g.forEach(x=>{c.push(new d.Vector3(x[0],x[1],0))})}!R.areVector3sEqual(c[0],c[c.length-1])&&c.push(c[0]),n.polyline=c,n.bReversed=u>0}let a;return this.enableReleaseData&&(e.vertices=[],e.matrix=[],e.invertBlockMatrix=[]),i.localMatrix=ne.clone(),i.clipPolylines=[],i.clipPolylines.push(n),a}loadLayout(e,i,s,r,n,a){if(!e.entities)return;const o=new F;for(let u=0;u<e.entities.length;u++){const f=e.entities[u];this.addViewport(f,a);const m=this.loadEntity(f,i);m&&(this.enableMerge&&et.merge(m,!1),o.add(m),m.traverse(g=>{if(g.geometry){const x=g.userData.layerName;let y=n[x];!y&&(y=[],n[x]=y),y.push(g),g.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[s.layoutName]&&(this.layoutsSnapObjectsMap[s.layoutName]=[]),this.layoutsSnapObjectsMap[s.layoutName].push(g))}}))}if(o.children.length===0)return;o.userData.layerName=e.layer;const l=s.layoutName;let c=r.children.find(u=>u.name===l);!c&&(c=new F,c.name=l,c.userData.isLayoutLevelObject=!0,r.add(c)),c.add(o),e.position&&o.matrix.setPosition(e.position.x,e.position.y,e.position.z||0)}convertEdgeToPoints(e){const i=[];if(!e)return i;switch(e.type){case Lt.Line:{const r=e;i.push(new d.Vector2(r.startPoint.x,r.startPoint.y)),i.push(new d.Vector2(r.endPoint.x,r.endPoint.y));break}case Lt.Arc:{const r=e;let n=r.startAngle*d.MathUtils.DEG2RAD,a=r.endAngle*d.MathUtils.DEG2RAD;!r.bCounterclockwise&&(n=Math.PI*2-n,a=Math.PI*2-a);const o=new d.ArcCurve(r.center.x,r.center.y,r.radius,n,a,!r.bCounterclockwise),l=this.getDivision(n,a,r.radius),c=o.getPoints(l);e.startPoint=c[0],e.endPoint=c[c.length-1],i.push(...c);break}case Lt.Ellipse:{const r=e,n=Math.sqrt(Math.pow(r.majorAxisEndPoint.x,2)+Math.pow(r.majorAxisEndPoint.y,2)),a=n*r.minorRatio,o=Math.atan2(r.majorAxisEndPoint.y,r.majorAxisEndPoint.x);let l=r.startAngle*d.MathUtils.DEG2RAD,c=r.endAngle*d.MathUtils.DEG2RAD;!r.bCounterclockwise&&(l=Math.PI*2-l,c=Math.PI*2-c);const u=new d.EllipseCurve(r.center.x,r.center.y,n,a,l,c,!r.bCounterclockwise,o),f=this.getDivision(l,c,Math.max(n,a)),m=u.getPoints(f);e.startPoint=m[0],e.endPoint=m[m.length-1],i.push(...m);break}case Lt.Spline:{const r=e,n=kr(r.controlPoints,r.degreeOfSplineCurve,r.knotValues);if(n.length===0)break;e.startPoint=n[0],e.endPoint=n[n.length-1],i.push(...n);break}case Lt.Polyline:{const r=e,n=us(r.points,r.isClosed);e.startPoint=n[0],e.endPoint=n[n.length-1],i.push(...n);break}}return i}loadHatch(e,i,s){const r=e;let n=[];function a(O,_){const{startPoint:C,endPoint:w}=O,{startPoint:M,endPoint:P}=_,A=w.x-C.x,I=w.y-C.y,k=P.x-M.x,B=P.y-M.y,L=A*B-I*k;if(Math.abs(L)<1e-10)return null;const q=C.x-M.x,me=C.y-M.y,ue=(k*me-B*q)/L,nt=(A*me-I*q)/L;return ue>=0&&ue<=1&&nt>=0&&nt<=1?{x:C.x+ue*A,y:C.y+ue*I}:null}function o(O){const{edges:_}=O,C=[],w=_.length;if({...O},w!==4)return[O];for(let M=0;M<w;M++)for(let P=M+2;P<w;P++){if(P===M+1||M===0&&P===w-1)continue;const A=a(_[M],_[P]);A&&C.push({edgeIndex1:M,edgeIndex2:P,point:{x:A.x,y:A.y}})}if(C.length&&C.length===1){const M={pathTypeFlag:O.pathTypeFlag,edges:[_[C[0].edgeIndex1-1],{startPoint:{..._[C[0].edgeIndex1].startPoint},endPoint:{x:C[0].point.x,y:C[0].point.y},type:_[C[0].edgeIndex1].type},{startPoint:{x:C[0].point.x,y:C[0].point.y},endPoint:{x:_[C[0].edgeIndex2].startPoint.x,y:_[C[0].edgeIndex2].startPoint.y},type:_[C[0].edgeIndex2].type}]},P={pathTypeFlag:O.pathTypeFlag,edges:[{startPoint:{x:C[0].point.x-1e-5,y:C[0].point.y-1e-5},endPoint:{..._[C[0].edgeIndex1].endPoint},type:_[C[0].edgeIndex1].type},{..._[C[0].edgeIndex2-1]},{startPoint:_[C[0].edgeIndex2].startPoint,endPoint:{x:C[0].point.x-1e-5,y:C[0].point.y-1e-5},type:_[C[0].edgeIndex2].type}]};return[M,P]}return[O]}if(r.boundaryPaths.length==0)return;for(let O=0;O<r.boundaryPaths.length;O++){const _=r.boundaryPaths[O],C=o(_);n=[...n,...C]}if(r.boundaryPaths=n,!r.solidFill&&!r.patternLines?.length){S.warn("[Dxf] Hatch entity(handle: '"+r.handle+"') doesn't have solid fill, nor patternLines, ignored!");return}const l=[],c=[],u=[],f=O=>{const _=[];let C=[];C.push(...this.convertEdgeToPoints(O[0]));for(let w=1;w<O.length;w++){const M=this.convertEdgeToPoints(O[w]);if(C.push(...M),C.length>2){const P=this.convertEdgeToPoints(O[w-1]);R.areVector2sEqual(P[P.length-1],M[0])?R.areVector2sEqual(C[0],M[M.length-1],1e-5)&&(_.push(C),C=[]):R.areVector2sEqual(P[0],M[M.length-1])?R.areVector2sEqual(C[1],M[0],1e-5)&&(_.push(C),C=[]):C=[]}}return _};if(r.boundaryPaths.forEach((O,_)=>{let C=[];if(this.IsfilteredByPathTypeFlag(O.pathTypeFlag)){S.info("[Dxf] The %d path type flag is filtered at the %dth boundrayPath (hatch handle '%s')",O.pathTypeFlag,_,r.handle);return}const w=O.edges;if(w.length===0)return;const M=[];for(let P=0;P<w.length;P++){const A=this.convertEdgeToPoints(w[P]);if(A.length<2){S.warn("[Dxf] The %dth edge of the %dth boundaryPath (hatch handle '%s') has less than 2 points, ignored!",P,_,r.handle);continue}M.push(...A)}if(M.length<3){S.warn("[Dxf] The %dth boundaryPath (hatch handle '%s') has less than 3 points, ignored!",_,r.handle);return}if(C.push(M),O.pathTypeFlag>Mn.MaxFlags&&(!(A=>{for(let I=1;I<A.length;++I){const k=A[I-1].endPoint,B=A[I].startPoint;if(!k||!B||!R.areVector2sEqual(k,B))return!1}return!0})(O.edges)||!r.associativity)&&(C=f(w),C.length<2)){S.warn("[Dxf] The %dth boundaryPath (hatch handle '%s') has unknown path, ignored!",_,r.handle);return}C.forEach(P=>{!R.areVector2sEqual(P[0],P[P.length-1])&&P.push(P[0]);const A=P.map(I=>new d.Vector2(z.roundNumber(I.x,7),z.roundNumber(I.y,7)));if(A?.length>0){l.push(A);const I=new d.Box2().setFromPoints(A);c.push(I);const k=I.getSize(Qt),B=k.x*k.y;u.push({area:B,index:l.length-1})}})}),l.length===0)return;const m=new d.Vector2,g=this.checkAndRebasePolygonsOnRTC(l,m);u.sort((O,_)=>O.area-_.area);const x=[];u.forEach(O=>{x.push(O.index)});const y=this.buildContainHierarchyTree(l,c,x),T=[];this.buildHatchGeometry(l,y,T);let v;if(T.length>0&&(v=xe.mergeGeometries(T)),!v||!v.getIndex()||v.getIndex()?.count===0)return S.warn("[Dxf] Failed to convert hatch boundaries!"),void 0;const b=new F(H.Mesh);b.geometry=v,b.material=_t,this.setHatchMaterial(b,r,i,m,s);const E=b;return g&&(this.setRTCUserData(E),E.matrix.setPosition(m.x,m.y,0)),E.traverse(O=>{O.layers.enableAll(),O.layers.disable(Ce)}),E}loadOle2frame(e,i){const{leftUpX:s,leftUpY:r,rightDownX:n,rightDownY:a}=e;if(!s||!r||!n||!a)return;const o=[new d.Vector2(s,r),new d.Vector2(s,a),new d.Vector2(n,a),new d.Vector2(n,r),new d.Vector2(s,r)],l=new d.Vector3;let c=!1;this.enableRTC&&(c=U.checkAndRebasePositionsOnRTC(o,l));const u=new d.BufferGeometry().setFromPoints(o),f=this.getLineBasicMaterial(16777215),m=new F(H.Line);m.geometry=u,m.material=f,m.layers.enableAll(),c&&(this.setRTCUserData(m),m.matrix.setPosition(l.x,l.y,0));const g=new F;g.add(m);let x;const y=i.objects.DICTIONARY;for(const v of y)for(const b in v.entries)if(v.entries[b]===e.handle){x=b;break}let T;if(x)if(this.meshTextureMaterials[x])T=this.meshTextureMaterials[x];else for(let v=0;v<i.objects.XRECORD.length;v++){const b=i.objects.XRECORD[v];if(b.handle===x){const E=b.binaryData,O=z.hexToBase64(E),_="data:image/jpg;base64,"+O,C=new d.TextureLoader(this.manager).load(_);C.colorSpace=d.SRGBColorSpace;const w=new d.MeshBasicMaterial({transparent:!0,map:C});this.meshTextureMaterials[x]=w,T=w;break}}if(T){const v=new d.Box2().setFromPoints(o),b=v.getSize(Qt),E=new d.PlaneGeometry(b.x,b.y),O=new F(H.Mesh);O.geometry=E,O.material=T;const _=v.getCenter(Qt);j.set(_.x,_.y,0),c&&(this.setRTCUserData(O),j.x+=l.x,j.y+=l.y),O.matrix.setPosition(j),O.layers.enableAll(),g.add(O)}return g.children.length>1?g:m}static getOcsMatrix(e){let i=Ae,s=ds,r=Et;const n=new d.Vector3(0,1,0),a=new d.Vector3(0,0,1);return R.areVectorsClose(e,a)?ne.identity():(r=e.clone().normalize(),!R.areVectorsClose(r,a)&&(Math.abs(r.x)<1/64&&Math.abs(r.y)<1/64?i=n.cross(r).normalize():i=a.cross(r).normalize(),s=r.clone().cross(i).normalize()),ne.set(i.x,i.y,i.z,0,s.x,s.y,s.z,0,r.x,r.y,r.z,0,0,0,0,1))}static getDcs2WcsMatrix(e,i){let s;ih(e)?s=e.viewDirectionFromTarget:s=e.viewDirection,s??(s={x:0,y:0,z:1});const r=e.viewTarget??{x:0,y:0,z:0},n=new d.Vector3(R.roundNumber(s.x,7),R.roundNumber(s.y,7),s.z),a=new d.Vector3(r.x,r.y,r.z),o=e.viewTwistAngle||0;let l,c,u;u=n.clone().normalize(),l=Et.clone().cross(n),l.length()>0?(l.normalize(),c=u.clone().cross(l)):u.z<0?(l=Ae.clone().negate(),c=ds,u=Et.clone().negate()):(l=Ae,c=ds,u=Et);const f=new d.Matrix4,m=ne.identity();return m.makeBasis(l,c,u),f.premultiply(m),f.premultiply(ne.identity().compose(a.clone(),new d.Quaternion().setFromAxisAngle(new d.Vector3(0,0,1),d.MathUtils.degToRad(i?o:-o)),new d.Vector3(1,1,1))),f}getViewportMsToPsMatrix(e){const i=e.centerPoint_dcs??{x:0,y:0},s=e.centerPoint??{x:0,y:0,z:0},r=new d.Vector3(i.x,i.y,0),n=new d.Vector3(s.x,s.y,s.z),a=e.viewHeight,o=e.height_paperSpace||1,l=(a||o)/o,c=V.getDcs2WcsMatrix(e,this.angDir),u=new d.Matrix4;u.setPosition(Cr.clone().sub(n));const f=Or.identity();f.scale(j.set(l,l,l));const m=Fe.identity().setPosition(Cr.clone().sub(n));f.premultiply(m.clone().invert()).multiply(m),u.multiply(f);const g=ne.identity();g.setPosition(r),c.multiply(g);const x=ne.identity();return u.invert().multiply(x).multiply(c.invert())}loadViewport(e,i,s){if(e.viewportId+""=="1"){e.psBBox=new d.Box3,e.msToPsMatrix=new d.Matrix4;return}const r=e.centerPoint;if(!r||!Number.isFinite(r.x)||!Number.isFinite(r.y)){e.psBBox=new d.Box3,e.msToPsMatrix=new d.Matrix4;return}const n=e.width_paperSpace/2,a=e.height_paperSpace/2,o=[new d.Vector3(r.x-n,r.y-a,0),new d.Vector3(r.x-n,r.y+a,0),new d.Vector3(r.x+n,r.y+a,0),new d.Vector3(r.x+n,r.y-a,0)];o.push(o[0]),e.psBBox=new d.Box3().setFromPoints([o[0],o[2]]),e.msToPsMatrix=this.getViewportMsToPsMatrix(e);let l=!1;const c=new d.Vector3;this.enableRTC&&(l=U.checkAndRebasePositionsOnRTC(o,c));const u=new d.BufferGeometry().setFromPoints(o),f=new F(H.Line);f.geometry=u,f.material=le,f.userData.entityType=e.type,f.layers.enableAll(),l&&(this.setRTCUserData(f),f.matrix.setPosition(c.x,c.y,0));const m=e.psBBox.clone();m.applyMatrix4(e.msToPsMatrix.clone().invert()),m.min.z=0,m.max.z=0;const g=[m.min,new d.Vector3(m.min.x,m.max.y,0),m.max,new d.Vector3(m.max.x,m.min.y,0)];g.push(g[0]);let x=!1;const y=new d.Vector3;this.enableRTC&&(x=U.checkAndRebasePositionsOnRTC(g,y));const T=new d.BufferGeometry().setFromPoints(g),v=new F(H.Line);v.geometry=T,v.material=le,v.userData.entityType=e.type,v.userData.inPaperSpace=[],v.layers.enableAll(),x&&(this.setRTCUserData(v),v.matrix.setPosition(y.x,y.y,0));const b=new F;return b.add(f),b.add(v),f}getColor(e,i,s){if(this.compareContext)return Ue.ENTITY_COLOR_NO_CHANGE;if(this.overrideColor!=null)return this.overrideColor;const r=e;if(r&&r.isGradientColor){const n=r.gradientColors;if(n&&n.length>=2){if(n[0]!==n[1]){const a="[Dxf] Gradient colors are not supported for hatch '"+e.handle+"', will use the first color!";S.warn(a)}return n[0]}}if(e.isTrueColor||e.colorIndex>0&&e.colorIndex<256)return e.color;if(e.colorIndex===0)return s?this.getColor(s,i):i.tables?.layer?.layers[0].color;if(e.colorIndex===256){const n=i.tables?.layer?.layers,a=n&&n[e.layer],o=n&&s&&n[s.layer];let l=ct;return a&&a.name!=="0"?l=a.color:o?l=o.color:a?l=a.color:n&&n[0].color&&(l=n[0].color),l}return S.warn("[Dxf] Unknown colorIndex"),ct}getLineType(e,i,s){if(s&&s.type==="DIMENSION")return this.getLineType(s,i);if(e.lineType!==Fs&&e.lineType!==mi)return e.lineType;if(e.lineType===mi)return s?this.getLineType(s,i):e.lineType;const r=i.tables?.layer?.layers,n=th;if(e.layer!=="0"){const a=r&&r[e.layer];if(a)return a.lineType}else if(s){const a=r&&r[s.layer];if(a)return a.lineType}return n}getLayerName(e,i,s){const r=c=>{n&&c&&!n[e.layer]&&(console.warn("[Dxf] Failed to find layer object for '"+c+"', adding a default one."),n[c]={name:c,handle:"",colorIndex:256,lineType:"",visible:!0})},n=i.tables?.layer?.layers;r(e.layer);const a=n&&n[e.layer];r(s?.layer);const o=n&&s&&n[s.layer];let l=a?.name||"";return a&&a.name==="0"&&o&&(l=o.name),l}setMaterial(e,i,s,r){const n=e;if(!n.geometry||(this.setRenderOrderByObjectType(e),i.type==="OLE2FRAME"))return;if(i.type==="MTEXT"){e.renderOrder=ge.Text;return}if(i.type==="HATCH"){Qt.set(0,0),this.setHatchMaterial(e,i,s,Qt,r);return}if(i.type==="IMAGE")return;let a;const o=this.getColor(i,s,r);if(i.type==="LWPOLYLINE"&&(n.isMesh?(a=this.getMeshBasicMaterial(o),e.renderOrder=ge.LineWithWidth):e.userData.isOutline&&(a=this.getLineBasicMaterial(o),e.renderOrder=ge.LineWithPattern),a)){n.material=a;return}if(i.type==="SOLID")a=this.getMeshBasicMaterial(o);else if(i.type==="TEXT"||i.type==="ATTDEF"||i.type==="ATTRIB")a=this.getLineBasicMaterial(o),e.renderOrder=ge.Text;else if(i.type==="LEADER"||i.type==="MULTILEADER"||i.type==="VIEWPORT")a=this.getLineBasicMaterial(o);else if(i.type==="POINT")a=this.getPointsMaterial(o);else{if(e.material instanceof d.PointsMaterial){a=this.getPointsMaterial(o),n.material=a;return}const l=s.tables?.lineType?.lineTypes,c=l&&l[this.getLineType(i,s,r)];if(c&&c.pattern&&c.pattern.length!==0){const u=i.lineTypeScale||1;a=this.getLineShaderMaterial(c,o,u),e.renderOrder=ge.LineWithPattern}else a=this.getLineBasicMaterial(o)}n.material=a}setHatchMaterial(e,i,s,r,n){const a=e;if(!a.geometry)return;const o=this.getColor(i,s,n);if(a.type===H.Line||a.type===H.LineSegment){a.material=this.getLineBasicMaterial(o);return}let l=ge.Mesh,c;if(i.solidFill)c=this.getMeshBasicMaterial(o);else{if(a.material instanceof d.ShaderMaterial){c=a.material;const u=new d.Color(o);!a.material.uniforms.u_color.value.equals(u)&&(c=a.material.clone(),V.updateMaterialUniforms(c),c.uniforms.u_color.value.set(o))}else c=this.getHatchShaderMaterial(i,o,r);l=ge.MeshWithPattern}!c&&(c=this.getMeshBasicMaterial(o),l=ge.Mesh),a.material=c,a.renderOrder=l}setRenderOrderByObjectType(e){const i=e;let s=0;i.isMesh?s=ge.Mesh:i.isLine?s=ge.Line:i.isPoints&&(s=ge.Point),e.renderOrder=s}getPointsMaterial(e){return!this.pointsMaterials[e]&&(this.pointsMaterials[e]=new d.PointsMaterial({size:.2,color:e})),this.pointsMaterials[e]}getLineBasicMaterial(e){return!this.lineBasicMaterials[e]&&(this.lineBasicMaterials[e]=new d.LineBasicMaterial({color:e})),this.lineBasicMaterials[e]}getLineShaderMaterial(e,i,s){const r=e.name+"_"+i+"_"+s;if(!this.lineShaderMaterials[r]){const n=this.getLineTypeScales(),a=n.ltScale*n.celtScale*s;this.lineShaderMaterials[r]=bn.createLineShaderMaterial(e.pattern,i,a,V.ViewportScaleUniform,V.CameraZoomUniform)}return this.lineShaderMaterials[r]}getMeshBasicMaterial(e){return!this.meshBasicMaterials[e]&&(this.meshBasicMaterials[e]=new d.MeshBasicMaterial({color:e})),this.meshBasicMaterials[e]}getHatchShaderMaterial(e,i,s){if(!e.patternLines||e.patternLines.length<1)return;const r=this.findMatchedHatchShaderMaterial(e,i);if(r)return r;const n=.005,a=.05;let o=2;e.patternLines.forEach(m=>{o=Math.max(m.dashPattern.length,o)});let l=0;const c=[],u=new d.Vector2;for(const m of e.patternLines){const g=new d.Vector2(m.origin.x,m.origin.y).sub(s).rotateAround(u,-d.MathUtils.degToRad(e.patternAngle)),x=new d.Vector2(m.delta.x,m.delta.y).rotateAround(u,-d.MathUtils.degToRad(m.angle));if(x.y===0)return S.warn("[Dxf] delta.y is equal to zero !"),void 0;const y=m.dashPattern.length;let T=!0,v=0;for(let w=0;w<y;++w){const M=m.dashPattern[w];M>0&&(T=!1),v+=Math.abs(M)}const b=T?a:n,E=[],O=[];let _=0;O[0]=_;for(let w=0;w<y;++w)E[w]=m.dashPattern[w],E[w]===0&&(E[w]=b*v),_+=Math.abs(E[w]),O[w+1]=_;for(let w=y;w<o;++w)E[w]=0;for(let w=O.length;w<o+1;++w)O[w]=_;const C={origin:g,delta:x,angle:m.angle-e.patternAngle,pattern:E,patternSum:O,patternLength:_};if(l+=4,l+=o,l+=o+1,l>V.MaxFragmentUniforms){S.warn("[Dxf] There will be warning in fragment shader when number of uniforms exceeds 1024, so extra hatch line patterns are ignored here!");break}c.push(C)}const f=vn(c,e.patternAngle,V.CameraZoomUniform,new d.Color(i),this.overrideHatchPatternLineThickness);return f.defines={MAX_PATTERN_SEGMENT_COUNT:o},this.hatchShaderMaterials.push({patternLines:e.patternLines,patternAngle:e.patternAngle,color:i,material:f}),f}getDivision(e,i,s){let r=Math.round(5e4/this.entityCount);r=Math.max(r,2),r=Math.min(r,10);const n=r*5;let o=r*2;if(this.averageCurveSize){const u=Math.pow(s/this.averageCurveSize,.5);o*=u,o=Math.max(o,r),o=Math.min(o,n)}let l=i-e;l<0&&(l+=Math.PI*2),o=Math.ceil(o*(l/Math.PI));let c=8;return l<.087?c=2:l<.174?c=3:l<.52?c=4:l<1.57?c=5:l<3.14?c=6:l<4.71&&(c=7),o=Math.max(o,c),this.averageCurveSize=(this.averageCurveSize*this.curveCount+s)/(this.curveCount+1),this.curveCount++,Math.max(o,12)}getBSplineInterpolationsPerSplineSegment(e,i){let s=1;this.averageCurveSize&&(s=Math.pow(i/this.averageCurveSize,.5),s=Math.max(s,.5),s=Math.min(s,2)),this.averageCurveSize=(this.averageCurveSize*this.curveCount+i)/(this.curveCount+1),this.curveCount++;let r=e*2*s;if(e>20){const n=Math.log10(e);r/=n}return r}async setDxfDataToIndexedDb(e,i){const s={dxfDataId:e,dxf:i};return new Promise((r,n)=>{Yi.instance().add(s,()=>{S.info("[Dxf] Saved '"+e+"' to indexedDb"),r()},a=>{n(a)})})}async getDxfDataFromIndexedDb(e){return new Promise((i,s)=>{Yi.instance().query(e,r=>{r&&r.length>0&&i(r[0].dxf),i(void 0)},()=>s())})}buildContainHierarchyTree(e,i,s){const r=new Map,n=s.length;for(let o=0;o<n;o++)r.set(s[o],{index:s[o],children:[]});const a={index:-1,children:[]};for(let o=0;o<n;o++){const l=s[o],c=e[l],u=i[l];let f=o+1;for(;f<n;f++){const m=s[f],g=e[m];if(i[m].containsBox(u)&&U.isPointInPolygon(c[z.generateRandomInt(0,c.length-1)],g)){r.get(m)?.children.push(r.get(l));break}}f===n&&a.children.push(r.get(l))}return a}buildHatchGeometry(e,i,s){if(i.children.length===0)return;const r=[],n=new Map;i.children.forEach(l=>{l.children.length===0?r.push(l.index):n.set(l.index,l.children.map(c=>c.index))});const a=l=>{try{const c=new d.ShapeGeometry(l);c.hasAttribute("uv")&&c.deleteAttribute("uv"),c.hasAttribute("normal")&&c.deleteAttribute("normal"),s.push(c)}catch{S.warn("[Dxf] triangulate shape error: "+l.getPoints().map(u=>u.toArray()).toString())}};r.forEach(l=>{const c=e[l];if(c.length===0)return;const u=new d.Shape(c);a(u)});const o=l=>l.map(c=>c.toArray());for(const l of n){const c=new d.Shape(e[l[0]]);let u={regions:[],inverted:!1};const f=this.findIntersectHole(e,l[1]);f.forEach(g=>{let x={regions:[],inverted:!1};try{g.forEach((y,T)=>{if(yt.epsilon(R.getVector2RelativeEps(e[y][0]),1e-6),T===0)x=yt.segments({regions:[o(e[y])],inverted:!1});else{const v=yt.segments({regions:[o(e[y])],inverted:!1}),b=yt.combine(x,v);u=yt.polygon(yt.selectUnion(b)),u.regions.length>0?u.regions.forEach(E=>{if(E.length===0)return;const O=E.map(_=>new d.Vector2(_[0],_[1]));c.holes.push(new d.Path(O))}):S.warn("[Dxf] mergedHoles.regions is empty")}})}catch(y){S.warn("[Dxf] polybooljs has error: "+y+", epsilon is "+yt.epsilon())}});const m=f.flat(2);for(let g=0;g<l[1].length;g++){const x=l[1][g];!m.includes(x)&&c.holes.push(new d.Path(e[x]))}a(c)}i.children.forEach(l=>{l.children.forEach(c=>{this.buildHatchGeometry(e,c,s)})})}findIntersectHole(e,i){const s=i.length,r=[];for(let n=0;n<s;n++){const a=e[i[n]];let o=!1;const l=[];for(let c=n+1;c<s;c++){const u=e[i[c]];U.arePolygonsIntersect(a,u)&&(o=!0,l.push(i[c]))}o&&(l.push(i[n]),r.push(l))}return r}checkAndRebasePolygonsOnRTC(e,i){if(!this.enableRTC||e.length===0)return!1;let s=0;e.forEach(n=>{n.forEach(a=>{i.add(a),s++})}),i.divideScalar(s);let r=!1;if(this.enableRTC&&U.shouldRebasePositionOnRTC(i)){r=!0;for(let n=0;n<e.length;n++){const a=e[n];for(let o=0;o<a.length;o++){const l=a[o].x-i.x,c=a[o].y-i.y;a[o]=new d.Vector2(l,c)}}}else i.set(0,0);return r}setRTCUserData(e){e.userData.relativeToCenter=!0,this.statsInfo.rebasedEntityCount++}IsfilteredByPathTypeFlag(e){return e<0}findSpatialFilterByHandle(e,i){const s=i.objects.DICTIONARY;if(!s)return;if(!this.dictionaryOwnerHandleAndSpatialFilterHandlesCache){this.dictionaryOwnerHandleAndSpatialFilterHandlesCache={};for(const n of s){const a=n;let o="";for(const l in a.entries)if(a.entries[l]==="ACAD_FILTER"){o=l;break}o&&(this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[n.ownerHandle]&&S.warn("[Dxf] Why this.dictionaryObjectsCache[obj.ownerHandle] already exist?",n.ownerHandle),this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[n.ownerHandle]=o)}}const r=this.dictionaryOwnerHandleAndSpatialFilterHandlesCache[e];if(r){if(!this.spatialFiltersCache){this.spatialFiltersCache={};const n=i.objects.SPATIAL_FILTER||[];for(const a of n){const o=a;o.numberOfPointsOnClipBoundary<2||(this.spatialFiltersCache[o.ownerHandle]&&S.warn("[Dxf] Why this.spatialFiltersCache[spatialFilterObj.ownerHandle] already exist?",r),this.spatialFiltersCache[o.ownerHandle]=o)}}return this.spatialFiltersCache[r]}}initRenderOrderInfo(e){const i=new Set,s=e.objects.DICTIONARY;for(const n of s){const a=n;Object.keys(a.entries).forEach(o=>{a.entries[o]&&a.entries[o]==="ACAD_SORTENTS"&&i.add(o)})}if(i.size===0)return;const r=e.objects.SORTENTSTABLE;if(r)for(let n=0;n<r.length;++n){const a=r[n];if(i.has(a.handle)){for(let o=0;o<a.sortEntsObject.entityHandles.length;++o){const l=a.sortEntsObject.entityHandles[o];l.length===2&&!this.entityHandlesWithRenderOrder[l[0]]?this.entityHandlesWithRenderOrder[l[0]]=l[1]:S.warn("[Dxf] Failed to handle sortEntsTable: "+a.handle+".")}break}}}findMatchedHatchShaderMaterial(e,i){const s=e.patternLines;if(!s||s.length<1)return;const r=(c,u)=>Math.abs(c-u)<1e-5,n=(c,u)=>{if(c.length!==u.length)return!1;for(let f=0;f<c.length;++f)if(!r(c[f],u[f]))return!1;return!0},a=(c,u)=>r(c.angle,u.angle)&&r(c.delta.x,u.delta.x)&&r(c.delta.y,u.delta.y)&&r(c.origin.x,u.origin.x)&&r(c.origin.y,u.origin.y)&&n(c.dashPattern,u.dashPattern),o=(c,u)=>{if(c.length!==u.length)return!1;for(let f=0;f<c.length;++f)if(!a(c[f],u[f]))return!1;return!0};return this.hatchShaderMaterials.find(c=>c.color===i&&c.patternAngle===e.patternAngle&&o(c.patternLines,s))?.material}getLayout(e,i){if(!this.blockRecordsCache){this.blockRecordsCache={};const n=this.blockRecordsCache,a=e.tables?.blockRecord?.blockRecords;a&&Object.values(a).forEach(o=>{n[o.handle]=o.layoutHandle})}const s=this.blockRecordsCache[i.ownerHandle];if(s){const n=e.objects.LAYOUT,a=n.find(o=>o.handle===s);if(a)return a}if(!this.entitiesCache){this.entitiesCache={};const n=this.entitiesCache;Object.values(e.entities).forEach(a=>{n[a.handle]=a})}const r=this.entitiesCache[i.ownerHandle];return r?this.getLayout(e,r):e.objects.LAYOUT.find(n=>n.layoutName===V.MODEL_LAYOUT_NAME)}getLayerVisible(e,i){const s=e.tables?.layer?.layers;return s&&s[i]?.visible}getLayerFrozen(e,i){const s=e.tables?.layer?.layers;return s&&s[i.layer]?.frozen}cloneMaterialsForSpatialFilter(e){const i=new Map,s=r=>{let n;if(Array.isArray(r)){const a=[];n=a,r.forEach(o=>{if(i.has(o.id))a.push(i.get(o.id));else{const l=o.clone();V.updateMaterialUniforms(l),i.set(o.id,l),a.push(l)}})}else r&&(i.has(r.id)?n=i.get(r.id):(n=r.clone(),V.updateMaterialUniforms(n),i.set(r.id,n)));return n};e.traverse(r=>{r.material&&(r.material=s(r.material))})}getLineTypeScales(){const e={ltScale:1,celtScale:1};return this.header&&(e.ltScale=this.header.$LTSCALE||1,e.celtScale=this.header.$CELTSCALE||1),e}static getDxfUnits(e){switch(e||0){case 0:return De.Unitless;case 1:return De.Inches;case 2:return De.Feet;case 4:return De.Millimeters;case 5:return De.Centimeters;case 6:return De.Meters;default:S.warn("[Dxf] Unsupported $INSUNITS '"+e+"'");break}return De.Unitless}static computeLineDistance(e){const i=e.isLineSegments===!0;let s=e.geometry;const r=e.matrixWorld;if(s.index&&(S.debug("[Dxf] Line with id '"+e.id+"' contains index buffer, going to convert it to non-indexed."),s=U.convertGeometryWithIndexedToNonIndexed(s),e.userData.batches&&e.userData.batches.length>0)){S.debug("[Dxf] This line has been merged!");let n=0;e.userData.batches.forEach(a=>{a.positionStart=n,a.positionCount=a.indexCount,a.indexStart=0,a.indexCount=0,n+=a.positionCount})}if(s.index===null){const n=s.attributes.position;if(!n||n.count===0)return;const a=[];if(i)for(let o=0,l=n.count;o<l;o+=2)j.fromBufferAttribute(n,o).applyMatrix4(r),Z.fromBufferAttribute(n,o+1).applyMatrix4(r),a[o]=o===0?0:a[o-1],a[o+1]=a[o]+j.distanceTo(Z);else{a[0]=0;for(let o=1,l=n.count;o<l;o++)j.fromBufferAttribute(n,o-1).applyMatrix4(r),Z.fromBufferAttribute(n,o).applyMatrix4(r),a[o]=a[o-1],a[o]+=j.distanceTo(Z)}s.setAttribute("lineDistance",new d.Float32BufferAttribute(a,1)),e.geometry=s}else S.warn("[Dxf] computeLineDistances only possible with non-indexed BufferGeometry.")}static computeLineDistances(e){const i=Date.now();e.traverse(s=>{const r=s;r.isLine&&r.material instanceof d.ShaderMaterial&&V.computeLineDistance(r)}),S.debug("[Dxf] Computed line distances in "+(Date.now()-i)/1e3+"s")}static mergeDxfObjects(e){const i=Date.now(),s={},r={},n=15e3;let a=0,o=0;const l=()=>{const u=Date.now();for(const f in s){const m=s[f];V.removeEmptyObjectsFromRemovingMarkedObjects2(m.children,m.object),m.children=[]}a=0,o+=Date.now()-u};for(const u in e.layersAndObjects){const f=e.layersAndObjects[u];if(f.length<=1)continue;const m=Date.now(),g={},x=[];for(const y of f){if(y.userData.isSnapObject){x.push(y);continue}let T,v=y;for(;v;){if(v.userData.isLayoutLevelObject){T=v;break}v=v.parent}if(!T)continue;const b=T.name;!g[b]&&(g[b]={object:T,children:[]}),g[b].children.push(y)}for(const y in g){const T=g[y],v=et.deepMerge(T.children,T.object,!1,!1,!0),b=v.added,E=v.removed;!s[y]&&(s[y]={object:T.object,children:[]}),!r[y]&&(r[y]={object:T.object,children:[]});const O=E.length>n;if(O){const _=Date.now();V.removeEmptyObjectsFromRemovingMarkedObjects2(E,T.object),o+=Date.now()-_}else a+=E.length;if(E.length===T.children.length)!O&&E.forEach(_=>{s[y].children.push(_)});else{let _=E;E.length>=100&&(_=new Set(E));const C=w=>Array.isArray(_)?_.indexOf(w)>=0:_.has(w);for(let w=0;w<T.children.length;w++){const M=T.children[w];C(M)?!O&&s[y].children.push(M):x.push(M)}}for(let _=0;_<b.length;_++){const C=b[_];x.push(C),r[y].children.push(C)}a>n&&l()}e.layersAndObjects[u]=x,S.debug("[Dxf] Merged layer '"+u+"' in "+(Date.now()-m)/1e3+"s")}a>0&&l();for(const u in r){const f=r[u];!e.root.children.find(g=>g.name===u)&&e.root.add(f.object),f.children.forEach(g=>{f.object.add(g)}),f.children=[]}S.debug("[Dxf] MergeUtils.deepMerge took "+oe.MergeInfo.elapsedTime/1e3+"s"),S.debug("[Dxf] The remove operation of deep merge took "+o/1e3+"s"),S.debug("[Dxf] Deep merge totally took "+(Date.now()-i)/1e3+"s");const c=oe.MergeInfo;S.debug("[Dxf] Totally merged "+c.removedObjects+" objects to "+c.mergedMeshes+"meshes, "+c.mergedLines+"lines, "+c.mergedPoints+"points, "+(c.mergedUnknownTypeObjects?c.mergedUnknownTypeObjects+" unknown type,":" ")+" ")}static async merge(e,i){const s=z.getUpdateProgressFuncAsync(i),r={};e.objects.LAYOUT.forEach(y=>{const T=y;r[T.layoutName]=T,T.directAssociatedLeafObjectSet?.clear()});const n=Date.now(),a={},o={},l=15e3;let c=0,u=0;const f=()=>{const y=Date.now();for(const T in a){const v=a[T];V.removeEmptyObjectsFromRemovingMarkedObjects(v.children,v.object),v.children=[]}c=0,u+=Date.now()-y},m=Object.keys(e.layersAndThreejsObjects).length;let g=0;for(const y in e.layersAndThreejsObjects){const T=e.layersAndThreejsObjects[y];if(T.length<=1){await s(++g/m*100);continue}const v=Date.now(),b={},E=[];for(const C of T){if(C.userData.isSnapObject){E.push(C);continue}let w,M=C;for(;M;){if(M.userData.isLayoutLevelObject){w=M;break}M=M.parent}if(!w)continue;const P=w.name;!b[P]&&(b[P]={object:w,children:[]}),b[P].children.push(C)}const O=Object.keys(b).length;let _=0;for(const C in b){let w;if(C!==V.MODEL_LAYOUT_NAME){const B=r[C];!B.directAssociatedLeafObjectSet&&(B.directAssociatedLeafObjectSet=new Set),w=B.directAssociatedLeafObjectSet}const M=b[C],P=oe.deepMerge(M.children,M.object,!1,!1,!0),A=P.added,I=P.removed;!a[C]&&(a[C]={object:M.object,children:[]}),!o[C]&&(o[C]={object:M.object,children:[]});const k=I.length>l;if(k){const B=Date.now();V.removeEmptyObjectsFromRemovingMarkedObjects(I,M.object),u+=Date.now()-B}else c+=I.length;if(I.length===M.children.length)!k&&I.forEach(B=>{a[C].children.push(B)});else{let B=I;I.length>=100&&(B=new Set(I));const L=q=>Array.isArray(B)?B.indexOf(q)>=0:B.has(q);for(let q=0;q<M.children.length;q++){const me=M.children[q];L(me)?!k&&a[C].children.push(me):(E.push(me),w&&w.add(me))}}for(let B=0;B<A.length;B++){const L=A[B];$.setSharedVariablesOfObject(L),E.push(L),o[C].children.push(L),w&&w.add(L)}c>l&&f(),await s((g+ ++_/O)/m*100)}await s(++g/m*100),e.layersAndThreejsObjects[y]=E,S.debug("[Dxf] Merged layer '"+y+"' in "+(Date.now()-v)/1e3+"s")}c>0&&f();for(const y in o){const T=o[y],v=e.threejsObject.children.find(b=>b.name===y);if(v){const b=v.children.find(E=>E.name===V.SNAP_GROUP_NAME);if(b&&y!==V.MODEL_LAYOUT_NAME){const E=r[y];!E.directAssociatedLeafObjectSet&&(E.directAssociatedLeafObjectSet=new Set),b.children.forEach(O=>E.directAssociatedLeafObjectSet?.add(O))}}!v&&e.threejsObject.add(T.object),T.children.forEach(b=>{!b.visible&&(b.userData.layerVisible=!1),T.object.add(b),b.updateWorldMatrix(!1,!1)}),T.children=[]}S.debug("[Dxf] MergeUtils.deepMerge took "+oe.MergeInfo.elapsedTime/1e3+"s"),S.debug("[Dxf] The remove operation of deep merge took "+u/1e3+"s"),S.debug("[Dxf] Deep merge totally took "+(Date.now()-n)/1e3+"s");const x=oe.MergeInfo;S.debug("[Dxf] Totally merged "+x.removedObjects+" objects to "+x.mergedMeshes+"meshes, "+x.mergedLines+"lines, "+x.mergedPoints+"points, "+(x.mergedUnknownTypeObjects?x.mergedUnknownTypeObjects+" unknown type,":" ")+" "),s(100)}printStatsInfo(){const e=this.entityTypesAndTimes;for(const r in e)e[r].averageTime=e[r].totalTime/e[r].createCount;S.debug("[Dxf] Entity types and took how much time in ms:",e),S.debug("[Dxf] Entity types and mesh count:",this.statsInfo.entityTypesAndMeshCount);let i=0;if(Object.values(this.statsInfo.entityTypesAndMeshCount).forEach(r=>{i+=r}),this.enableRTC&&S.debug("[Dxf] Totally rebased "+this.statsInfo.rebasedEntityCount+"(out of "+i+") entities"),this.enableMerge){const r=oe.MergeInfo;S.debug("[Dxf] Inner merged "+r.removedObjects+" objects to "+r.mergedMeshes+"meshes, "+r.mergedLines+"lines, "+r.mergedPoints+"points, "+(r.mergedUnknownTypeObjects?r.mergedUnknownTypeObjects+" unknown type,":" ")+"in "+r.elapsedTime/1e3+"s")}const s=(r,n,...a)=>{Object.keys(n).length>0};s("[Dxf] Unsupported entity types and count:",this.statsInfo.unsupportedEntityTypes),s("[Dxf] Unsupported text style names and count:",this.statsInfo.unsupportedTextStyles,". Will use a default style."),s("[Dxf] Unsupported hatch pattern names and count:",this.statsInfo.unsupportedHatchPatterns,". Filling in solid lines instead."),this.statsInfo.unsupportedPolylineCount&&S.warn("[Dxf] Unsupported polyline (with both width and linetype) count: "+this.statsInfo.unsupportedPolylineCount+", linetype will be ignored."),s("[Dxf] Ignored invisible entity types and count:",this.statsInfo.invisibleEntities),s("[Dxf] Ignored frozen layers and entity count:",this.statsInfo.ignoredFrozenLayersAndEntityCount),s("[Dxf] Ignored inserts and count (may because they don't contain anything):",this.statsInfo.ignoredInserts),this.ignorePaperSpace&&s("[Dxf] Ignored paper space entity count:",this.statsInfo.ignoredPaperSpaceEntityTypesAndCount),this.font&&s("[Dxf] Unsupported chars and count:",this.font.getUnsupportedChar())}static statLayoutAndLayerObjects(e){const i=new WeakSet;let s=0;for(const a in e.layersAndThreejsObjects)e.layersAndThreejsObjects[a].forEach(l=>{l.geometry&&(s++,i.has(l)?console.warn(l):i.add(l))});const r=new WeakSet;let n=0;if(e.threejsObject.traverse(a=>{a.geometry&&(n++,r.has(a)?console.warn(a):r.add(a))}),s!=n)for(const a in e.layersAndThreejsObjects)e.layersAndThreejsObjects[a].forEach(l=>{l.geometry&&!r.has(l)&&console.warn(l)});S.info("[Dxf] The count of layer objects is "+s+",The count of layout objects is "+n+" ")}static removeEmptyObjectsFromRemovingMarkedObjects(e,i){if(e.length===0)return;const s=r=>{const n=[];for(const a of r){a.userData.validCount=0;const o=a.parent;o&&o!==i&&(o.userData.validCount===void 0&&(o.userData.validCount=o.children.length),--o.userData.validCount===0&&n.push(o))}n.length>0&&s(n)};s(e),this.removeEmptyObjectsFromMark(i)}static removeEmptyObjectsFromMark(e){if(e.userData.validCount===0||$.isEmptyObject(e))return e.removeFromParent(),!0;for(let i=0;i<e.children.length;)!this.removeEmptyObjectsFromMark(e.children[i])&&++i;return!1}static removeEmptyObjectsFromRemovingMarkedObjects2(e,i){if(e.length===0)return;const s=r=>{const n=[];for(const a of r){a.userData.validCount=0;const o=a.parent;o&&o!==i&&(o.userData.validCount===void 0&&(o.userData.validCount=o.children.length),--o.userData.validCount===0&&n.push(o))}n.length>0&&s(n)};s(e),this.removeEmptyObjectsFromMark2(i)}static removeEmptyObjectsFromMark2(e){if(e.userData.validCount===0||e.type===H.Object&&e.children.length===0)return e.removeFromParent(),!0;for(let i=0;i<e.children.length;)!this.removeEmptyObjectsFromMark2(e.children[i])&&++i;return!1}};p(V,"MODEL_LAYOUT_NAME","Model"),p(V,"SNAP_GROUP_NAME","InvisibleObjectGroupForOSnap"),p(V,"SHOW_SNAP_OBJECT",!1),p(V,"REQUWSTHEADER"),p(V,"CameraZoomUniform",{value:1}),p(V,"ViewportScaleUniform",{value:1}),p(V,"TransformMatrixUniform",{value:new d.Matrix4}),p(V,"ResolutionUniform",{value:new d.Vector2}),p(V,"LOADLLDATA",!1),p(V,"MaxFragmentUniforms",1024);let Y=V;class As extends mt{constructor(e){super();p(this,"viewer");p(this,"overlayRender");p(this,"drawableList");this.drawableList=new bi("compare"),this.viewer=e,this.overlayRender=this.viewer.getOverlayRender(),this.overlayRender?.addDrawableList(this.drawableList)}drawCompareDrawable(e){const i=[],s=[],r=[];for(const l of Object.values(e)){const c=l.box;c&&(l.type===Te.Added?i.push(c):l.type===Te.Removed?s.push(c):r.push(c))}const n=U.mergeBBoxes(i),a=U.mergeBBoxes(s),o=U.mergeBBoxes(r);this.drawableList.addDrawable(new Je(z.guid(),n,[.1,.9,.2,1])),this.drawableList.addDrawable(new Je(z.guid(),a,[1,.15,.15,1])),this.drawableList.addDrawable(new Je(z.guid(),o,[1,.85,.1,1])),this.viewer.enableRender()}setCompareDrawableVisible(e){this.drawableList.getDrawables().forEach(i=>i.visible=e),this.viewer.enableRender()}}class Ji{}const Pt=new d.Matrix4,fs=new d.Box3;class Wt extends Ji{constructor(e){super();p(this,"modelId");p(this,"modelData");p(this,"modelObject");p(this,"bbox");this.modelData=e,this.modelId=e.modelId,this.modelObject=e.dxfData?.threejsObject||e.pdfData?.threejsObject,this.modelObject.name=this.modelId,this.modelObject.userData.modelId=this.modelId}get pdfData(){return this.modelData.pdfData}get dxfData(){return this.modelData.dxfData}get msTransformMatrix(){return this.modelData.msTransformMatrix}set msTransformMatrix(e){this.modelData.msTransformMatrix=e}get loadedEntityCount(){return this.dxfData?.loadedEntityCount||this.pdfData?.loadedEntityCount||0}get header(){return this.dxfData?.header}get viewports(){return this.dxfData?.tables.viewport.viewports}get layers(){const e=this.dxfData||this.pdfData;return e.tables?.layer.layers||e.layers}get layoutViewportsMap(){return this.dxfData?.layoutViewportsMap}getModelObject(){const e=this.dxfData||this.pdfData;if(!e)throw new Error("Failed to find model by modelId '"+this.modelId+"'!");return e.threejsObject}getBBox(){if(!this.bbox){const e=new d.Box3,i=this.getModelObject();e.setFromObject(i),this.bbox=e}return this.bbox}getUnits(){if(!this.dxfData)return De.Unitless;const e=this.dxfData.header;if(!e)return S.warn("DxfData or its header is undefined!"),De.Unitless;const i=e.$INSUNITS;return Y.getDxfUnits(i)}getModelSpaceExtent(){const e=this.header,i=new d.Vector3,s=new d.Vector3;if(!e){S.error("Header is undefined in "+this.modelId+"!");return}const r=this.viewports;let n=e.$EXTMIN,a=e.$EXTMAX;const o=e.$ANGDIR;if(r&&r.length>0)for(let l=0;l<r.length;l++){const c=r[l];if(c.name.toLocaleUpperCase()==="*ACTIVE"){const{center:u,viewHeight:f,aspectRatio:m}=c,g=f*m,x=Y.getDcs2WcsMatrix(c,o),y=new d.Vector3(u.x,u.y,0);y.applyMatrix4(x),n={x:y.x-g/2,y:y.y-f/2,z:0},a={x:y.x+g/2,y:y.y+f/2,z:0};break}}return i.set(n.x,n.y,n.z),s.set(a.x,a.y,a.z),new d.Box3(i,s)}getLayer(e){if(this.layers)return this.layers[e]}getObjectsByLayer(e){const i=this.dxfData||this.pdfData;return i?.layersAndThreejsObjects&&i.layersAndThreejsObjects[e]}getLayouts(){const e=[];return this.dxfData?.objects.LAYOUT?.forEach(r=>{e.push(r)}),e}getLayoutByName(e){let i;const s=this.getLayouts();for(const r of s)if(r.layoutName===e){i=r;break}return i}getLayoutExtent(e){const i=this.header,s=new d.Vector3,r=new d.Vector3;if(!i)throw new Error("Header is undefined in "+this.modelId+"!");const n=this.getLayoutViewports(e);let a=i.$PEXTMIN,o=i.$PEXTMAX;const l=i.$ANGDIR;if(n&&n.length>0){const c=n.filter(T=>parseInt(T.viewportId)===1);let u;c.length>0?u=c[0]:u=n[0];const{centerPoint:f,width_paperSpace:m,height_paperSpace:g}=u,x=Y.getDcs2WcsMatrix(u,l),y=new d.Vector3(f.x,f.y,0);y.applyMatrix4(x),a={x:y.x-m/2,y:y.y-g/2,z:0},o={x:y.x+m/2,y:y.y+g/2,z:0}}return s.set(a.x,a.y,a.z),r.set(o.x,o.y,o.z),new d.Box3(s,r)}getLayoutViewports(e){const s=this.layoutViewportsMap[e.ownerHandle];return s||[]}getLayoutLevelObject(e){return this.getModelObject()?.children.find(s=>s.name===e)}setVisible(e){const i=this.getModelObject();i.visible=e}setLayerVisible(e,i,s,r){const n=this.getLayer(e);n?n.visible=i:S.warn("[Viewer] Layer '"+e+"' not found from modelData!");const a=this.getObjectsByLayer(e);if(a)for(let o=0;o<a.length;o++){const l=a[o];!(s&&i&&r&&l.userData.visibleMinZoom&&r<l.userData.visibleMinZoom)&&(l.visible=i),(i===!1||l.userData.layerVisible!=null)&&(l.userData.layerVisible=i),l.userData.isSnapObject&&(l.visible?Y.SHOW_SNAP_OBJECT?l.layers.enableAll():l.layers.set(Ce):Y.SHOW_SNAP_OBJECT?l.layers.disableAll():l.layers.disable(Ce))}else S.info("[Viewer] No object found for layer '"+e+"'")}setLayerOpacity(e,i){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const r=this.getObjectsByLayer(e);r?r.forEach(n=>{const a=n;if(a.material){!a.userData.originalMaterial&&(a.userData.originalMaterial=de.cloneMaterial(a.material));const o=de.cloneMaterial(a.material);de.setMaterialOpacity(o,i),Y.updateMaterialUniforms(o),a.material=o}}):S.info("[Viewer] No object found for layer '"+e+"'")}setLayerColor(e,i){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const r=this.getObjectsByLayer(e);r?r.forEach(n=>{const a=n;if(a.material){!a.userData.originalMaterial&&(a.userData.originalMaterial=de.cloneMaterial(a.material));const o=de.cloneMaterial(a.material);de.setMaterialColor(o,new d.Color(i)),Y.updateMaterialUniforms(o),a.material=o}}):S.info("[Viewer] No object found for layer '"+e+"'")}resetLayerColor(e){if(!this.getLayer(e))throw new Error("Failed to find layer by layerName '"+e+"'!");const s=this.getObjectsByLayer(e);s?s.forEach(r=>{const n=r;n.material&&n.userData.originalMaterial&&(n.material.dispose(),n.material=n.userData.originalMaterial,delete n.userData.originalMaterial)}):S.info("[Viewer] No object found for layer '"+e+"'")}switchTransformMs(e){const i=this.msTransformMatrix;if(Pt.identity(),!i||!z.isMatrixValid(i)||i.equals(Pt))return;const s=this.getLayoutLevelObject(Y.MODEL_LAYOUT_NAME);s&&(e===Y.MODEL_LAYOUT_NAME?s.applyMatrix4(i):s.applyMatrix4(i.clone().invert()),s.updateMatrixWorld(!0))}activateLayout(e=Y.MODEL_LAYOUT_NAME,i){this.switchTransformMs(e);const s=this.getLayoutByName(e);if(s){if(!i){const r=this.getLayoutViewports(s);let n=[];r.length>0&&(n=r[0].frozenLayerHandles);const a=e!==Y.MODEL_LAYOUT_NAME,o=this.getLayoutLevelObject(e);if(o){const u=[];o.traverse(f=>{this.addSpatialFilterSection(f,this.dxfData);const m=f;if(a&&m.material&&m.geometry){const g=m.userData.layerName;if(this.isLayerFrozenForViewport(g,n))return;u.push(m);let x=-1;const y=this.getObjectsByLayer(g);y&&(x=y.indexOf(m),x>=0&&y.splice(x,1)),x<0&&S.warn("[Viewer] Failed to find object for modelId '"+this.modelId+"', layer '"+g+"', layout '"+e+"'")}}),u.forEach(f=>{f.removeFromParent()})}const l=this.getFilteredViewports(s);S.debug("[Viewer] Active layout:",e,", viewports:",l);const c=Date.now();l.forEach(u=>{this.generateObjectsByViewport(e,u,this)}),S.info("[Viewer] generateObjectsByViewport in "+(Date.now()-c)/1e3+"s")}this.showLayoutObjects(e)}}getFilteredViewports(e){const i=this.getLayoutViewports(e);let s=i.filter(r=>r.viewportId!=="1");return s.length===i.length&&(s=i.filter((r,n)=>n!==0)),s}generateObjectsByViewport(e,i,s,r=[]){const n=i;if(i.viewportId=="1")return;if(!n.psBBox||!n.msToPsMatrix)throw new Error("The bbox or matrix is invalid in the viewport!");Y.TransformMatrixUniform={value:n.msToPsMatrix},Y.ViewportScaleUniform={value:i.viewHeight/i.height_paperSpace};const a=n.psBBox.clone();a.applyMatrix4(n.msToPsMatrix.clone().invert()),a.min.setZ(-1),a.max.setZ(1);const o=this.getObjectsByBoundingBox(a);if(o.length===0)return;const l=n.psBBox.min,c=n.psBBox.max,u=new d.Box2(new d.Vector2(l.x,l.y),new d.Vector2(c.x,c.y)),f=dt.generateSectionPlanesByBox(u),m=[],g=M=>(!m[M.id]&&(m[M.id]=M.clone(),this.setMaterialUniforms(m[M.id],s.dxfData),dt.setMaterialSection(m[M.id],f)),m[M.id]),x=M=>{if(Array.isArray(M)){const P=[];return M.forEach(A=>{const I=g(A);P.push(I)}),P}else return g(M)},y=[...r,...i.frozenLayerHandles||[]];let T;if(e!==Y.MODEL_LAYOUT_NAME){const M=n;!M.associatedLeafObjectSet&&(M.associatedLeafObjectSet=new Set),T=M.associatedLeafObjectSet}const v=new d.Group;v.name=n.viewportId;const b=[];if(o.forEach(M=>{const P=M.clone();P.traverse(A=>{const I=A;if(I.material&&I.geometry){const k=I.userData.layerName;if(this.isLayerFrozenForViewport(k,y)){b.push(I);return}I.userData.layerVisible!==!1&&(I.visible=!0),I.material=x(I.material),T?.add(I);const B=s.getObjectsByLayer(k);B?B.push(I):S.warn("[Viewer] Failed to find object for modelId '"+this.modelId+"', layer '"+k+"', layout '"+e+"'")}}),v.add(P)}),T&&T.size===0)return;const E=s.getModelObject();let O=s.getLayoutLevelObject(e);!O&&(O=new d.Group,$.setSharedVariablesOfObject(O),O.name=e,E?.add(O)),O.add(v),v.applyMatrix4(n.msToPsMatrix),v.updateMatrixWorld(!0);let _=O.children.find(M=>M.name===Y.SNAP_GROUP_NAME);!_&&(_=new d.Group,_.visible=Y.SHOW_SNAP_OBJECT,_.name=Y.SNAP_GROUP_NAME,O.add(_));const C=s.getLayoutLevelObject(Y.MODEL_LAYOUT_NAME),w=C?.children.find(M=>M.name===Y.SNAP_GROUP_NAME);w&&w.traverse(M=>{if(!M.geometry)return;const P=M.userData.layerName;if(this.isLayerFrozenForViewport(P,y)||(fs.makeEmpty(),fs.expandByObject(M),!a.intersectsBox(fs)))return;const A=M.clone();$.setSharedVariablesOfObject(A);let I=A.parent;const k=Pt.identity();for(;I&&I.userData.isLayoutLevelObject!==!0;)k.premultiply(I.matrix),I=I.parent;k.premultiply(n.msToPsMatrix),A.applyMatrix4(k),_?.add(A),T?.add(A);const B=s.getObjectsByLayer(P);B&&B.push(A)}),b.length>0&&$.removeEmptyObjectsFromRemovingObjects(b,v),v.traverse(M=>{$.setSharedVariablesOfObject(M),this.addSpatialFilterSection(M,s.dxfData,!0)})}setMaterialUniforms(e,i){e instanceof d.ShaderMaterial&&(e.uniforms.u_cameraZoom&&(e.uniforms.u_cameraZoom=Y.CameraZoomUniform),e.uniforms.u_viewportScale&&i?.header.$PSLTSCALE===1&&(e.uniforms.u_viewportScale=Y.ViewportScaleUniform))}getObjectsByBoundingBox(e){const i=[];if(e.isEmpty())return S.warn("[Viewer] bbox is empty !"),i;const s=n=>{const a=rt.getBoundingBox(n,!1);e.intersectsBox(a)&&i.push(n)},r=this.getLayoutLevelObject(Y.MODEL_LAYOUT_NAME);return r&&r.children.forEach(n=>{n.name!==Y.SNAP_GROUP_NAME&&s(n)}),i}showLayoutObjects(e){let i=0,s=0;const r=this.getModelObject();r.children.forEach(n=>{const a=n.name===e;n.visible=a,a?i++:s++}),S.debug("[Viewer] showLayoutObjects('"+e+"') sets "+i+" layout level object(s) to visible and "+s+" to hidden for model '"+r?.name+"'")}isLayerFrozenForViewport(e,i){const s=this.getLayer(e);return s&&(s.flag&1)>0?!0:!i||i.length<=0?!1:s&&i.indexOf(s.handle)>=0}addSpatialFilterSection(e,i,s=!1){if(e.userData.entityType!=="INSERT"||!e.userData.spatialFilterHandle)return;const r=this.findSpatialFilter(e.userData.spatialFilterHandle,i);if(r){let n=s,a=!1;const o=this.getAnyMaterial(e);if(o&&(o.clippingPlanes&&(n=o.clippingPlanes.length>0),a=o.clipIntersection),n&&a!==r.clipPolylines[0].bReversed){S.warn("[Viewer] Material cannot set clipIntersection to different values at the same time. clipIntersection needs to be set to true here!");return}a=r.clipPolylines[0].bReversed;const l=this.generateSectionsBySpatialFilter(r,e.matrixWorld);if(l){const c=m=>{let g=0;return m.clippingPlanes&&(g=m.clippingPlanes.length),g+l.length>Y.MaxFragmentUniforms},u=new Set,f=m=>{u.has(m.id)||(u.add(m.id),!c(m)&&dt.setMaterialSection(m,l,n,a))};e.traverse(m=>{const g=m.material;Array.isArray(g)?g.forEach(x=>{f(x)}):g&&f(g)})}}}findSpatialFilter(e,i){const s=i.objects.SPATIAL_FILTER;if(!s)return;let r;for(const n of s)if(n.handle===e){r=n;break}return r}getAnyMaterial(e){const i=e;if(i.material)return Array.isArray(i.material)?i.material[0]:i.material;let s;for(let r=0;r<e.children.length&&(s=this.getAnyMaterial(e.children[r]),!s);r++);return s}generateSectionsBySpatialFilter(e,i){const s=e.clipPolylines[0];if(s.bConcave){S.warn("[Viewer] clipPolyline.bConcave = true is not supported yet in spatialFilter !");return}Pt.copy(i),e.localMatrix&&Pt.multiply(e.localMatrix);const r=s.polyline,n=[];r.forEach(l=>{const c=l.clone().applyMatrix4(Pt);n.push(new d.Vector2(c.x,c.y))});const a=d.ShapeUtils.isClockWise(n),o=!a&&!s.bReversed||a&&s.bReversed;return dt.generateSectionPlanesByPoints(n,o)}hasObject(e){return!!this.modelObject.getObjectById(e.id)}hasObjectWithId(e){return!!this.modelObject.getObjectById(e)}highlightObject(e){if(!this.hasObject(e))return;const i=de.clonedHighlightMaterials(e,{depthTest:!1});i&&(e.userData.originalMaterial=e.material,e.material=i)}unHighlightObject(e){if(!this.hasObject(e))return;const i=e.material;e.material=e.userData.originalMaterial,delete e.userData.originalMaterial,Array.isArray(i)?i.forEach(s=>s.dispose()):i instanceof d.Material&&i.dispose()}clearHighlight(){}}class zs extends Ji{constructor(e){super();p(this,"modelId");p(this,"bbox");p(this,"rootObject");p(this,"modelObject");p(this,"highlighUsage");p(this,"transparentUsage");p(this,"edges");p(this,"highlighedObject");this.modelId=e.modelId,this.bbox=e.bbox,this.modelObject=e.object,this.rootObject=new d.Group,this.rootObject.name="rootObject-"+this.modelId,this.rootObject.userData.modelId=this.modelId,this.highlighUsage=new d.Group,this.highlighUsage.name="highlighUsage-"+this.modelId,this.highlighUsage.layers.disable(ft),this.transparentUsage=new d.Group,this.transparentUsage.name="transparentUsage-"+this.modelId,this.transparentUsage.layers.disable(ft),this.rootObject.add(this.modelObject),this.rootObject.add(this.highlighUsage),this.rootObject.add(this.transparentUsage)}setDoubleSidedMaterials(){this.getModelObject().traverse(e=>{e instanceof d.Mesh&&$.setDoubleSidedMaterialToObject(e)})}revertDoubleSidedMaterials(){this.getModelObject().traverse(e=>{e instanceof d.Mesh&&$.revertDoubleSidedMaterialToObject(e)})}getModelObject(){return this.rootObject}getBBox(){return!this.bbox&&(this.bbox=new d.Box3,this.bbox.setFromObject(this.getModelObject())),this.bbox}async enableOutline(e,i){e&&!this.edges&&(this.edges=await $.createOutlines(this.getModelObject(),void 0,i)),this.edges&&this.edges.forEach(s=>s.visible=e)}setObjectColor(e,i){this.hasObject(e)&&e.material.color.set(i)}setObjectOpacity(e,i=.5,s,r){if(this.hasObject(e)){if(e instanceof d.InstancedMesh&&r){const n=this.createInstanceMeshById(e,r,{opacity:i});n.material.opacity*=i,e.userData.instanceId=r,e.userData.transparentedMesh=n,this.transparentUsage.add(n)}else if(oe.isMergedMesh(e)&&s){const n=this.createBatchMeshById(e,s,{opacity:i});n.material.opacity*=i,e.userData.batchId=s,e.userData.transparentedMesh=n,this.transparentUsage.add(n)}else{const n=new d.MeshBasicMaterial({color:0,transparent:!0,opacity:.05});n&&(e.userData.originalMaterial=e.material,e.material=n)}e.userData.isTransparent=!0}}clearObjectOpacity(e,i,s){if(!this.isObjectTransparent(e))return;const{transparentedMesh:r,originalMaterial:n}=e.userData;r&&(this.transparentUsage.remove(r),delete e.userData.batchId,delete e.userData.instanceId,delete e.userData.transparentedMesh),n&&(e.material=n),delete e.userData.isTransparent}isObjectTransparent(e){const{isTransparent:i}=e.userData;return!!i}setOpacity(e=.5){this.getModelObject().traverse(i=>{i instanceof d.Mesh&&this.setObjectOpacity(i,e)})}clearOpacity(){this.getModelObject().traverse(e=>{e instanceof d.Mesh&&this.clearObjectOpacity(e)})}highlightObjectById(e,i,s){if(!this.hasObjectWithId(e))return;const r=this.getModelObject().getObjectById(e);r&&this.highlightObject(r,i,s)}highlightObject(e,i,s){if(!this.hasObject(e))return;const r=new d.Color(Bs);if(e instanceof d.InstancedMesh&&s){const n=this.createInstanceMeshById(e,s,{depthTest:!1});n.material.opacity=.7,de.setMaterialColor(n.material,r),e.userData.instanceId=s,e.userData.clonedMesh=n,this.highlighUsage.add(n)}else if(oe.isMergedMesh(e)&&i){const n=this.createBatchMeshById(e,i,{depthTest:!1});n.material.opacity=.7,de.setMaterialColor(n.material,r),e.userData.batchId=i,e.userData.clonedMesh=n,this.highlighUsage.add(n)}else{const n=de.clonedHighlightMaterials(e,{depthTest:!1});n&&(e.userData.originalMaterial=e.material,e.material=n)}e.userData.isHighlight=!0,this.highlighedObject=e}clearHighlight(){if(this.highlighedObject&&this.highlighedObject.userData){const e=this.highlighedObject.userData,{clonedMesh:i,originalMaterial:s,instanceId:r,originalMatrix:n}=e;i&&(i.removeFromParent(),i.geometry.dispose(),delete e.clonedMesh),r&&n&&(this.highlighedObject.setMatrixAt(r,n),delete e.instanceId,delete e.originalMatrix),s&&(this.highlighedObject.material=s,delete e.originalMaterial),delete e.isHighlight}this.highlighUsage.clear(),this.highlighedObject=void 0}setObjectVisible(e,i){this.hasObject(e)&&(e.visible=i)}setVisible(e){this.getModelObject().traverse(i=>{i instanceof d.Mesh&&(i.visible=e)})}hasVisibleObject(){let e=0;return this.modelObject.traverseVisible(i=>{i instanceof d.Mesh&&e++}),e>0}hasInvisibleObject(){let e=0;return this.modelObject.traverse(i=>{i instanceof d.Mesh&&e++}),this.modelObject.traverseVisible(i=>{i instanceof d.Mesh&&e--}),e>0}createBatchMeshById(e,i,{opacity:s=1,depthTest:r=!0}){const n=oe.getBatchByBatchId(e,i);let a="[Viewer] Clicked on merged mesh(id: "+e.id+").";a+=" batchId: "+i+", object name: "+n?.name,n?.userData&&(a+=`
|
|
797
797
|
userData: `+JSON.stringify(n.userData)),n?.parentUserData&&(a+=`
|
|
798
798
|
parentUserData: `+JSON.stringify(n.parentUserData)),S.info(a);const o=de.cloneMaterial(e.material);o.opacity=s,o.transparent=s<1,!r&&(o.depthTest=r,o.depthWrite=r,o.side=d.DoubleSide);const l=oe.cloneGeometryForBatch(e,n),c=new d.Mesh(l,o);return c.applyMatrix4(e.matrixWorld),c.matrixWorldNeedsUpdate=!0,c.name="Cloned mesh for highlighting",c.layers.enableAll(),c}createInstanceMeshById(e,i,{opacity:s=1,depthTest:r=!0}){const n=e,a=new d.Matrix4,o=new d.Matrix4;o.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0),n.getMatrixAt(i,a);const l=de.cloneMaterial(n.material);l.opacity=s,l.transparent=s<1,!r&&(l.depthTest=r,l.depthWrite=r,l.side=d.DoubleSide);const c=new d.Mesh(n.geometry.clone(),l);c.applyMatrix4(e.matrixWorld.multiply(a)),c.matrixWorldNeedsUpdate=!0,c.name="Cloned mesh for highlighting",c.layers.enableAll();const u=a.clone();return u.multiplyMatrices(a,o),n.setMatrixAt(i,u),n.instanceMatrix.needsUpdate=!0,n.updateMatrix(),e.userData.originalMatrix=a,c}setClipPlanes(e){this.getModelObject().traverse(i=>{const s=i.material;s&&(Array.isArray(s)?s.forEach(r=>{r.clippingPlanes=e,r.clipIntersection=!1}):(s.clippingPlanes=e,s.clipIntersection=!1))})}getObjectTree(){}hasObject(e){return!!this.modelObject.getObjectById(e.id)}hasObjectWithId(e){return!!this.modelObject.getObjectById(e)}}class Dr extends d.MeshStandardMaterial{constructor(e){super(e);p(this,"isBimTilesMaterial");p(this,"type");p(this,"uniforms");p(this,"vertexShader");p(this,"fragmentShader");p(this,"stateTexture");p(this,"defaultOutlineColor");p(this,"useBCOutline");p(this,"outlineVisible");this.isBimTilesMaterial=!0,this.type="BimTilesMaterial",this.defaultOutlineColor=new d.Color(Vi[0],Vi[1],Vi[2]),this.useBCOutline=!1,this.outlineVisible=!0;const i=e.stateTexture;this.stateTexture=i;const{uniforms:s,fragmentShader:r,vertexShader:n}=d.ShaderLib.standard;this.uniforms=d.UniformsUtils.merge([s,{uTextureWidth:{value:i.image.width},uTextureHeight:{value:i.image.height},outlineColor:{value:this.defaultOutlineColor}}]),this.uniforms.uStateTexture={value:i},this.vertexShader=n.replace("#include <common>",`
|
|
799
799
|
#include <common>
|