@maqiuyao/dxf-viewer 0.2.18 → 0.2.20

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.
@@ -788,7 +788,7 @@ void main() {
788
788
  gl_FragColor = vec4(u_color * total, 1.0);
789
789
  #include <colorspace_fragment>
790
790
  }
791
- `;return new p.ShaderMaterial({uniforms:n,vertexShader:r,fragmentShader:a,clipping:!0})}var Ke=(c=>(c.Unitless="Unitless",c.Inches="Inches",c.Feet="Feet",c.Millimeters="Millimeters",c.Centimeters="Centimeters",c.Meters="Meters",c))(Ke||{});const wr=c=>c==="Unitless"?1:c==="Inches"?.0254:c==="Feet"?.3048:c==="Millimeters"?.001:c==="Centimeters"?.01:(c==="Meters"||console.warn("[Units] Unsupported unit '"+c+"', will return 1 for unit scale."),1),md=(c,t)=>wr(c)/wr(t);class Uo{constructor(){g(this,"pointer");g(this,"eof");g(this,"lastReadGroup");this.pointer=0,this.eof=!1}}class vs{constructor(t,e){g(this,"endian");g(this,"position");g(this,"data");g(this,"decoder");this.endian=e&&e==="big"?"big":"little",this.position=0,this.data=new DataView(t)}readAsciiString(t){if(this.data.byteLength<this.position+t)throw"range error";let e="";for(let i=0;i<t;i++)e+=String.fromCharCode(this.data.getInt8(this.position+i));return this.position+=t,e}readUtf8String(t){const e=this.readBytes(t);return this.decoder||(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}readBytes(t=1){if(this.data.byteLength<this.position+t)throw"range error";const e=new Uint8Array(t);for(let i=0;i<t;i++)e[i]=this.data.getUint8(this.position+i);return this.position+=t,e}readUint8(){if(this.data.byteLength<this.position+1)throw"range error";const t=this.data.getUint8(this.position);return this.position+=1,t}readInt8(){if(this.data.byteLength<this.position+1)throw"range error";const t=this.data.getInt8(this.position);return this.position+=1,t}readUint16(){if(this.data.byteLength<this.position+2)throw"range error";const t=this.data.getUint16(this.position,this.endian==="little");return this.position+=2,t}readInt16(){if(this.data.byteLength<this.position+2)throw"range error";const t=this.data.getInt16(this.position,this.endian==="little");return this.position+=2,t}readUint32(){if(this.data.byteLength<this.position+4)throw"range error";const t=this.data.getUint32(this.position,this.endian==="little");return this.position+=4,t}readInt32(){if(this.data.byteLength<this.position+4)throw"range error";const t=this.data.getInt32(this.position,this.endian==="little");return this.position+=4,t}readFloat32(){if(this.data.byteLength<this.position+4)throw"range error";const t=this.data.getFloat32(this.position,this.endian==="little");return this.position+=4,t}readFloat64(){if(this.data.byteLength<this.position+8)throw"range error";const t=this.data.getFloat64(this.position,this.endian==="little");return this.position+=8,t}readInt64(){if(this.data.byteLength<this.position+8)throw"range error";const t=Ms.DataViewGetBigInt64(this.data,this.position,this.endian==="little");return this.position+=8,Ms.toNumber(t)}readUint64(){if(this.data.byteLength<this.position+8)throw"range error";const t=Ms.DataViewGetBigUint64(this.data,this.position,this.endian==="little");return this.position+=8,Ms.toNumber(t)}getPosition(){return this.position}setPosition(t){if(this.data.byteLength<t)throw"range error";this.position=t}isEnd(){return this.position===this.data.byteLength-1}}const Ma=1e3;class gd extends Uo{constructor(e){super();g(this,"reader");g(this,"decoder");g(this,"int8Array");g(this,"caches");this.int8Array=new Int8Array(Ma),this.caches=new Map,this.reader=new vs(e);const i=this.reader.readBytes(22);let s="";for(let n=0;n<18;n++)s+=String.fromCharCode(i[n]);if(s!=="AutoCAD Binary DXF")throw new Error("Invalid DXF file")}next(){if(!this.hasNext())throw this.eof?new Error("Cannot call 'next' after EOF group has been read"):new Error("Unexpected end of input: EOF group not read before end of file.");const e={code:this.reader.readInt16()};return e.value=this.parseGroupValue(e.code),e.code===0&&e.value==="EOF"&&(this.eof=!0),this.lastReadGroup=e,e}hasNext(){return this.eof?!1:!this.reader.isEnd()}isEOF(){return this.eof}parseGroupValue(e){if(e>=0&&e<=9)return this.readNullTerminatedString();if(e>=10&&e<=59)return this.reader.readFloat64();if(e>=60&&e<=79)return this.reader.readInt16();if(e>=90&&e<=99)return this.reader.readInt32();if(e>=100&&e<=109)return this.readNullTerminatedString();if(e>=110&&e<=149)return this.reader.readFloat64();if(e>=160&&e<=169)return this.reader.readInt64();if(e>=170&&e<=179)return this.reader.readInt16();if(e>=210&&e<=239)return this.reader.readFloat64();if(e>=270&&e<=289)return this.reader.readInt16();if(e>=290&&e<=299)return this.reader.readInt8()>0;if(e>=300&&e<=309)return this.readNullTerminatedString();if(e>=310&&e<=319){const i=this.ReadBinaryData();return Ta(i)}if(e>=320&&e<=369)return this.readNullTerminatedString();if(e>=370&&e<=389)return this.reader.readInt16();if(e>=390&&e<=399)return this.readNullTerminatedString();if(e>=400&&e<=409)return this.reader.readInt16();if(e>=410&&e<=419)return this.readNullTerminatedString();if(e>=420&&e<=429)return this.reader.readInt32();if(e>=430&&e<=439)return this.readNullTerminatedString();if(e>=440&&e<=449)return this.reader.readInt32();if(e>=450&&e<=459)return this.reader.readFloat64();if(e>=460&&e<=469)return this.readNullTerminatedString();if(e>=470&&e<=479)return this.readNullTerminatedString();if(e>=480&&e<=481)return this.readNullTerminatedString();if(e>=999&&e<=999)throw new Error("The comment group 999, is not used in binary DXF files at byte address!");if(e===1004){const i=this.ReadBinaryData();return Ta(i)}if(e>=1e3&&e<=1009)return this.readNullTerminatedString();if(e>=1010&&e<=1059)return this.reader.readFloat64();if(e>=1060&&e<=1070)return this.reader.readInt16();if(e===1071)return this.reader.readInt32();console.warn("[DxfBinReader] Invalid code '"+e+"' at byte address "+this.reader.getPosition())}readNullTerminatedString(){this.decoder||(this.decoder=new TextDecoder("utf-8"));let e=0,i=this.reader.readInt8();for(;i!==0;)this.int8Array[e++]=i,i=this.reader.readInt8();if(e===0)return"";if(e>Ma)return console.warn("[DxfBinReader] Failed to read string! The number of bytes is "+e+" !"),"";const s=this.int8Array.subarray(0,e),n=s.toString();if(this.caches.get(n))return this.caches.get(n);const r=this.decoder?.decode(s);return this.caches.set(n,r),r}ReadBinaryData(){const e=this.reader.readUint8();return this.reader.readBytes(e)}}function Ta(c){return Array.prototype.map.call(c,t=>("00"+t.toString(16)).slice(-2)).join("")}class Ca extends Uo{constructor(e){super();g(this,"data");this.data=e}next(){if(!this.hasNext())throw this.eof?new Error("Cannot call 'next' after EOF group has been read"):new Error("Unexpected end of input: EOF group not read before end of file. Ended on code "+this.data[this.pointer]);const e={code:parseInt(this.data[this.pointer])};return this.pointer++,e.value=yd(e.code,this.data[this.pointer].trim(),this.data[this.pointer]),this.pointer++,e.code===0&&e.value==="EOF"&&(this.eof=!0),this.lastReadGroup=e,e}hasNext(){return!(this.eof||this.pointer>this.data.length-2)}isEOF(){return this.eof}}function yd(c,t,e){return c>=0&&c<=9?e:c>=10&&c<=59?parseFloat(t):c>=60&&c<=99?parseInt(t):c>=100&&c<=109?t:c>=110&&c<=149?parseFloat(t):c>=160&&c<=179?parseInt(t):c>=210&&c<=239?parseFloat(t):c>=270&&c<=289?parseInt(t):c>=290&&c<=299?xd(t):c>=300&&c<=369?t:c>=370&&c<=389?parseInt(t):c>=390&&c<=399?t:c>=400&&c<=409?parseInt(t):c>=410&&c<=419?t:c>=420&&c<=429?parseInt(t):c>=430&&c<=439?t:c>=440&&c<=449?parseInt(t):c>=450&&c<=459?parseFloat(t):c>=460&&c<=469||c===999||c>=1e3&&c<=1009?t:c>=1010&&c<=1059?parseFloat(t):c>=1060&&c<=1071?parseInt(t):(console.info("WARNING: Group code does not have a defined type: %j",{code:c,value:t}),t)}function xd(c){if(c==="0")return!1;if(c==="1")return!0;throw TypeError("String '"+c+"' cannot be cast to Boolean type")}function bd(c){if(c==null)return!0;for(const t in c)if(Object.prototype.hasOwnProperty.call(c,t))return!1;return!0}function wd(c,t){const e=[];let i=!1,s=!1;const n=4;for(let r=0;r<=n;r++){const a={};for(;!c.isEOF()&&!(t.code===0||s);){switch(t.code){case 10:case 11:case 12:case 13:if(i){s=!0;continue}a.x=t.value,i=!0;break;case 20:case 21:case 22:case 23:a.y=t.value;break;case 30:case 31:case 32:case 33:a.z=t.value;break;default:return e}t=c.next()}bd(a)||e.push(a),i=!1,s=!1}return e}class vd{constructor(){g(this,"ForEntityName","3DFACE")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 70:if(e.value!==0){const s=Math.log2(e.value)-1;i.vertices.splice(s,0,1)}e=t.next();break;case 10:i.vertices=wd(t,e),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}class Md{constructor(){g(this,"ForEntityName","ARC")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.center=Td(t),e=t.lastReadGroup;break;case 40:i.radius=e.value,e=t.next();break;case 50:i.startAngle=Math.PI/180*e.value,e=t.next();break;case 51:i.endAngle=Math.PI/180*e.value,i.angleLength=i.endAngle-i.startAngle,e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Td(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Cd{constructor(){g(this,"ForEntityName","ATTDEF")}parseEntity(t,e){const i={type:e.value,xScale:1,textStyle:"STANDARD"};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 1:i.text=e.value,e=t.next();break;case 2:i.tag=e.value,e=t.next();break;case 3:i.prompt=e.value,e=t.next();break;case 7:i.textStyle=e.value,e=t.next();break;case 10:i.startPoint=Sa(t),e=t.lastReadGroup;break;case 11:i.endPoint=Sa(t),e=t.lastReadGroup;break;case 39:i.thickness=e.value,e=t.next();break;case 40:i.textHeight=e.value,e=t.next();break;case 41:i.xScale=e.value,e=t.next();break;case 50:i.rotation=e.value,e=t.next();break;case 51:i.obliqueAngle=e.value,e=t.next();break;case 70:i.invisible=!!(e.value&1),i.constant=!!(e.value&2),i.verificationRequired=!!(e.value&4),i.preset=!!(e.value&8),e=t.next();break;case 71:i.backwards=!!(e.value&2),i.mirrored=!!(e.value&4),e=t.next();break;case 72:i.horizontalJustification=e.value,i.halign=e.value,e=t.next();break;case 73:i.fieldLength=e.value,e=t.next();break;case 74:i.verticalJustification=e.value,i.valign=e.value,e=t.next();break;case 100:e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Sa(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Sd{constructor(){g(this,"ForEntityName","ATTRIB")}parseEntity(t,e){const i={type:e.value,xScale:1,textStyle:"STANDARD"};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 1:i.text=e.value,e=t.next();break;case 2:i.tag=e.value,e=t.next();break;case 3:i.prompt=e.value,e=t.next();break;case 7:i.textStyle=e.value,e=t.next();break;case 10:i.startPoint=Ea(t),e=t.lastReadGroup;break;case 11:i.endPoint=Ea(t),e=t.lastReadGroup;break;case 39:i.thickness=e.value,e=t.next();break;case 40:i.textHeight=e.value,e=t.next();break;case 41:i.xScale=e.value,e=t.next();break;case 50:i.rotation=e.value,e=t.next();break;case 51:i.obliqueAngle=e.value,e=t.next();break;case 70:i.invisible=!!(e.value&1),i.constant=!!(e.value&2),i.verificationRequired=!!(e.value&4),i.preset=!!(e.value&8),e=t.next();break;case 71:i.backwards=!!(e.value&2),i.mirrored=!!(e.value&4),e=t.next();break;case 72:i.horizontalJustification=e.value,i.halign=e.value,e=t.next();break;case 73:i.fieldLength=e.value,e=t.next();break;case 74:i.verticalJustification=e.value,i.valign=e.value,e=t.next();break;case 100:e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Ea(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Ed{constructor(){g(this,"ForEntityName","CIRCLE")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.center=Od(t),e=t.lastReadGroup;break;case 40:i.radius=e.value,e=t.next();break;case 50:i.startAngle=Math.PI/180*e.value,e=t.next();break;case 51:const s=Math.PI/180*e.value;s<i.startAngle?i.angleLength=s+2*Math.PI-i.startAngle:i.angleLength=s-i.startAngle,i.endAngle=s,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Od(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class _d{constructor(){g(this,"ForEntityName","DIMENSION")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 2:i.block=e.value,e=t.next();break;case 3:i.dimStyleName=e.value,e=t.next();break;case 10:i.anchorPoint=Jt(t),e=t.lastReadGroup;break;case 11:i.middleOfText=Jt(t),e=t.lastReadGroup;break;case 12:i.insertionPoint=Jt(t),e=t.lastReadGroup;break;case 13:i.linearOrAngularPoint1=Jt(t),e=t.lastReadGroup;break;case 14:i.linearOrAngularPoint2=Jt(t),e=t.lastReadGroup;break;case 15:i.diameterOrRadiusPoint=Jt(t),e=t.lastReadGroup;break;case 16:i.arcPoint=Jt(t),e=t.lastReadGroup;break;case 70:i.dimensionType=e.value,e=t.next();break;case 71:i.attachmentPoint=e.value,e=t.next();break;case 42:i.actualMeasurement=e.value,e=t.next();break;case 1:i.text=e.value,e=t.next();break;case 50:i.angle=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Jt(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Pd{constructor(){g(this,"ForEntityName","MULTILEADER")}parseEntity(t,e){const i={type:e.value};i.contextData={leaders:[]},e=t.next();const s=()=>{const o=i.contextData.leaders[i.contextData.leaders.length-1],l={vertices:[[]]};for(o.leaderLines.push(l);!t.isEOF();)switch(e.code){case 10:l.vertices[0].push(He(t)),e=t.lastReadGroup;break;case 305:return;default:e=t.next();break}},n=()=>{const o={leaderLines:[]};for(i.contextData.leaders.push(o);!t.isEOF();)switch(e.code){case 290:o.hasSetLastLeaderLinePoint=e.value,e=t.next();break;case 291:o.hasSetDoglegVector=e.value,e=t.next();break;case 10:o.lastLeaderLinePoint=He(t),e=t.lastReadGroup;break;case 11:o.doglegVector=He(t),e=t.lastReadGroup;break;case 90:o.leaderBranchIndex=e.value,e=t.next();break;case 40:o.doglegLength=e.value,e=t.next();break;case 303:return;case 304:s(),e=t.lastReadGroup;break;default:e=t.next();break}},r=()=>{for(;!t.isEOF();)switch(e.code){case 40:i.contextData.contentScale=e.value,e=t.next();break;case 10:i.contextData.contentBasePosition=He(t),e=t.lastReadGroup;break;case 145:i.contextData.landingGap=e.value,e=t.next();break;case 290:i.contextData.hasMText=e.value,e=t.next();break;case 300:i.contextData.defaultTextContents=e.value,e=t.next();break;case 11:i.contextData.textNormalDirection=He(t),e=t.lastReadGroup;break;case 12:i.contextData.textLocation=He(t),e=t.lastReadGroup;break;case 13:i.contextData.textDirection=He(t),e=t.lastReadGroup;break;case 140:i.contextData.arrowHeadSize=e.value,e=t.next();break;case 41:i.contextData.textHeight=e.value,e=t.next();break;case 42:i.contextData.textRotation=e.value,e=t.next();break;case 43:i.contextData.textWidth=e.value,e=t.next();break;case 44:e=t.next();break;case 45:i.contextData.textLineSpacingFactor=e.value,e=t.next();break;case 90:i.contextData.textColor=e.value,e=t.next();break;case 170:i.contextData.textLineSpacingStyle=e.value,e=t.next();break;case 171:i.contextData.textAttachment=e.value,e=t.next();break;case 172:i.contextData.textFlowDirection=e.value,e=t.next();break;case 141:i.contextData.textBackgroundScaleFactor=e.value,e=t.next();break;case 92:i.contextData.textBackgroundTransparency=e.value,e=t.next();break;case 291:i.contextData.textBackgroundColorOn=e.value,e=t.next();break;case 292:i.contextData.textBackgroundFillOn=e.value,e=t.next();break;case 293:i.contextData.textUseAutoHeight=e.value,e=t.next();break;case 173:i.contextData.textColumnType=e.value,e=t.next();break;case 142:i.contextData.textColumnWidth=e.value,e=t.next();break;case 143:i.contextData.textColumnGutterWidth=e.value,e=t.next();break;case 144:i.contextData.textColumnHeight=e.value,e=t.next();break;case 295:i.contextData.textUseWordBreak=e.value,e=t.next();break;case 296:i.contextData.hasBlock=e.value,e=t.next();break;case 341:i.contextData.blockContentId=e.value,e=t.next();break;case 14:i.contextData.blockContentNormalDirection=He(t),e=t.lastReadGroup;break;case 15:i.contextData.blockContentPosition=He(t),e=t.lastReadGroup;break;case 16:i.contextData.blockContentScale=e.value,e=t.next();break;case 46:i.contextData.blockContentRotation=e.value,e=t.next();break;case 93:i.contextData.blockContentColor=e.value,e=t.next();break;case 47:i.contextData.blockTransformationMatrix=Ad(t,47),e=t.lastReadGroup;break;case 110:i.contextData.planeOriginPoint=He(t),e=t.lastReadGroup;break;case 111:i.contextData.planeXAxisDirection=He(t),e=t.lastReadGroup;break;case 112:i.contextData.planeYAxisDirection=He(t),e=t.lastReadGroup;break;case 297:i.contextData.planeNormalReversed=e.value,e=t.next();break;case 301:return;case 302:n(),e=t.lastReadGroup;break;default:e=t.next();break}};return(()=>{for(;!t.isEOF();)switch(e.code){case 0:return;case 340:i.leaderStyleId=e.value,e=t.next();break;case 170:i.leaderLineType=e.value,e=t.next();break;case 91:i.leaderLineColor=e.value,e=t.next();break;case 341:i.leaderLineTypeId=e.value,e=t.next();break;case 171:i.leaderLineWeight=e.value,e=t.next();break;case 41:i.doglegLength=e.value,e=t.next();break;case 290:i.enableLanding=e.value,e=t.next();break;case 291:i.enableDogLeg=e.value,e=t.next();break;case 342:i.arrowHeadId=e.value,e=t.next();break;case 42:i.arrowHeadSize=e.value,e=t.next();break;case 172:i.contentType=e.value,e=t.next();break;case 173:i.textLeftAttachmentType=e.value,e=t.next();break;case 95:i.textLeftAttachmentType=e.value,e=t.next();break;case 174:i.textAngleType=e.value,e=t.next();break;case 175:i.textAlignmentType=e.value,e=t.next();break;case 343:i.textStyleId=e.value,e=t.next();break;case 92:i.textColor=e.value,e=t.next();break;case 292:i.enableFrameText=e.value,e=t.next();break;case 344:i.blockContentId=e.value,e=t.next();break;case 93:i.blockContentColor=e.value,e=t.next();break;case 10:i.blockContentScale=He(t),e=t.lastReadGroup;break;case 43:i.blockContentRotation=e.value,e=t.next();break;case 176:i.blockContentConnectionType=e.value,e=t.next();break;case 293:i.enableAnotationScale=e.value,e=t.next();break;case 94:i.arrowHeadIndex=e.value,e=t.next();break;case 177:i.blockAttributeIndex=e.value,e=t.next();break;case 44:i.blockAttributeWidth=e.value,e=t.next();break;case 302:i.blockAttributeTextString=e.value,e=t.next();break;case 294:i.textDirectionNegative=e.value,e=t.next();break;case 178:i.textAlignInIPE=e.value,e=t.next();break;case 179:i.textAttachmentPoint=e.value,e=t.next();break;case 271:i.textAttachmentDirectionMText=e.value,e=t.next();break;case 272:i.textAttachmentDirectionBottom=e.value,e=t.next();break;case 273:i.textAttachmentDirectionTop=e.value,e=t.next();break;case 300:r(),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}})(),i}}function He(c){const t={};let e=c.lastReadGroup||c.next();for(;!c.isEOF();){switch(e.code){case 10:case 11:case 12:case 13:case 14:case 15:case 16:case 110:case 111:case 112:t.x=e.value;break;case 20:case 21:case 22:case 23:case 24:case 25:case 26:case 120:case 121:case 122:t.y=e.value;break;case 30:case 31:case 32:case 33:case 34:case 35:case 36:case 130:case 131:case 132:t.z=e.value;break;case 42:t.bulge=e.value;break;default:return t}e=c.next()}return t}function Ad(c,t){const e=[];let i=c.lastReadGroup||c.next();for(;!c.isEOF()&&(i.code>=t&&i.code<t+16);){e.push(i.value);i=c.next()}return e}class Id{constructor(){g(this,"ForEntityName","ELLIPSE")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.center=Gn(t),e=t.lastReadGroup;break;case 11:i.majorAxisEndPoint=Gn(t),e=t.lastReadGroup;break;case 40:i.axisRatio=e.value,e=t.next();break;case 41:i.startAngle=e.value,e=t.next();break;case 42:i.endAngle=e.value,e=t.next();break;case 210:i.extrusionDirection=Gn(t),e=t.lastReadGroup;break;case 2:i.name=e.value,e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Gn(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}var No=(c=>(c[c.Default=0]="Default",c[c.External=1]="External",c[c.Polyline=2]="Polyline",c[c.Derived=4]="Derived",c[c.Textbox=8]="Textbox",c[c.Outermost=16]="Outermost",c[c.MaxFlags=31]="MaxFlags",c))(No||{}),Ci=(c=>(c[c.Polyline=0]="Polyline",c[c.Line=1]="Line",c[c.Arc=2]="Arc",c[c.Ellipse=3]="Ellipse",c[c.Spline=4]="Spline",c))(Ci||{});function Si(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;if(e.code===i)if(t.x=e.value,!c.isEOF()&&c.hasNext())e=c.next();else return t;if(e.code===i+10)if(t.y=e.value,!c.isEOF()&&c.hasNext())e=c.next();else return t;return e.code===i+20&&(t.z=e.value,!c.isEOF()&&c.hasNext()&&(e=c.next())),t}function Bd(c){const t={type:0,points:[],isClosed:!0};let e=c.next();const i=e.value!==0;e=c.next(),t.isClosed=e.value!==0,e=c.next();const s=e.value;e=c.next();for(let r=0;r<s;r++){const a=Si(c);e=c.lastReadGroup,i&&(a.bulge=e.value,e=c.next()),t.points.push(a)}e=c.lastReadGroup,console.assert(e.code===97,"The reference count code 97 was expected.");const n=e.value;e=c.next();for(let r=0;r<n;r++)console.assert(e.code===330,"The reference handle code 330 was expected."),e=c.next();return{edges:[t],pathTypeFlag:-1}}function kd(c,t){const e=[];let i=t.next();for(;e.length<c;){if(i.code!==72){i=t.next();continue}switch(i.value){case 1:{i=t.next();const r={type:1,startPoint:Si(t),endPoint:Si(t)};i=t.lastReadGroup,e.push(r);break}case 2:{i=t.next();const r={type:2,center:Si(t),radius:0,startAngle:0,endAngle:0,bCounterclockwise:!1};i=t.lastReadGroup,r.radius=i.value,i=t.next(),r.startAngle=i.value,i=t.next(),r.endAngle=i.value,i=t.next(),r.bCounterclockwise=i.value!==0,i=t.next(),e.push(r);break}case 3:{i=t.next();const r={type:3,center:Si(t),majorAxisEndPoint:Si(t),minorRatio:0,startAngle:0,endAngle:0,bCounterclockwise:!1};i=t.lastReadGroup,r.minorRatio=i.value,i=t.next(),r.startAngle=i.value,i=t.next(),r.endAngle=i.value,i=t.next(),r.bCounterclockwise=i.value!==0,i=t.next(),e.push(r);break}case 4:{i=t.next();const r={type:4,degreeOfSplineCurve:i.value,bRational:!1,bPeriodic:!1,numKnots:0,numControlPoints:0,knotValues:[],controlPoints:[]};i=t.next(),r.bRational=i.value!==0,i=t.next(),r.bPeriodic=i.value!==0,i=t.next(),r.numKnots=i.value,i=t.next(),r.numControlPoints=i.value,i=t.next();for(let a=0;a<r.numKnots;a++)r.knotValues.push(i.value),i=t.next();for(let a=0;a<r.numControlPoints;a++){const o=i.value;i=t.next();const l=i.value;let h=1;i=t.next(),i.code===42&&(h=i.value,i=t.next()),r.controlPoints.push({x:o,y:l,z:h})}e.push(r);break}default:i=t.next();break}}i=t.lastReadGroup,console.assert(i.code===97,"The reference count code 97 was expected.");const s=i.value;i=t.next();for(let n=0;n<s;n++)console.assert(i.code===330,"The reference handle code 330 was expected."),i=t.next();return{edges:e,pathTypeFlag:-1}}function Dd(c,t){const e=[];let i=-1,s=t.next();for(;e.length<c;){let n;switch(s.code){case 92:if(i=s.value,i&2){if(n=Bd(t),n)n.pathTypeFlag=i,e.push(n);else throw new Error("[Hatch] Failed to parse hatch polyline boundary path !");s=t.lastReadGroup}else s=t.next();break;case 93:{const r=s.value;n=kd(r,t),n.pathTypeFlag=i,e.push(n),s=t.lastReadGroup;break}default:s=t.next();break}}return e}function Ld(c,t){if(c<=0){t.next();return}const e=[];let i=t.next();for(let s=0;s<c;s++){let n=0;const r={x:0,y:0},a={x:0,y:0};let o=-1;const l=[];for(;!t.isEOF()&&i.code!==0;){let h=!1;switch(i.code){case 53:n=i.value;break;case 43:r.x=i.value;break;case 44:r.y=i.value;break;case 45:a.x=i.value;break;case 46:a.y=i.value;break;case 79:o=i.value;break;case 49:l.push(i.value);break;default:h=!0}if(i=t.next(),h||l.length===o)break}o>=0&&e.push({angle:n,origin:r,delta:a,dashPattern:l})}return e}function Rd(c,t){const e=[];let i=t.next();for(;e.length<c&&!t.isEOF()&&i.code!==void 0&&i.code!==0;)switch(i.code){case 63:i=t.next();break;case 421:e.push(i.value),i=t.next();break;default:i=t.next();break}return e}class Fd{constructor(){g(this,"ForEntityName","HATCH")}parseEntity(t,e){const i={type:e.value,boundaryPaths:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 2:i.patternName=e.value,e=t.next();break;case 10:i.elevationX=e.value,e=t.next();break;case 20:i.elevationY=e.value,e=t.next();break;case 30:i.elevationZ=e.value,e=t.next();break;case 41:i.patternScale=e.value,e=t.next();break;case 47:i.pixelSize=e.value,e=t.next();break;case 52:i.patternAngle=e.value,e=t.next();break;case 63:i.patternFillColor=e.value,e=t.next();break;case 70:i.solidFill=(e.value&1)!==0,e=t.next();break;case 71:i.associativity=(e.value&1)!==0,e=t.next();break;case 73:i.annotatedBoundary=(e.value&1)!==0,e=t.next();break;case 75:i.style=e.value,e=t.next();break;case 76:i.patternType=e.value,e=t.next();break;case 78:i.patternLines=Ld(e.value,t),e=t.lastReadGroup;break;case 91:i.boundaryPathsCount=e.value,i.boundaryPaths=Dd(i.boundaryPathsCount,t),e=t.lastReadGroup;break;case 98:i.seedPointsCount=e.value,e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 450:i.isGradientColor=e.value===1,e=t.next();break;case 451:e=t.next();break;case 452:e=t.next();break;case 453:i.gradientColorCount=e.value,i.gradientColors=Rd(i.gradientColorCount,t),e=t.next();break;case 460:e=t.next();break;case 461:e=t.next();break;case 462:e=t.next();break;case 463:e=t.next();break;case 470:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}var hn=(c=>(c[c.ShowImage=1]="ShowImage",c[c.ShowImageWhenNotAlignedWithScreen=2]="ShowImageWhenNotAlignedWithScreen",c[c.UseClippingBoundary=4]="UseClippingBoundary",c[c.TransparencyIsOn=8]="TransparencyIsOn",c))(hn||{});let zd=class{constructor(){g(this,"ForEntityName","IMAGE")}parseEntity(t,e){const i={type:e.value,clippingBoundaryPath:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.position=Zi(t),e=t.lastReadGroup;break;case 11:i.uPixel=Zi(t),e=t.lastReadGroup;break;case 12:i.vPixel=Zi(t),e=t.lastReadGroup;break;case 13:i.imageSize=Zi(t),e=t.lastReadGroup;break;case 340:i.imageDefHandle=e.value,e=t.next();break;case 70:i.flags=e.value,e=t.next();break;case 280:i.clipping=e.value,e=t.next();break;case 281:i.brightness=e.value,e=t.next();break;case 282:i.contrast=e.value,e=t.next();break;case 283:i.fade=e.value,e=t.next();break;case 360:i.imageDefReactorHandle=e.value,e=t.next();break;case 71:i.clippingBoundaryType=e.value,e=t.next();break;case 91:i.countBoundaryPoints=e.value,e=t.next();break;case 14:i.clippingBoundaryPath.push(Zi(t)),e=t.lastReadGroup;break;case 290:i.clipMode=e.value,e=t.next();break;default:ee(i,e),e=t.next();break}return i}};function Zi(c){const t={};let e=c.lastReadGroup||c.next();for(;!c.isEOF();){switch(e.code){case 10:case 11:case 12:case 13:case 14:t.x=e.value;break;case 20:case 21:case 22:case 23:case 24:t.y=e.value;break;case 30:case 31:case 32:case 33:case 34:t.z=e.value;break;case 42:t.bulge=e.value;break;default:return t}e=c.next()}return t}class Vd{constructor(){g(this,"ForEntityName","INSERT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 2:i.block=e.value,e=t.next();break;case 66:i.attributesFollow=e.value!=0,e=t.next();break;case 41:i.xScale=e.value,e=t.next();break;case 42:i.yScale=e.value,e=t.next();break;case 43:i.zScale=e.value,e=t.next();break;case 10:i.position=Oa(t),e=t.lastReadGroup;break;case 50:i.rotation=e.value,e=t.next();break;case 70:i.columnCount=e.value,e=t.next();break;case 71:i.rowCount=e.value,e=t.next();break;case 44:i.columnSpacing=e.value,e=t.next();break;case 45:i.rowSpacing=e.value,e=t.next();break;case 210:i.extrusionDirection=Oa(t),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;case 1e3:i.zdysx?i.zdysx+=e.value:i.zdysx=e.value,e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Oa(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}function jd(c){switch(c){case 40:return"DIMSCALE";case 41:return"DIMASZ";case 42:return"DIMEXO";case 44:return"DIMEXE";case 75:return"DIMSE1";case 76:return"DIMSE2";case 77:return"DIMTAD";case 140:return"DIMTXT";case 144:return"DIMLFAC";case 147:return"DIMGAP";case 176:return"DIMCLRD";case 178:return"DIMCLRT";case 271:return"DIMDEC";case 341:return"DIMLDRBLK";default:return null}}class Ud{constructor(){g(this,"ForEntityName","LEADER")}parseEntity(t,e){const i={type:e.value,arrowFlag:1,vertices:[]};e=t.next();let s=!1;for(;!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.vertices.push(Nd(t)),e=t.lastReadGroup;break;case 3:i.dimensionStyle=e.value,e=t.next();break;case 40:i.textHeight=e.value,e=t.next();break;case 41:i.textWidth=e.value,e=t.next();break;case 71:i.arrowFlag=e.value,e=t.next();break;case 72:i.pathType=e.value,e=t.next();break;case 73:i.creationFlag=e.value,e=t.next();break;case 74:i.direction=e.value,e=t.next();break;case 75:i.hasHookline=e.value===1,e=t.next();break;case 1001:s=e.value==="ACAD",e=t.next();break;case 1070:if(s){const n=jd(e.value);n&&(e=t.next(),(e.code==1005||e.code==1040||e.code==1070)&&(n==="DIMLDRBLK"?i.arrowHeadBlockHandle=e.value:n==="DIMASZ"?i.arrowHeight=e.value:n==="DIMSCALE"?i.arrowHeadScale=e.value:n==="DIMCLRD"&&e.value>0&&(i.colorIndex=e.value,i.color=ki(Math.abs(e.value)))))}e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Nd(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Hd{constructor(){g(this,"ForEntityName","LINE")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.vertices.unshift(qn(t)),e=t.lastReadGroup;break;case 11:i.vertices.push(qn(t)),e=t.lastReadGroup;break;case 210:i.extrusionDirection=qn(t),e=t.lastReadGroup;break;case 100:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function qn(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}function Gd(c,t){if(!c||c<=0)throw Error("n must be greater than 0 verticies");const e=[];let i=!1,s=!1,n=t.lastReadGroup;const r={};for(;!t.isEOF()&&!(n.code===0||s);)switch(n.code){case 10:if(i){s=!0;continue}r.x=n.value,i=!0,n=t.next();break;case 20:r.y=n.value,n=t.next();break;case 30:r.z=n.value,n=t.next();break;case 40:r.startWidth=n.value,n=t.next();break;case 41:r.endWidth=n.value,n=t.next();break;case 42:n.value!=0&&(r.bulge=n.value),n=t.next();break;default:return i&&e.push(r),e}return e.push(r),i=!1,s=!1,e}class qd{constructor(){g(this,"ForEntityName","LWPOLYLINE")}parseEntity(t,e){const i={type:e.value,vertices:[]};let s=0;for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 38:i.elevation=e.value,e=t.next();break;case 39:i.thickness=e.value,e=t.next();break;case 70:i.shape=(e.value&1)===1,i.hasContinuousLinetypePattern=(e.value&128)===128,e=t.next();break;case 90:s=e.value,e=t.next();break;case 10:i.vertices.push(...Gd(s,t)),e=t.lastReadGroup;break;case 43:e.value!==0&&(i.constantWidth=e.value),e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}class Wd{constructor(){g(this,"ForEntityName","MTEXT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 3:const s=e.value;i.text?i.text+=s:i.text=s,e=t.next();break;case 1:const n=e.value;i.text?i.text+=n:i.text=n,e=t.next();break;case 10:i.position=_a(t),e=t.lastReadGroup;break;case 7:i.textStyle=e.value,e=t.next();break;case 44:i.lineSpaceFactor=e.value,e=t.next();break;case 11:i.directionVector=_a(t),i.rotation=void 0,e=t.lastReadGroup;break;case 40:i.height=e.value,e=t.next();break;case 41:const r=e.value;Math.abs(r)<1e-6?i.width=void 0:i.width=r,e=t.next();break;case 50:i.rotation=e.value,i.directionVector=void 0,e=t.next();break;case 71:i.attachmentPoint=e.value,e=t.next();break;case 72:i.drawingDirection=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function _a(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Yd{constructor(){g(this,"ForEntityName","OLE2FRAME")}parseEntity(t,e){const i={type:e.value,binaryData:""};for(e=t.next();e.value!=="OLE"&&e.code!==0;)switch(e.code){case 3:i.documentType=e.value,e=t.next();break;case 70:i.version=e.value,e=t.next();break;case 10:i.leftUpX=e.value,e=t.next();break;case 20:i.leftUpY=e.value,e=t.next();break;case 30:i.leftUpZ=e.value,e=t.next();break;case 11:i.rightDownX=e.value,e=t.next();break;case 21:i.rightDownY=e.value,e=t.next();break;case 31:i.rightDownZ=e.value,e=t.next();break;case 90:i.lengthOfBinaryData=e.value,e=t.next();break;case 310:i.binaryData+=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}class Xd{constructor(){g(this,"ForEntityName","POINT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.position=Pa(t),e=t.lastReadGroup;break;case 39:i.thickness=e.value,e=t.next();break;case 210:i.extrusionDirection=Pa(t),e=t.lastReadGroup;break;case 100:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Pa(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Zd{constructor(){g(this,"ForEntityName","VERTEX")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.x=e.value,e=t.next();break;case 20:i.y=e.value,e=t.next();break;case 30:i.z=e.value,e=t.next();break;case 40:e=t.next();break;case 41:e=t.next();break;case 42:e.value!=0&&(i.bulge=e.value),e=t.next();break;case 70:i.curveFittingVertex=(e.value&1)!==0,i.curveFitTangent=(e.value&2)!==0,i.splineVertex=(e.value&8)!==0,i.splineControlPoint=(e.value&16)!==0,i.threeDPolylineVertex=(e.value&32)!==0,i.threeDPolylineMesh=(e.value&64)!==0,i.polyfaceMeshVertex=(e.value&128)!==0,e=t.next();break;case 50:e=t.next();break;case 71:i.faceA=e.value,e=t.next();break;case 72:i.faceB=e.value,e=t.next();break;case 73:i.faceC=e.value,e=t.next();break;case 74:i.faceD=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Kd(c,t){const e=new Zd,i=[];for(;!c.isEOF();)if(t.code===0){if(t.value==="VERTEX")i.push(e.parseEntity(c,t)),t=c.lastReadGroup;else if(t.value==="SEQEND"){$d(c,t);break}}return i}function $d(c,t){const e={type:t.value};for(t=c.next();!c.isEOF()&&t.code!==0;)if(t.code===101)for(;t.code!=0;)t=c.next();else ee(e,t),t=c.next();return e}class Jd{constructor(){g(this,"ForEntityName","POLYLINE")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:e=t.next();break;case 20:e=t.next();break;case 30:e=t.next();break;case 39:e=t.next(),i.thickness=e.value;break;case 40:e=t.next();break;case 41:e=t.next();break;case 70:i.shape=(e.value&1)!==0,i.includesCurveFitVertices=(e.value&2)!==0,i.includesSplineFitVertices=(e.value&4)!==0,i.is3dPolyline=(e.value&8)!==0,i.is3dPolygonMesh=(e.value&16)!==0,i.is3dPolygonMeshClosed=(e.value&32)!==0,i.isPolyfaceMesh=(e.value&64)!==0,i.hasContinuousLinetypePattern=(e.value&128)!==0,e=t.next();break;case 71:e=t.next();break;case 72:e=t.next();break;case 73:e=t.next();break;case 74:e=t.next();break;case 75:e=t.next();break;case 210:i.extrusionDirection=Qd(t),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i.vertices=Kd(t,e),i}}function Qd(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class e1{constructor(){g(this,"ForEntityName","REGION")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 70:i.modelerVersion=e.value,e=t.next();break;case 1:i.proprietaryData=e.value,e=t.next();break;case 3:i.proprietaryData+=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}class t1{constructor(){g(this,"ForEntityName","RAY")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.vertices.unshift(Aa(t)),e=t.lastReadGroup;break;case 11:i.directionVector=Aa(t),e=t.lastReadGroup;break;case 100:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Aa(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class i1{constructor(){g(this,"ForEntityName","SEQEND")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)e.code===-2||(ee(i,e),e=t.next());return i}}class s1{constructor(){g(this,"ForEntityName","SOLID")}parseEntity(t,e){const i={type:e.value,points:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.points[0]=Ki(t),e=t.lastReadGroup;break;case 11:i.points[1]=Ki(t),e=t.lastReadGroup;break;case 12:i.points[2]=Ki(t),e=t.lastReadGroup;break;case 13:i.points[3]=Ki(t),e=t.lastReadGroup;break;case 210:i.extrusionDirection=Ki(t),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Ki(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class n1{constructor(){g(this,"ForEntityName","SPLINE")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.controlPoints||(i.controlPoints=[]),i.controlPoints.push($i(t)),e=t.lastReadGroup;break;case 11:i.fitPoints||(i.fitPoints=[]),i.fitPoints.push($i(t)),e=t.lastReadGroup;break;case 12:i.startTangent=$i(t),e=t.lastReadGroup;break;case 13:i.endTangent=$i(t),e=t.lastReadGroup;break;case 40:i.knotValues||(i.knotValues=[]),i.knotValues.push(e.value),e=t.next();break;case 70:(e.value&1)!=0&&(i.closed=!0),(e.value&2)!=0&&(i.periodic=!0),(e.value&4)!=0&&(i.rational=!0),(e.value&8)!=0&&(i.planar=!0),(e.value&16)!=0&&(i.planar=!0,i.linear=!0),e=t.next();break;case 71:i.degreeOfSplineCurve=e.value,e=t.next();break;case 72:i.numberOfKnots=e.value,e=t.next();break;case 73:i.numberOfControlPoints=e.value,e=t.next();break;case 74:i.numberOfFitPoints=e.value,e=t.next();break;case 210:i.normalVector=$i(t),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function $i(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}function r1(c,t,e){let i=c;for(;i.code!==304;)switch(i.code){case 301:i=e.next();break;case 93:i=e.next();break;case 90:i=e.next();break;case 1:t.text=i.value,i=e.next();break;case 94:i=e.next();break;case 300:t.attrText=i.value,i=e.next();break;case 302:t.text=i.value?i.value:t.text,i=e.next();break;default:console.log("[DXF ACAD_TABLE] ignore code: "+i.code+", value: "+i.value),i=e.next();break}}function Ia(c,t){const e={};for(c.code===171&&(e.cellType=c.value);!t.isEOF();){const i=t.next();if(i.code===0||i.code===171){t.lastReadGroup=i;break}if(i.code===301){r1(i,e,t);continue}switch(i.code){case 172:e.flagValue=i.value;break;case 173:e.mergedValue=i.value;break;case 174:e.autoFit=i.value;break;case 175:e.borderWidth=i.value;break;case 176:e.borderHeight=i.value;break;case 177:e.overrideFlag=i.value;break;case 178:e.virtualEdgeFlag=i.value;break;case 145:e.rotation=i.value;break;case 140:e.textHeight=i.value;break;case 170:e.attachmentPoint=i.value;break;case 91:e.extendedCellFlags=i.value;break;case 7:e.textStyle=i.value;break;case 340:e.blockTableRecordId=i.value;break;case 345:e.fieldObjetId=i.value;break;case 146:e.blockScale=i.value;break;case 179:e.blockAttrNum=i.value;break;case 1:e.text=i.value;break;case 302:e.attrText=i.value;break}}return e}class a1{constructor(){g(this,"ForEntityName","ACAD_TABLE")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.startPoint=Ba(t),e=t.lastReadGroup;break;case 11:i.directionVector=Ba(t),e=t.lastReadGroup;break;case 90:i.tableValue=e.value,e=t.next();break;case 91:i.rowCount=e.value,e=t.next();break;case 92:i.columnCount=e.value,e=t.next();break;case 93:i.overrideFlag=e.value,e=t.next();break;case 94:i.borderColorOverrideFlag=e.value,e=t.next();break;case 95:i.borderLineWeightOverrideFlag=e.value,e=t.next();break;case 96:i.borderVisibilityOverrideFlag=e.value,e=t.next();break;case 141:i.rowHeightArr?i.rowHeightArr.push(e.value):i.rowHeightArr=[e.value],e=t.next();break;case 142:i.columnWidthArr?i.columnWidthArr.push(e.value):i.columnWidthArr=[e.value],e=t.next();break;case 280:i.version=e.value,e=t.next();break;case 342:i.tableStyleId=e.value,e=t.next();break;case 343:i.blockRecordHandle=e.value,e=t.next();break;case 171:i.cells?i.cells.push(Ia(e,t)):i.cells=[Ia(e,t)],e=t.lastReadGroup;break;default:ee(i,e),e=t.next();break}return i}}function Ba(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class o1{constructor(){g(this,"ForEntityName","TEXT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.startPoint=ka(t),e=t.lastReadGroup;break;case 11:i.endPoint=ka(t),e=t.lastReadGroup;break;case 40:i.textHeight=e.value,e=t.next();break;case 41:i.xScale=e.value,e=t.next();break;case 50:i.rotation=e.value,e=t.next();break;case 1:i.text=e.value,e=t.next();break;case 72:i.halign=e.value,e=t.next();break;case 73:i.valign=e.value,e=t.next();break;case 7:i.textStyle=e.value,e=t.next();break;case 71:i.mirrored=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function ka(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class l1{constructor(){g(this,"ForEntityName","VIEWPORT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 68:i.viewportStatus=e.value,e=t.next();break;case 40:i.width_paperSpace=e.value,e=t.next();break;case 41:i.height_paperSpace=e.value,e=t.next();break;case 69:i.viewportId=e.value,e=t.next();break;case 10:i.centerPoint=ut(t),e=t.lastReadGroup;break;case 12:i.centerPoint_dcs=ut(t),e=t.lastReadGroup;break;case 13:i.snapBasePoint_dcs=ut(t),e=t.lastReadGroup;break;case 14:i.snapSpacing_dcs=ut(t),e=t.lastReadGroup;break;case 15:i.gridSpacing_dcs=ut(t),e=t.lastReadGroup;break;case 16:i.viewDirection=ut(t),e=t.lastReadGroup;break;case 17:i.viewTarget=ut(t),e=t.lastReadGroup;break;case 42:i.perspectiveLens=e.value,e=t.next();break;case 43:i.frontClippingPlaneZ=e.value,e=t.next();break;case 44:i.backClippingPlaneZ=e.value,e=t.next();break;case 45:i.viewHeight=e.value,e=t.next();break;case 50:i.snapAngle=e.value,e=t.next();break;case 51:i.viewTwistAngle=e.value,e=t.next();break;case 72:i.circleZoomPercent=e.value,e=t.next();break;case 331:i.frozenLayerHandles=i.frozenLayerHandles||[],i.frozenLayerHandles.push(e.value),e=t.next();break;case 90:i.viewportStatusFlags=e.value,e=t.next();break;case 340:i.viewportClippingBoundaryhandleId=e.value,e=t.next();break;case 1:i.plotStyleSheetName=e.value,e=t.next();break;case 281:i.renderMode=e.value,e=t.next();break;case 71:i.viewportFlag_ucs=e.value,e=t.next();break;case 74:i.ucsIcon=e.value,e=t.next();break;case 110:i.ucsOrigin=ut(t),e=t.lastReadGroup;break;case 111:i.ucsXAxis=ut(t),e=t.lastReadGroup;break;case 112:i.ucsYAxis=ut(t),e=t.lastReadGroup;break;case 345:i.ucsTableRecordHandle=e.value,e=t.next();break;case 346:i.baseUcsTableRecordHandle=e.value,e=t.next();break;case 79:i.orthographicType=e.value,e=t.next();break;case 146:i.elevation=e.value,e=t.next();break;case 170:i.shadePlotMode=e.value,e=t.next();break;case 61:i.frequency=e.value,e=t.next();break;case 292:i.lightingFlag=e.value,e=t.next();break;case 282:i.lightingType=e.value,e=t.next();break;case 141:i.viewBrightness=e.value,e=t.next();break;case 142:i.viewContrast=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function ut(c){const t={};let e=c.lastReadGroup||c.next();for(;!c.isEOF();){switch(e.code){case 10:case 12:case 13:case 14:case 15:case 16:case 17:case 110:case 111:case 112:t.x=e.value;break;case 20:case 22:case 23:case 24:case 25:case 26:case 27:case 120:case 121:case 122:t.y=e.value;break;case 30:case 32:case 33:case 34:case 35:case 36:case 37:case 130:case 131:case 132:t.z=e.value;break;case 42:t.bulge=e.value;break;default:return t}e=c.next()}return t}class c1{constructor(){g(this,"ForEntityName","XLINE")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.vertices.unshift(Da(t)),e=t.lastReadGroup;break;case 11:i.directionVector=Da(t),e=t.lastReadGroup;break;case 100:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Da(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class h1{constructor(){g(this,"ForObjectName","DICTIONARY")}parseObject(t,e){const s={type:e.value},n=[],r=[];for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 280:s.isHardOwner=e.value===1,e=t.next();break;case 281:s.cloningFlag=e.value,e=t.next();break;case 3:n.push(e.value),e=t.next();break;case 350:r.push(e.value),e=t.next();break;case 360:r.push(e.value),e=t.next();break;case 100:e=t.next();break;case 102:e=t.next();break;default:zi(s,e),e=t.next();break}if(n.length!==r.length)throw new Error("The number of Dictionary entries does not match !");return s.entries={},n.forEach((a,o)=>{s.entries[r[o]]=a}),s}}class d1{constructor(){g(this,"ForObjectName","IMAGEDEF")}parseObject(t,e){const s={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 90:s.classVersion=e.value,e=t.next();break;case 1:s.filename=e.value,e=t.next();break;case 10:s.imageSize=La(t),e=t.next();break;case 11:s.pixelSize=La(t),e=t.next();break;case 280:s.loaded=e.value,e=t.next();break;case 281:s.resolutionUnits=e.value,e=t.next();break;default:zi(s,e),e=t.next();break}return s}}function La(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class u1{constructor(){g(this,"ForObjectName","LAYOUT")}parseObject(t,e){const s={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 100:e=t.next();break;case 1:s.layoutName=e.value,e=t.next();break;case 70:s.flag=e.value,e=t.next();break;case 71:s.tabOrder=e.value,e=t.next();break;case 76:s.orthographicType=e.value,e=t.next();break;case 10:s.minLimit=kt(t),e=t.lastReadGroup;break;case 11:s.maxLimit=kt(t),e=t.lastReadGroup;break;case 12:s.basePoint=kt(t),e=t.lastReadGroup;break;case 13:s.origin=kt(t),e=t.lastReadGroup;break;case 14:s.minExtent=kt(t),e=t.lastReadGroup;break;case 15:s.maxExtent=kt(t),e=t.lastReadGroup;break;case 16:s.XAxis=kt(t),e=t.lastReadGroup;break;case 17:s.YAxis=kt(t),e=t.lastReadGroup;break;case 146:s.elevation=e.value,e=t.next();break;case 330:s.viewportHandle=e.value,e=t.next();break;default:zi(s,e),e=t.next();break}return s.blockTableHandle=s.ownerHandle,s}}function kt(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class f1{constructor(){g(this,"ForObjectName","SORTENTSTABLE")}parseObject(t,e){const s={type:e.value};let n=!1;s.sortEntsObject={},s.sortEntsObject.entityHandles=[];let r=[];for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 5:n?(r.push(e.value),s.sortEntsObject.entityHandles.push(r),r=[]):s.handle=e.value,e=t.next();break;case 100:e=t.next(),n=!0;break;case 102:e=t.next();break;case 330:n?s.sortEntsObject.ownerHandle=e.value:s.ownerHandle=e.value,e=t.next();break;case 331:r.push(e.value),e=t.next();break;default:zi(s,e),e=t.next();break}return s}}class p1{constructor(){g(this,"ForObjectName","SPATIAL_FILTER")}parseObject(t,e){const s={type:e.value};s.vertices=[];let n,r;for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 11:s.origin=dn(t),e=t.lastReadGroup;break;case 70:s.numberOfPointsOnClipBoundary=e.value,s.numberOfPointsOnClipBoundary===2?(e=t.next(),n=dn(t),e=t.lastReadGroup,r=dn(t),e=t.lastReadGroup,s.vertices.push(n,{x:r.x,y:n.y},r,{x:n.x,y:r.y},n)):s.numberOfPointsOnClipBoundary>2?(s.vertices=m1(s.numberOfPointsOnClipBoundary,t),e=t.lastReadGroup):e=t.next();break;case 71:s.clipBoundaryVisible=e.value===1,e=t.next();break;case 72:s.frontClippingPlaneFlag=e.value===1,e=t.next(),s.frontClippingPlaneFlag&&e.code===40&&(s.frontClippingPlaneDistance=e.value,e=t.next());break;case 73:s.backClippingPlaneFlag=e.value===1,e=t.next(),s.backClippingPlaneFlag&&e.code===41&&(s.backClippingPlaneDistance=e.value,e=t.next());break;case 100:e=t.next();break;case 102:e=t.next();break;case 210:s.extrusionDirectionX=e.value,e=t.next();break;case 220:s.extrusionDirectionY=e.value,e=t.next();break;case 230:s.extrusionDirectionZ=e.value,e=t.next();break;case 40:s.invertBlockMatrix=Ra(t,40),s.matrix=Ra(t,40),e=t.lastReadGroup;break;default:zi(s,e),e=t.next();break}return s}}function m1(c,t){t.next();const e=[];for(;e.length<c;)e.push(dn(t));return e}function Ra(c,t){let e=c.lastReadGroup;const i=[];for(let s=0;s<12;s++){if(e.code!==t)throw new Error("Expected code for matrix value to be "+t+" but got "+e.code);i.push(e.value),e=c.next()}return i}function dn(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class g1{constructor(){g(this,"ForObjectName","XRECORD")}parseObject(t,e){const s={type:e.value,binaryData:""};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 100:e=t.next();break;case 280:s.cloningFlag=e.value,e=t.next();break;case 310:s.binaryData+=e.value,e=t.next();break;case 311:e=t.next();break;default:zi(s,e),e=t.next();break}return s}}function y1(c){c.registerEntityHandler(vd),c.registerEntityHandler(Md),c.registerEntityHandler(Cd),c.registerEntityHandler(Sd),c.registerEntityHandler(Ed),c.registerEntityHandler(_d),c.registerEntityHandler(Pd),c.registerEntityHandler(Id),c.registerEntityHandler(Fd),c.registerEntityHandler(zd),c.registerEntityHandler(Vd),c.registerEntityHandler(Ud),c.registerEntityHandler(Hd),c.registerEntityHandler(qd),c.registerEntityHandler(Wd),c.registerEntityHandler(Yd),c.registerEntityHandler(Xd),c.registerEntityHandler(Jd),c.registerEntityHandler(e1),c.registerEntityHandler(t1),c.registerEntityHandler(i1),c.registerEntityHandler(s1),c.registerEntityHandler(n1),c.registerEntityHandler(a1),c.registerEntityHandler(o1),c.registerEntityHandler(l1),c.registerEntityHandler(c1)}function x1(c){c.registerObjectHandler(h1),c.registerObjectHandler(d1),c.registerObjectHandler(u1),c.registerObjectHandler(f1),c.registerObjectHandler(p1),c.registerObjectHandler(g1)}function b1(c){const t=new Uint8Array(c,0,18);let e="";for(let i=0;i<18;i++)e+=String.fromCharCode(t[i]);return e==="AutoCAD Binary DXF"}class Ho{constructor(t){g(this,"_entityHandlers",{});g(this,"_objectHandlers",{});g(this,"_layoutBlocks",{});g(this,"unhandledSections",{});g(this,"unhandledObjects",{});g(this,"unhandledEntities",{});g(this,"unsupportedLineTypes",{});g(this,"encoding");this.encoding=t,y1(this),x1(this)}parse(t){if(typeof t=="string"){const e=this.splitByLineSeparator(t),i=new Ca(e);return this._parse(i)}else{let e;if(b1(t))e=new gd(t);else{const i=new TextDecoder(this.encoding).decode(t),s=Date.now(),n=this.splitByLineSeparator(i);console.info("[DxfParser] string.split took "+(Date.now()-s)/1e3+"s, it is avoidable by using dxf in binary."),e=new Ca(n)}return this._parse(e)}}registerEntityHandler(t){const e=new t;this._entityHandlers[e.ForEntityName]=e}registerObjectHandler(t){const e=new t;this._objectHandlers[e.ForObjectName]=e}parseSync(t){return this.parse(t)}parseStream(t){let e="";const i=this;return new Promise((s,n)=>{t.on("data",r=>{e+=r}),t.on("end",()=>{try{s(i.parse(e))}catch(r){n(r)}}),t.on("error",r=>{n(r)})})}_parse(t){const e={};let i=0;if(!t.hasNext())throw Error("Empty file");const s=this;let n;function r(){for(n=t.next();n.code===999;)n=t.next();for(;!t.isEOF();)if(n.code===0&&n.value==="SECTION"){if(n=t.next(),n.code!==2){console.error("Unexpected code %s after 0:SECTION",Go(n)),n=t.next();continue}if(n.value==="HEADER")P.trace("> HEADER"),e.header=a(),P.trace("<");else if(n.value==="TABLES")P.trace("> TABLES"),e.tables=h(),P.trace("<");else if(n.value==="BLOCKS")P.trace("> BLOCKS"),e.blocks=o(),P.trace("<");else if(n.value==="ENTITIES")P.trace("> ENTITIES"),e.entities=E(!1),P.trace("<");else if(n.value==="OBJECTS")P.trace("> OBJECTS"),e.objects=M(),P.trace("<");else if(n.value==="EOF")P.trace("EOF");else{const T=n.value;s.unhandledSections[T]?s.unhandledSections[T]++:s.unhandledSections[T]=1}}else n=t.next();s.unhandledSections={},s.unhandledEntities={},s.unhandledObjects={},s.unsupportedLineTypes={}}function a(){let T=null,v=null;const C={};for(n=t.next();;){if(Ge(n,0,"ENDSEC")){T&&(C[T]=v);break}else n.code===9?(T&&(C[T]=v),T=n.value):n.code===10?v={x:n.value}:n.code===20?v.y=n.value:n.code===30?v.z=n.value:v=n.value;n=t.next()}return n=t.next(),C}function o(){const T={};for(n=t.next();n.value!=="EOF"&&!Ge(n,0,"ENDSEC");)if(Ge(n,0,"BLOCK")){P.trace("block {");const v=l();P.trace("}"),O(v),v.name?T[v.name]=v:console.error("[DxfParser] Block with handle '"+v.handle+"' is missing a name, ignored!")}else vt(n),n=t.next();return T}function l(){const T={};for(n=t.next();n.value!=="EOF";){switch(n.code){case 1:T.xrefPath=n.value,n=t.next();break;case 2:T.name=n.value,n=t.next();break;case 3:T.name2=n.value,n=t.next();break;case 4:T.description=n.value,n=t.next();break;case 5:T.handle=n.value,n=t.next();break;case 8:T.layer=n.value,n=t.next();break;case 10:T.position=Xe(t),n=t.lastReadGroup;break;case 67:T.paperSpace=!!(n.value&&n.value===1),n=t.next();break;case 70:T.blockType=n.value,n=t.next();break;case 100:n=t.next();break;case 330:T.ownerHandle=n.value,n=t.next();break;case 0:if(n.value==="ENDBLK")break;T.entities=E(!0);break;default:vt(n),n=t.next();break}if(Ge(n,0,"ENDBLK")){n=t.next();break}}return T}function h(){const T={};for(n=t.next();n.value!=="EOF"&&!Ge(n,0,"ENDSEC");)Ge(n,0,"TABLE")?(n=t.next(),x[n.value]?(P.trace(n.value+" Table {"),T[x[n.value].tableName]=u(n),P.trace("}")):P.trace("Unhandled Table "+n.value)):n=t.next();return n=t.next(),T}const d="ENDTAB";function u(T){const v=x[T.value],C={};let _=0;for(n=t.next();!Ge(n,0,d);)switch(n.code){case 5:C.handle=n.value,n=t.next();break;case 330:C.ownerHandle=n.value,n=t.next();break;case 100:n.value==="AcDbSymbolTable"||vt(n),n=t.next();break;case 70:_=n.value,n=t.next();break;case 0:n.value===v.dxfSymbolName?C[v.tableRecordsProperty]=v.parseTableRecords():(vt(n),n=t.next());break;default:vt(n),n=t.next();break}const A=C[v.tableRecordsProperty];if(A){const I=(()=>{if(A.constructor===Array)return A.length;if(typeof A=="object")return Object.keys(A).length})();_!==I&&console.warn("[DxfParser] Parsed "+I+" "+v.dxfSymbolName+"s but expected "+_)}return n=t.next(),C}function f(){const T=[];let v={};for(P.trace("Viewport {"),n=t.next();!Ge(n,0,d);)switch(n.code){case 2:v.name=n.value,n=t.next();break;case 10:v.lowerLeftCorner=Xe(t),n=t.lastReadGroup;break;case 11:v.upperRightCorner=Xe(t),n=t.lastReadGroup;break;case 12:v.center=Xe(t),n=t.lastReadGroup;break;case 13:v.snapBasePoint=Xe(t),n=t.lastReadGroup;break;case 14:v.snapSpacing=Xe(t),n=t.lastReadGroup;break;case 15:v.gridSpacing=Xe(t),n=t.lastReadGroup;break;case 16:v.viewDirectionFromTarget=Xe(t),n=t.lastReadGroup;break;case 17:v.viewTarget=Xe(t),n=t.lastReadGroup;break;case 40:v.viewHeight=n.value,n=t.next();break;case 41:v.aspectRatio=n.value,n=t.next();break;case 42:v.lensLength=n.value,n=t.next();break;case 43:v.frontClippingPlane=n.value,n=t.next();break;case 44:v.backClippingPlane=n.value,n=t.next();break;case 45:v.viewHeight=n.value,n=t.next();break;case 50:v.snapRotationAngle=n.value,n=t.next();break;case 51:v.viewTwistAngle=n.value,n=t.next();break;case 79:v.orthographicType=n.value,n=t.next();break;case 110:v.ucsOrigin=Xe(t),n=t.lastReadGroup;break;case 111:v.ucsXAxis=Xe(t),n=t.lastReadGroup;break;case 112:v.ucsYAxis=Xe(t),n=t.lastReadGroup;break;case 281:v.renderMode=n.value,n=t.next();break;case 282:v.defaultLightingType=n.value,n=t.next();break;case 292:v.defaultLightingOn=n.value,n=t.next();break;case 330:v.ownerHandle=n.value,n=t.next();break;case 63:case 421:case 431:v.ambientColor=n.value,n=t.next();break;case 0:n.value==="VPORT"&&(P.trace("}"),T.push(v),P.trace("Viewport {"),v={},n=t.next());break;default:vt(n),n=t.next();break}return P.trace("}"),T.push(v),T}function m(){const T={};let v={},C=0,_="",A=!1;for(P.trace("LType {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 2:v.name=n.value.toUpperCase(),_=v.name,n=t.next();break;case 3:v.description=n.value,n=t.next();break;case 9:n=t.next();break;case 40:v.patternLength=n.value,n=t.next();break;case 44:n=t.next();break;case 45:n=t.next();break;case 46:n=t.next();break;case 49:let I=n.value;A&&(I=Math.abs(I),A=!1),v.pattern.push(I),n=t.next();break;case 70:n=t.next();break;case 73:C=n.value,C>0&&(v.pattern=[]),n=t.next();break;case 74:n.value!==0&&(A=!0,s.unsupportedLineTypes[v.name]?s.unsupportedLineTypes[v.name]++:s.unsupportedLineTypes[v.name]=1),n=t.next();break;case 75:n=t.next();break;case 0:P.trace("}"),C>0&&C!==v.pattern.length&&console.warn("[DxfParser] lengths do not match on LTYPE pattern"),T[_]=v,v={},P.trace("LType {"),n=t.next();break;default:n=t.next();break}return P.trace("}"),T[_]=v,T}function b(){const T={};let v={},C;for(P.trace("Layer {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 2:v.name=n.value,C=n.value,n=t.next();break;case 5:v.handle=n.value,n=t.next();break;case 62:v.visible=n.value>=0,v.colorIndex=Math.abs(n.value),v.color=ki(v.colorIndex),n=t.next();break;case 70:v.flag=n.value,v.frozen=(v.flag&1)>0,n=t.next();break;case 420:v.color=Math.abs(n.value),n=t.next();break;case 6:v.lineType=n.value.toUpperCase(),n=t.next();break;case 370:v.lineweight=n.value,n=t.next();break;case 0:n.value==="LAYER"&&(P.trace("}"),C&&(T[C]=v),P.trace("Layer {"),v={},C=void 0,n=t.next());break;default:vt(n),n=t.next();break}return P.trace("}"),C&&(T[C]=v),T}function y(){const T={};let v={},C;for(P.trace("Style {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 2:v.styleName=n.value,C=n.value,n=t.next();break;case 3:v.fontFile=n.value,n=t.next();break;case 4:v.bigFontFile=n.value,n=t.next();break;case 5:v.handle=n.value,n=t.next();break;case 40:v.textHeight=n.value,n=t.next();break;case 41:v.xScale=n.value,n=t.next();break;case 42:v.priorTextHeight=n.value,n=t.next();break;case 50:v.rotation=n.value,n=t.next();break;case 70:n=t.next();break;case 71:v.mirrorType=n.value,n=t.next();break;case 330:v.ownerHandle=n.value,n=t.next();break;case 0:n.value==="STYLE"&&(P.trace("}"),C&&(T[C]=v),P.trace("Style {"),v={},C=void 0,n=t.next());break;default:n=t.next();break}return P.trace("}"),C&&(T[C]=v),T}function S(){const T={};let v={},C;for(P.trace("DimStyle {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 2:v.styleName=n.value,C=n.value,n=t.next();break;case 40:v.DIMSCALE=n.value,n=t.next();break;case 41:v.DIMASZ=n.value,n=t.next();break;case 42:v.DIMEXO=n.value,n=t.next();break;case 44:v.DIMEXE=n.value,n=t.next();break;case 75:v.DIMSE1=n.value,n=t.next();break;case 76:v.DIMSE2=n.value,n=t.next();break;case 77:v.DIMTAD=n.value,n=t.next();break;case 140:v.DIMTXT=n.value,n=t.next();break;case 144:v.DIMLFAC=n.value,n=t.next();break;case 147:v.DIMGAP=n.value,n=t.next();break;case 176:v.DIMCLRD=n.value,n=t.next();break;case 178:v.DIMCLRT=n.value,n=t.next();break;case 271:v.DIMDEC=n.value,n=t.next();break;case 341:v.DIMLDRBLK=n.value,n=t.next();break;case 70:n=t.next();break;case 0:n.value==="DIMSTYLE"&&(P.trace("}"),C&&(T[C]=v),P.trace("DimStyle {"),v={},C=void 0,n=t.next());break;default:n=t.next();break}return P.trace("}"),C&&(T[C]=v),T}function w(){const T={};let v={},C;for(P.trace("BlockRecord {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 5:v.handle=n.value,n=t.next();break;case 330:v.ownerHandle=n.value,n=t.next();break;case 2:v.blockName=n.value,C=v.blockName,n=t.next();break;case 340:v.layoutHandle=n.value,n=t.next();break;case 70:v.blockInsertUnits=n.value,n=t.next();break;case 280:v.blockExplodability=n.value,n=t.next();break;case 281:v.blockScalability=n.value,n=t.next();break;case 310:v.bitmap=n.value,n=t.next();break;case 0:if(n.value==="BLOCK_RECORD"){P.trace("}"),C&&(T[C]=v);const A=v.layoutHandle;C&&A&&A.length>0&&A!=="0"&&(s._layoutBlocks[A]=v),P.trace("BlockRecord {"),v={},C=void 0,n=t.next()}else vt(n),n=t.next();break;default:vt(n),n=t.next();break}P.trace("}"),C&&(T[C]=v);const _=v.layoutHandle;return C&&_&&_.length>0&&_!=="0"&&(s._layoutBlocks[_]=v),T}const x={VPORT:{tableRecordsProperty:"viewports",tableName:"viewport",dxfSymbolName:"VPORT",parseTableRecords:f},LTYPE:{tableRecordsProperty:"lineTypes",tableName:"lineType",dxfSymbolName:"LTYPE",parseTableRecords:m},LAYER:{tableRecordsProperty:"layers",tableName:"layer",dxfSymbolName:"LAYER",parseTableRecords:b},BLOCK_RECORD:{tableRecordsProperty:"blockRecords",tableName:"blockRecord",dxfSymbolName:"BLOCK_RECORD",parseTableRecords:w},STYLE:{tableRecordsProperty:"styles",tableName:"style",dxfSymbolName:"STYLE",parseTableRecords:y},DIMSTYLE:{tableRecordsProperty:"dimStyles",tableName:"dimStyle",dxfSymbolName:"DIMSTYLE",parseTableRecords:S}};function E(T){const v=[],C=T?"ENDBLK":"ENDSEC";for(T||(n=t.next());;)if(n.code===0){if(n.value===C)break;const _=s._entityHandlers[n.value];if(_!=null){P.trace(n.value+" {");const A=_.parseEntity(t,n);A&&(A.layer||(A.layer="0"),A.colorIndex===void 0&&(A.colorIndex=256),A.lineType||(A.lineType="BYLAYER"),n=t.lastReadGroup,P.trace("}"),O(A),v.push(A))}else{const A=n.value;s.unhandledEntities[A]||(s.unhandledEntities[A]=0),s.unhandledEntities[A]++,n=t.next();continue}}else n=t.next();return C==="ENDSEC"&&(n=t.next()),v}function M(){const T={},v="ENDSEC";for(n=t.next();n.value!=="EOF";)if(n.code===0){if(n.value===v)break;const C=s._objectHandlers[n.value];if(C!=null){P.trace(n.value+" {");const _=C.parseObject(t,n),A=n.value;n=t.lastReadGroup,P.trace("}"),O(_),T[A]||(T[A]=[]),T[A].push(_)}else{const _=n.value;s.unhandledObjects[_]||(s.unhandledObjects[_]=0),s.unhandledObjects[_]++,n=t.next();continue}}else n=t.next();return n=t.next(),T.LAYOUT&&(Object.keys(s._layoutBlocks).length!==T.LAYOUT.length&&console.warn("[DxfParser] The number of layout and block associations does not match!"),T.LAYOUT.forEach(C=>{s._layoutBlocks[C.handle]&&(C.associatedBlockName=s._layoutBlocks[C.handle].blockName)}),T.LAYOUT.sort((C,_)=>C.tabOrder-_.tabOrder)),T}function O(T){if(!T)throw new TypeError("entity cannot be undefined or null");T.handle||(T.handle=(i++).toString())}return r(),e}splitByLineSeparator(t){const e=[];let i=0;for(let s=0,n=t.length;s<n;++s){const r=t[s];if(r==="\r"||r===`
791
+ `;return new p.ShaderMaterial({uniforms:n,vertexShader:r,fragmentShader:a,clipping:!0})}var Ke=(c=>(c.Unitless="Unitless",c.Inches="Inches",c.Feet="Feet",c.Millimeters="Millimeters",c.Centimeters="Centimeters",c.Meters="Meters",c))(Ke||{});const wr=c=>c==="Unitless"?1:c==="Inches"?.0254:c==="Feet"?.3048:c==="Millimeters"?.001:c==="Centimeters"?.01:(c==="Meters"||console.warn("[Units] Unsupported unit '"+c+"', will return 1 for unit scale."),1),md=(c,t)=>wr(c)/wr(t);class Uo{constructor(){g(this,"pointer");g(this,"eof");g(this,"lastReadGroup");this.pointer=0,this.eof=!1}}class vs{constructor(t,e){g(this,"endian");g(this,"position");g(this,"data");g(this,"decoder");this.endian=e&&e==="big"?"big":"little",this.position=0,this.data=new DataView(t)}readAsciiString(t){if(this.data.byteLength<this.position+t)throw"range error";let e="";for(let i=0;i<t;i++)e+=String.fromCharCode(this.data.getInt8(this.position+i));return this.position+=t,e}readUtf8String(t){const e=this.readBytes(t);return this.decoder||(this.decoder=new TextDecoder("utf-8")),this.decoder.decode(e)}readBytes(t=1){if(this.data.byteLength<this.position+t)throw"range error";const e=new Uint8Array(t);for(let i=0;i<t;i++)e[i]=this.data.getUint8(this.position+i);return this.position+=t,e}readUint8(){if(this.data.byteLength<this.position+1)throw"range error";const t=this.data.getUint8(this.position);return this.position+=1,t}readInt8(){if(this.data.byteLength<this.position+1)throw"range error";const t=this.data.getInt8(this.position);return this.position+=1,t}readUint16(){if(this.data.byteLength<this.position+2)throw"range error";const t=this.data.getUint16(this.position,this.endian==="little");return this.position+=2,t}readInt16(){if(this.data.byteLength<this.position+2)throw"range error";const t=this.data.getInt16(this.position,this.endian==="little");return this.position+=2,t}readUint32(){if(this.data.byteLength<this.position+4)throw"range error";const t=this.data.getUint32(this.position,this.endian==="little");return this.position+=4,t}readInt32(){if(this.data.byteLength<this.position+4)throw"range error";const t=this.data.getInt32(this.position,this.endian==="little");return this.position+=4,t}readFloat32(){if(this.data.byteLength<this.position+4)throw"range error";const t=this.data.getFloat32(this.position,this.endian==="little");return this.position+=4,t}readFloat64(){if(this.data.byteLength<this.position+8)throw"range error";const t=this.data.getFloat64(this.position,this.endian==="little");return this.position+=8,t}readInt64(){if(this.data.byteLength<this.position+8)throw"range error";const t=Ms.DataViewGetBigInt64(this.data,this.position,this.endian==="little");return this.position+=8,Ms.toNumber(t)}readUint64(){if(this.data.byteLength<this.position+8)throw"range error";const t=Ms.DataViewGetBigUint64(this.data,this.position,this.endian==="little");return this.position+=8,Ms.toNumber(t)}getPosition(){return this.position}setPosition(t){if(this.data.byteLength<t)throw"range error";this.position=t}isEnd(){return this.position===this.data.byteLength-1}}const Ma=1e3;class gd extends Uo{constructor(e){super();g(this,"reader");g(this,"decoder");g(this,"int8Array");g(this,"caches");this.int8Array=new Int8Array(Ma),this.caches=new Map,this.reader=new vs(e);const i=this.reader.readBytes(22);let s="";for(let n=0;n<18;n++)s+=String.fromCharCode(i[n]);if(s!=="AutoCAD Binary DXF")throw new Error("Invalid DXF file")}next(){if(!this.hasNext())throw this.eof?new Error("Cannot call 'next' after EOF group has been read"):new Error("Unexpected end of input: EOF group not read before end of file.");const e={code:this.reader.readInt16()};return e.value=this.parseGroupValue(e.code),e.code===0&&e.value==="EOF"&&(this.eof=!0),this.lastReadGroup=e,e}hasNext(){return this.eof?!1:!this.reader.isEnd()}isEOF(){return this.eof}parseGroupValue(e){if(e>=0&&e<=9)return this.readNullTerminatedString();if(e>=10&&e<=59)return this.reader.readFloat64();if(e>=60&&e<=79)return this.reader.readInt16();if(e>=90&&e<=99)return this.reader.readInt32();if(e>=100&&e<=109)return this.readNullTerminatedString();if(e>=110&&e<=149)return this.reader.readFloat64();if(e>=160&&e<=169)return this.reader.readInt64();if(e>=170&&e<=179)return this.reader.readInt16();if(e>=210&&e<=239)return this.reader.readFloat64();if(e>=270&&e<=289)return this.reader.readInt16();if(e>=290&&e<=299)return this.reader.readInt8()>0;if(e>=300&&e<=309)return this.readNullTerminatedString();if(e>=310&&e<=319){const i=this.ReadBinaryData();return Ta(i)}if(e>=320&&e<=369)return this.readNullTerminatedString();if(e>=370&&e<=389)return this.reader.readInt16();if(e>=390&&e<=399)return this.readNullTerminatedString();if(e>=400&&e<=409)return this.reader.readInt16();if(e>=410&&e<=419)return this.readNullTerminatedString();if(e>=420&&e<=429)return this.reader.readInt32();if(e>=430&&e<=439)return this.readNullTerminatedString();if(e>=440&&e<=449)return this.reader.readInt32();if(e>=450&&e<=459)return this.reader.readFloat64();if(e>=460&&e<=469)return this.readNullTerminatedString();if(e>=470&&e<=479)return this.readNullTerminatedString();if(e>=480&&e<=481)return this.readNullTerminatedString();if(e>=999&&e<=999)throw new Error("The comment group 999, is not used in binary DXF files at byte address!");if(e===1004){const i=this.ReadBinaryData();return Ta(i)}if(e>=1e3&&e<=1009)return this.readNullTerminatedString();if(e>=1010&&e<=1059)return this.reader.readFloat64();if(e>=1060&&e<=1070)return this.reader.readInt16();if(e===1071)return this.reader.readInt32();console.warn("[DxfBinReader] Invalid code '"+e+"' at byte address "+this.reader.getPosition())}readNullTerminatedString(){this.decoder||(this.decoder=new TextDecoder("utf-8"));let e=0,i=this.reader.readInt8();for(;i!==0;)this.int8Array[e++]=i,i=this.reader.readInt8();if(e===0)return"";if(e>Ma)return console.warn("[DxfBinReader] Failed to read string! The number of bytes is "+e+" !"),"";const s=this.int8Array.subarray(0,e),n=s.toString();if(this.caches.get(n))return this.caches.get(n);const r=this.decoder?.decode(s);return this.caches.set(n,r),r}ReadBinaryData(){const e=this.reader.readUint8();return this.reader.readBytes(e)}}function Ta(c){return Array.prototype.map.call(c,t=>("00"+t.toString(16)).slice(-2)).join("")}class Ca extends Uo{constructor(e){super();g(this,"data");this.data=e}next(){if(!this.hasNext())throw this.eof?new Error("Cannot call 'next' after EOF group has been read"):new Error("Unexpected end of input: EOF group not read before end of file. Ended on code "+this.data[this.pointer]);const e={code:parseInt(this.data[this.pointer])};return this.pointer++,e.value=yd(e.code,this.data[this.pointer].trim(),this.data[this.pointer]),this.pointer++,e.code===0&&e.value==="EOF"&&(this.eof=!0),this.lastReadGroup=e,e}hasNext(){return!(this.eof||this.pointer>this.data.length-2)}isEOF(){return this.eof}}function yd(c,t,e){return c>=0&&c<=9?e:c>=10&&c<=59?parseFloat(t):c>=60&&c<=99?parseInt(t):c>=100&&c<=109?t:c>=110&&c<=149?parseFloat(t):c>=160&&c<=179?parseInt(t):c>=210&&c<=239?parseFloat(t):c>=270&&c<=289?parseInt(t):c>=290&&c<=299?xd(t):c>=300&&c<=369?t:c>=370&&c<=389?parseInt(t):c>=390&&c<=399?t:c>=400&&c<=409?parseInt(t):c>=410&&c<=419?t:c>=420&&c<=429?parseInt(t):c>=430&&c<=439?t:c>=440&&c<=449?parseInt(t):c>=450&&c<=459?parseFloat(t):c>=460&&c<=469||c===999||c>=1e3&&c<=1009?t:c>=1010&&c<=1059?parseFloat(t):c>=1060&&c<=1071?parseInt(t):(console.info("WARNING: Group code does not have a defined type: %j",{code:c,value:t}),t)}function xd(c){if(c==="0")return!1;if(c==="1")return!0;throw TypeError("String '"+c+"' cannot be cast to Boolean type")}function bd(c){if(c==null)return!0;for(const t in c)if(Object.prototype.hasOwnProperty.call(c,t))return!1;return!0}function wd(c,t){const e=[];let i=!1,s=!1;const n=4;for(let r=0;r<=n;r++){const a={};for(;!c.isEOF()&&!(t.code===0||s);){switch(t.code){case 10:case 11:case 12:case 13:if(i){s=!0;continue}a.x=t.value,i=!0;break;case 20:case 21:case 22:case 23:a.y=t.value;break;case 30:case 31:case 32:case 33:a.z=t.value;break;default:return e}t=c.next()}bd(a)||e.push(a),i=!1,s=!1}return e}class vd{constructor(){g(this,"ForEntityName","3DFACE")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 70:if(e.value!==0){const s=Math.log2(e.value)-1;i.vertices.splice(s,0,1)}e=t.next();break;case 10:i.vertices=wd(t,e),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}class Md{constructor(){g(this,"ForEntityName","ARC")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.center=Td(t),e=t.lastReadGroup;break;case 40:i.radius=e.value,e=t.next();break;case 50:i.startAngle=Math.PI/180*e.value,e=t.next();break;case 51:i.endAngle=Math.PI/180*e.value,i.angleLength=i.endAngle-i.startAngle,e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Td(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Cd{constructor(){g(this,"ForEntityName","ATTDEF")}parseEntity(t,e){const i={type:e.value,xScale:1,textStyle:"STANDARD"};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 1:i.text=e.value,e=t.next();break;case 2:i.tag=e.value,e=t.next();break;case 3:i.prompt=e.value,e=t.next();break;case 7:i.textStyle=e.value,e=t.next();break;case 10:i.startPoint=Sa(t),e=t.lastReadGroup;break;case 11:i.endPoint=Sa(t),e=t.lastReadGroup;break;case 39:i.thickness=e.value,e=t.next();break;case 40:i.textHeight=e.value,e=t.next();break;case 41:i.xScale=e.value,e=t.next();break;case 50:i.rotation=e.value,e=t.next();break;case 51:i.obliqueAngle=e.value,e=t.next();break;case 70:i.invisible=!!(e.value&1),i.constant=!!(e.value&2),i.verificationRequired=!!(e.value&4),i.preset=!!(e.value&8),e=t.next();break;case 71:i.backwards=!!(e.value&2),i.mirrored=!!(e.value&4),e=t.next();break;case 72:i.horizontalJustification=e.value,i.halign=e.value,e=t.next();break;case 73:i.fieldLength=e.value,e=t.next();break;case 74:i.verticalJustification=e.value,i.valign=e.value,e=t.next();break;case 100:e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Sa(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Sd{constructor(){g(this,"ForEntityName","ATTRIB")}parseEntity(t,e){const i={type:e.value,xScale:1,textStyle:"STANDARD"};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 1:i.text=e.value,e=t.next();break;case 2:i.tag=e.value,e=t.next();break;case 3:i.prompt=e.value,e=t.next();break;case 7:i.textStyle=e.value,e=t.next();break;case 10:i.startPoint=Ea(t),e=t.lastReadGroup;break;case 11:i.endPoint=Ea(t),e=t.lastReadGroup;break;case 39:i.thickness=e.value,e=t.next();break;case 40:i.textHeight=e.value,e=t.next();break;case 41:i.xScale=e.value,e=t.next();break;case 50:i.rotation=e.value,e=t.next();break;case 51:i.obliqueAngle=e.value,e=t.next();break;case 70:i.invisible=!!(e.value&1),i.constant=!!(e.value&2),i.verificationRequired=!!(e.value&4),i.preset=!!(e.value&8),e=t.next();break;case 71:i.backwards=!!(e.value&2),i.mirrored=!!(e.value&4),e=t.next();break;case 72:i.horizontalJustification=e.value,i.halign=e.value,e=t.next();break;case 73:i.fieldLength=e.value,e=t.next();break;case 74:i.verticalJustification=e.value,i.valign=e.value,e=t.next();break;case 100:e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Ea(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Ed{constructor(){g(this,"ForEntityName","CIRCLE")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.center=Od(t),e=t.lastReadGroup;break;case 40:i.radius=e.value,e=t.next();break;case 50:i.startAngle=Math.PI/180*e.value,e=t.next();break;case 51:const s=Math.PI/180*e.value;s<i.startAngle?i.angleLength=s+2*Math.PI-i.startAngle:i.angleLength=s-i.startAngle,i.endAngle=s,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Od(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class _d{constructor(){g(this,"ForEntityName","DIMENSION")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 2:i.block=e.value,e=t.next();break;case 3:i.dimStyleName=e.value,e=t.next();break;case 10:i.anchorPoint=Jt(t),e=t.lastReadGroup;break;case 11:i.middleOfText=Jt(t),e=t.lastReadGroup;break;case 12:i.insertionPoint=Jt(t),e=t.lastReadGroup;break;case 13:i.linearOrAngularPoint1=Jt(t),e=t.lastReadGroup;break;case 14:i.linearOrAngularPoint2=Jt(t),e=t.lastReadGroup;break;case 15:i.diameterOrRadiusPoint=Jt(t),e=t.lastReadGroup;break;case 16:i.arcPoint=Jt(t),e=t.lastReadGroup;break;case 70:i.dimensionType=e.value,e=t.next();break;case 71:i.attachmentPoint=e.value,e=t.next();break;case 42:i.actualMeasurement=e.value,e=t.next();break;case 1:i.text=e.value,e=t.next();break;case 50:i.angle=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Jt(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Pd{constructor(){g(this,"ForEntityName","MULTILEADER")}parseEntity(t,e){const i={type:e.value};i.contextData={leaders:[]},e=t.next();const s=()=>{const o=i.contextData.leaders[i.contextData.leaders.length-1],l={vertices:[[]]};for(o.leaderLines.push(l);!t.isEOF();)switch(e.code){case 10:l.vertices[0].push(He(t)),e=t.lastReadGroup;break;case 305:return;default:e=t.next();break}},n=()=>{const o={leaderLines:[]};for(i.contextData.leaders.push(o);!t.isEOF();)switch(e.code){case 290:o.hasSetLastLeaderLinePoint=e.value,e=t.next();break;case 291:o.hasSetDoglegVector=e.value,e=t.next();break;case 10:o.lastLeaderLinePoint=He(t),e=t.lastReadGroup;break;case 11:o.doglegVector=He(t),e=t.lastReadGroup;break;case 90:o.leaderBranchIndex=e.value,e=t.next();break;case 40:o.doglegLength=e.value,e=t.next();break;case 303:return;case 304:s(),e=t.lastReadGroup;break;default:e=t.next();break}},r=()=>{for(;!t.isEOF();)switch(e.code){case 40:i.contextData.contentScale=e.value,e=t.next();break;case 10:i.contextData.contentBasePosition=He(t),e=t.lastReadGroup;break;case 145:i.contextData.landingGap=e.value,e=t.next();break;case 290:i.contextData.hasMText=e.value,e=t.next();break;case 304:i.contextData.defaultTextContents=e.value,e=t.next();break;case 11:i.contextData.textNormalDirection=He(t),e=t.lastReadGroup;break;case 12:i.contextData.textLocation=He(t),e=t.lastReadGroup;break;case 13:i.contextData.textDirection=He(t),e=t.lastReadGroup;break;case 140:i.contextData.arrowHeadSize=e.value,e=t.next();break;case 41:i.contextData.textHeight=e.value,e=t.next();break;case 42:i.contextData.textRotation=e.value,e=t.next();break;case 43:i.contextData.textWidth=e.value,e=t.next();break;case 44:e=t.next();break;case 45:i.contextData.textLineSpacingFactor=e.value,e=t.next();break;case 90:i.contextData.textColor=e.value,e=t.next();break;case 170:i.contextData.textLineSpacingStyle=e.value,e=t.next();break;case 171:i.contextData.textAttachment=e.value,e=t.next();break;case 172:i.contextData.textFlowDirection=e.value,e=t.next();break;case 141:i.contextData.textBackgroundScaleFactor=e.value,e=t.next();break;case 92:i.contextData.textBackgroundTransparency=e.value,e=t.next();break;case 291:i.contextData.textBackgroundColorOn=e.value,e=t.next();break;case 292:i.contextData.textBackgroundFillOn=e.value,e=t.next();break;case 293:i.contextData.textUseAutoHeight=e.value,e=t.next();break;case 173:i.contextData.textColumnType=e.value,e=t.next();break;case 142:i.contextData.textColumnWidth=e.value,e=t.next();break;case 143:i.contextData.textColumnGutterWidth=e.value,e=t.next();break;case 144:i.contextData.textColumnHeight=e.value,e=t.next();break;case 295:i.contextData.textUseWordBreak=e.value,e=t.next();break;case 296:i.contextData.hasBlock=e.value,e=t.next();break;case 341:i.contextData.blockContentId=e.value,e=t.next();break;case 14:i.contextData.blockContentNormalDirection=He(t),e=t.lastReadGroup;break;case 15:i.contextData.blockContentPosition=He(t),e=t.lastReadGroup;break;case 16:i.contextData.blockContentScale=e.value,e=t.next();break;case 46:i.contextData.blockContentRotation=e.value,e=t.next();break;case 93:i.contextData.blockContentColor=e.value,e=t.next();break;case 47:i.contextData.blockTransformationMatrix=Ad(t,47),e=t.lastReadGroup;break;case 110:i.contextData.planeOriginPoint=He(t),e=t.lastReadGroup;break;case 111:i.contextData.planeXAxisDirection=He(t),e=t.lastReadGroup;break;case 112:i.contextData.planeYAxisDirection=He(t),e=t.lastReadGroup;break;case 297:i.contextData.planeNormalReversed=e.value,e=t.next();break;case 301:return;case 302:n(),e=t.lastReadGroup;break;default:e=t.next();break}};return(()=>{for(;!t.isEOF();)switch(e.code){case 0:return;case 340:i.leaderStyleId=e.value,e=t.next();break;case 170:i.leaderLineType=e.value,e=t.next();break;case 91:i.leaderLineColor=e.value,e=t.next();break;case 341:i.leaderLineTypeId=e.value,e=t.next();break;case 171:i.leaderLineWeight=e.value,e=t.next();break;case 41:i.doglegLength=e.value,e=t.next();break;case 290:i.enableLanding=e.value,e=t.next();break;case 291:i.enableDogLeg=e.value,e=t.next();break;case 342:i.arrowHeadId=e.value,e=t.next();break;case 42:i.arrowHeadSize=e.value,e=t.next();break;case 172:i.contentType=e.value,e=t.next();break;case 173:i.textLeftAttachmentType=e.value,e=t.next();break;case 95:i.textLeftAttachmentType=e.value,e=t.next();break;case 174:i.textAngleType=e.value,e=t.next();break;case 175:i.textAlignmentType=e.value,e=t.next();break;case 343:i.textStyleId=e.value,e=t.next();break;case 92:i.textColor=e.value,e=t.next();break;case 292:i.enableFrameText=e.value,e=t.next();break;case 344:i.blockContentId=e.value,e=t.next();break;case 93:i.blockContentColor=e.value,e=t.next();break;case 10:i.blockContentScale=He(t),e=t.lastReadGroup;break;case 43:i.blockContentRotation=e.value,e=t.next();break;case 176:i.blockContentConnectionType=e.value,e=t.next();break;case 293:i.enableAnotationScale=e.value,e=t.next();break;case 94:i.arrowHeadIndex=e.value,e=t.next();break;case 177:i.blockAttributeIndex=e.value,e=t.next();break;case 44:i.blockAttributeWidth=e.value,e=t.next();break;case 302:i.blockAttributeTextString=e.value,e=t.next();break;case 294:i.textDirectionNegative=e.value,e=t.next();break;case 178:i.textAlignInIPE=e.value,e=t.next();break;case 179:i.textAttachmentPoint=e.value,e=t.next();break;case 271:i.textAttachmentDirectionMText=e.value,e=t.next();break;case 272:i.textAttachmentDirectionBottom=e.value,e=t.next();break;case 273:i.textAttachmentDirectionTop=e.value,e=t.next();break;case 300:r(),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}})(),i}}function He(c){const t={};let e=c.lastReadGroup||c.next(),i=!1,s=!1,n=!1,r=!1;for(;!c.isEOF();){const a=e.code,o=a>=10&&a<=16||a>=110&&a<=112,l=a>=20&&a<=26||a>=120&&a<=122,h=a>=30&&a<=36||a>=130&&a<=132;if(a===42&&!r)t.bulge=e.value,r=!0;else if(o&&!i)t.x=e.value,i=!0;else if(l&&!s)t.y=e.value,s=!0;else if(h&&!n)t.z=e.value,n=!0;else return t;e=c.next()}return t}function Ad(c,t){const e=[];let i=c.lastReadGroup||c.next();for(;!c.isEOF()&&(i.code>=t&&i.code<t+16);){e.push(i.value);i=c.next()}return e}class Id{constructor(){g(this,"ForEntityName","ELLIPSE")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.center=Gn(t),e=t.lastReadGroup;break;case 11:i.majorAxisEndPoint=Gn(t),e=t.lastReadGroup;break;case 40:i.axisRatio=e.value,e=t.next();break;case 41:i.startAngle=e.value,e=t.next();break;case 42:i.endAngle=e.value,e=t.next();break;case 210:i.extrusionDirection=Gn(t),e=t.lastReadGroup;break;case 2:i.name=e.value,e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Gn(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}var No=(c=>(c[c.Default=0]="Default",c[c.External=1]="External",c[c.Polyline=2]="Polyline",c[c.Derived=4]="Derived",c[c.Textbox=8]="Textbox",c[c.Outermost=16]="Outermost",c[c.MaxFlags=31]="MaxFlags",c))(No||{}),Ci=(c=>(c[c.Polyline=0]="Polyline",c[c.Line=1]="Line",c[c.Arc=2]="Arc",c[c.Ellipse=3]="Ellipse",c[c.Spline=4]="Spline",c))(Ci||{});function Si(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;if(e.code===i)if(t.x=e.value,!c.isEOF()&&c.hasNext())e=c.next();else return t;if(e.code===i+10)if(t.y=e.value,!c.isEOF()&&c.hasNext())e=c.next();else return t;return e.code===i+20&&(t.z=e.value,!c.isEOF()&&c.hasNext()&&(e=c.next())),t}function Bd(c){const t={type:0,points:[],isClosed:!0};let e=c.next();const i=e.value!==0;e=c.next(),t.isClosed=e.value!==0,e=c.next();const s=e.value;e=c.next();for(let r=0;r<s;r++){const a=Si(c);e=c.lastReadGroup,i&&(a.bulge=e.value,e=c.next()),t.points.push(a)}e=c.lastReadGroup,console.assert(e.code===97,"The reference count code 97 was expected.");const n=e.value;e=c.next();for(let r=0;r<n;r++)console.assert(e.code===330,"The reference handle code 330 was expected."),e=c.next();return{edges:[t],pathTypeFlag:-1}}function kd(c,t){const e=[];let i=t.next();for(;e.length<c;){if(i.code!==72){i=t.next();continue}switch(i.value){case 1:{i=t.next();const r={type:1,startPoint:Si(t),endPoint:Si(t)};i=t.lastReadGroup,e.push(r);break}case 2:{i=t.next();const r={type:2,center:Si(t),radius:0,startAngle:0,endAngle:0,bCounterclockwise:!1};i=t.lastReadGroup,r.radius=i.value,i=t.next(),r.startAngle=i.value,i=t.next(),r.endAngle=i.value,i=t.next(),r.bCounterclockwise=i.value!==0,i=t.next(),e.push(r);break}case 3:{i=t.next();const r={type:3,center:Si(t),majorAxisEndPoint:Si(t),minorRatio:0,startAngle:0,endAngle:0,bCounterclockwise:!1};i=t.lastReadGroup,r.minorRatio=i.value,i=t.next(),r.startAngle=i.value,i=t.next(),r.endAngle=i.value,i=t.next(),r.bCounterclockwise=i.value!==0,i=t.next(),e.push(r);break}case 4:{i=t.next();const r={type:4,degreeOfSplineCurve:i.value,bRational:!1,bPeriodic:!1,numKnots:0,numControlPoints:0,knotValues:[],controlPoints:[]};i=t.next(),r.bRational=i.value!==0,i=t.next(),r.bPeriodic=i.value!==0,i=t.next(),r.numKnots=i.value,i=t.next(),r.numControlPoints=i.value,i=t.next();for(let a=0;a<r.numKnots;a++)r.knotValues.push(i.value),i=t.next();for(let a=0;a<r.numControlPoints;a++){const o=i.value;i=t.next();const l=i.value;let h=1;i=t.next(),i.code===42&&(h=i.value,i=t.next()),r.controlPoints.push({x:o,y:l,z:h})}e.push(r);break}default:i=t.next();break}}i=t.lastReadGroup,console.assert(i.code===97,"The reference count code 97 was expected.");const s=i.value;i=t.next();for(let n=0;n<s;n++)console.assert(i.code===330,"The reference handle code 330 was expected."),i=t.next();return{edges:e,pathTypeFlag:-1}}function Dd(c,t){const e=[];let i=-1,s=t.next();for(;e.length<c;){let n;switch(s.code){case 92:if(i=s.value,i&2){if(n=Bd(t),n)n.pathTypeFlag=i,e.push(n);else throw new Error("[Hatch] Failed to parse hatch polyline boundary path !");s=t.lastReadGroup}else s=t.next();break;case 93:{const r=s.value;n=kd(r,t),n.pathTypeFlag=i,e.push(n),s=t.lastReadGroup;break}default:s=t.next();break}}return e}function Ld(c,t){if(c<=0){t.next();return}const e=[];let i=t.next();for(let s=0;s<c;s++){let n=0;const r={x:0,y:0},a={x:0,y:0};let o=-1;const l=[];for(;!t.isEOF()&&i.code!==0;){let h=!1;switch(i.code){case 53:n=i.value;break;case 43:r.x=i.value;break;case 44:r.y=i.value;break;case 45:a.x=i.value;break;case 46:a.y=i.value;break;case 79:o=i.value;break;case 49:l.push(i.value);break;default:h=!0}if(i=t.next(),h||l.length===o)break}o>=0&&e.push({angle:n,origin:r,delta:a,dashPattern:l})}return e}function Rd(c,t){const e=[];let i=t.next();for(;e.length<c&&!t.isEOF()&&i.code!==void 0&&i.code!==0;)switch(i.code){case 63:i=t.next();break;case 421:e.push(i.value),i=t.next();break;default:i=t.next();break}return e}class Fd{constructor(){g(this,"ForEntityName","HATCH")}parseEntity(t,e){const i={type:e.value,boundaryPaths:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 2:i.patternName=e.value,e=t.next();break;case 10:i.elevationX=e.value,e=t.next();break;case 20:i.elevationY=e.value,e=t.next();break;case 30:i.elevationZ=e.value,e=t.next();break;case 41:i.patternScale=e.value,e=t.next();break;case 47:i.pixelSize=e.value,e=t.next();break;case 52:i.patternAngle=e.value,e=t.next();break;case 63:i.patternFillColor=e.value,e=t.next();break;case 70:i.solidFill=(e.value&1)!==0,e=t.next();break;case 71:i.associativity=(e.value&1)!==0,e=t.next();break;case 73:i.annotatedBoundary=(e.value&1)!==0,e=t.next();break;case 75:i.style=e.value,e=t.next();break;case 76:i.patternType=e.value,e=t.next();break;case 78:i.patternLines=Ld(e.value,t),e=t.lastReadGroup;break;case 91:i.boundaryPathsCount=e.value,i.boundaryPaths=Dd(i.boundaryPathsCount,t),e=t.lastReadGroup;break;case 98:i.seedPointsCount=e.value,e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 450:i.isGradientColor=e.value===1,e=t.next();break;case 451:e=t.next();break;case 452:e=t.next();break;case 453:i.gradientColorCount=e.value,i.gradientColors=Rd(i.gradientColorCount,t),e=t.next();break;case 460:e=t.next();break;case 461:e=t.next();break;case 462:e=t.next();break;case 463:e=t.next();break;case 470:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}var hn=(c=>(c[c.ShowImage=1]="ShowImage",c[c.ShowImageWhenNotAlignedWithScreen=2]="ShowImageWhenNotAlignedWithScreen",c[c.UseClippingBoundary=4]="UseClippingBoundary",c[c.TransparencyIsOn=8]="TransparencyIsOn",c))(hn||{});let zd=class{constructor(){g(this,"ForEntityName","IMAGE")}parseEntity(t,e){const i={type:e.value,clippingBoundaryPath:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.position=Zi(t),e=t.lastReadGroup;break;case 11:i.uPixel=Zi(t),e=t.lastReadGroup;break;case 12:i.vPixel=Zi(t),e=t.lastReadGroup;break;case 13:i.imageSize=Zi(t),e=t.lastReadGroup;break;case 340:i.imageDefHandle=e.value,e=t.next();break;case 70:i.flags=e.value,e=t.next();break;case 280:i.clipping=e.value,e=t.next();break;case 281:i.brightness=e.value,e=t.next();break;case 282:i.contrast=e.value,e=t.next();break;case 283:i.fade=e.value,e=t.next();break;case 360:i.imageDefReactorHandle=e.value,e=t.next();break;case 71:i.clippingBoundaryType=e.value,e=t.next();break;case 91:i.countBoundaryPoints=e.value,e=t.next();break;case 14:i.clippingBoundaryPath.push(Zi(t)),e=t.lastReadGroup;break;case 290:i.clipMode=e.value,e=t.next();break;default:ee(i,e),e=t.next();break}return i}};function Zi(c){const t={};let e=c.lastReadGroup||c.next();for(;!c.isEOF();){switch(e.code){case 10:case 11:case 12:case 13:case 14:t.x=e.value;break;case 20:case 21:case 22:case 23:case 24:t.y=e.value;break;case 30:case 31:case 32:case 33:case 34:t.z=e.value;break;case 42:t.bulge=e.value;break;default:return t}e=c.next()}return t}class Vd{constructor(){g(this,"ForEntityName","INSERT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 2:i.block=e.value,e=t.next();break;case 66:i.attributesFollow=e.value!=0,e=t.next();break;case 41:i.xScale=e.value,e=t.next();break;case 42:i.yScale=e.value,e=t.next();break;case 43:i.zScale=e.value,e=t.next();break;case 10:i.position=Oa(t),e=t.lastReadGroup;break;case 50:i.rotation=e.value,e=t.next();break;case 70:i.columnCount=e.value,e=t.next();break;case 71:i.rowCount=e.value,e=t.next();break;case 44:i.columnSpacing=e.value,e=t.next();break;case 45:i.rowSpacing=e.value,e=t.next();break;case 210:i.extrusionDirection=Oa(t),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;case 1e3:i.zdysx?i.zdysx+=e.value:i.zdysx=e.value,e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Oa(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}function jd(c){switch(c){case 40:return"DIMSCALE";case 41:return"DIMASZ";case 42:return"DIMEXO";case 44:return"DIMEXE";case 75:return"DIMSE1";case 76:return"DIMSE2";case 77:return"DIMTAD";case 140:return"DIMTXT";case 144:return"DIMLFAC";case 147:return"DIMGAP";case 176:return"DIMCLRD";case 178:return"DIMCLRT";case 271:return"DIMDEC";case 341:return"DIMLDRBLK";default:return null}}class Ud{constructor(){g(this,"ForEntityName","LEADER")}parseEntity(t,e){const i={type:e.value,arrowFlag:1,vertices:[]};e=t.next();let s=!1;for(;!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.vertices.push(Nd(t)),e=t.lastReadGroup;break;case 3:i.dimensionStyle=e.value,e=t.next();break;case 40:i.textHeight=e.value,e=t.next();break;case 41:i.textWidth=e.value,e=t.next();break;case 71:i.arrowFlag=e.value,e=t.next();break;case 72:i.pathType=e.value,e=t.next();break;case 73:i.creationFlag=e.value,e=t.next();break;case 74:i.direction=e.value,e=t.next();break;case 75:i.hasHookline=e.value===1,e=t.next();break;case 1001:s=e.value==="ACAD",e=t.next();break;case 1070:if(s){const n=jd(e.value);n&&(e=t.next(),(e.code==1005||e.code==1040||e.code==1070)&&(n==="DIMLDRBLK"?i.arrowHeadBlockHandle=e.value:n==="DIMASZ"?i.arrowHeight=e.value:n==="DIMSCALE"?i.arrowHeadScale=e.value:n==="DIMCLRD"&&e.value>0&&(i.colorIndex=e.value,i.color=ki(Math.abs(e.value)))))}e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Nd(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Hd{constructor(){g(this,"ForEntityName","LINE")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.vertices.unshift(qn(t)),e=t.lastReadGroup;break;case 11:i.vertices.push(qn(t)),e=t.lastReadGroup;break;case 210:i.extrusionDirection=qn(t),e=t.lastReadGroup;break;case 100:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function qn(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}function Gd(c,t){if(!c||c<=0)throw Error("n must be greater than 0 verticies");const e=[];let i=!1,s=!1,n=t.lastReadGroup;const r={};for(;!t.isEOF()&&!(n.code===0||s);)switch(n.code){case 10:if(i){s=!0;continue}r.x=n.value,i=!0,n=t.next();break;case 20:r.y=n.value,n=t.next();break;case 30:r.z=n.value,n=t.next();break;case 40:r.startWidth=n.value,n=t.next();break;case 41:r.endWidth=n.value,n=t.next();break;case 42:n.value!=0&&(r.bulge=n.value),n=t.next();break;default:return i&&e.push(r),e}return e.push(r),i=!1,s=!1,e}class qd{constructor(){g(this,"ForEntityName","LWPOLYLINE")}parseEntity(t,e){const i={type:e.value,vertices:[]};let s=0;for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 38:i.elevation=e.value,e=t.next();break;case 39:i.thickness=e.value,e=t.next();break;case 70:i.shape=(e.value&1)===1,i.hasContinuousLinetypePattern=(e.value&128)===128,e=t.next();break;case 90:s=e.value,e=t.next();break;case 10:i.vertices.push(...Gd(s,t)),e=t.lastReadGroup;break;case 43:e.value!==0&&(i.constantWidth=e.value),e=t.next();break;case 210:i.extrusionDirectionX=e.value,e=t.next();break;case 220:i.extrusionDirectionY=e.value,e=t.next();break;case 230:i.extrusionDirectionZ=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}class Wd{constructor(){g(this,"ForEntityName","MTEXT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 3:const s=e.value;i.text?i.text+=s:i.text=s,e=t.next();break;case 1:const n=e.value;i.text?i.text+=n:i.text=n,e=t.next();break;case 10:i.position=_a(t),e=t.lastReadGroup;break;case 7:i.textStyle=e.value,e=t.next();break;case 44:i.lineSpaceFactor=e.value,e=t.next();break;case 11:i.directionVector=_a(t),i.rotation=void 0,e=t.lastReadGroup;break;case 40:i.height=e.value,e=t.next();break;case 41:const r=e.value;Math.abs(r)<1e-6?i.width=void 0:i.width=r,e=t.next();break;case 50:i.rotation=e.value,i.directionVector=void 0,e=t.next();break;case 71:i.attachmentPoint=e.value,e=t.next();break;case 72:i.drawingDirection=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function _a(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Yd{constructor(){g(this,"ForEntityName","OLE2FRAME")}parseEntity(t,e){const i={type:e.value,binaryData:""};for(e=t.next();e.value!=="OLE"&&e.code!==0;)switch(e.code){case 3:i.documentType=e.value,e=t.next();break;case 70:i.version=e.value,e=t.next();break;case 10:i.leftUpX=e.value,e=t.next();break;case 20:i.leftUpY=e.value,e=t.next();break;case 30:i.leftUpZ=e.value,e=t.next();break;case 11:i.rightDownX=e.value,e=t.next();break;case 21:i.rightDownY=e.value,e=t.next();break;case 31:i.rightDownZ=e.value,e=t.next();break;case 90:i.lengthOfBinaryData=e.value,e=t.next();break;case 310:i.binaryData+=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}class Xd{constructor(){g(this,"ForEntityName","POINT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.position=Pa(t),e=t.lastReadGroup;break;case 39:i.thickness=e.value,e=t.next();break;case 210:i.extrusionDirection=Pa(t),e=t.lastReadGroup;break;case 100:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Pa(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class Zd{constructor(){g(this,"ForEntityName","VERTEX")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.x=e.value,e=t.next();break;case 20:i.y=e.value,e=t.next();break;case 30:i.z=e.value,e=t.next();break;case 40:e=t.next();break;case 41:e=t.next();break;case 42:e.value!=0&&(i.bulge=e.value),e=t.next();break;case 70:i.curveFittingVertex=(e.value&1)!==0,i.curveFitTangent=(e.value&2)!==0,i.splineVertex=(e.value&8)!==0,i.splineControlPoint=(e.value&16)!==0,i.threeDPolylineVertex=(e.value&32)!==0,i.threeDPolylineMesh=(e.value&64)!==0,i.polyfaceMeshVertex=(e.value&128)!==0,e=t.next();break;case 50:e=t.next();break;case 71:i.faceA=e.value,e=t.next();break;case 72:i.faceB=e.value,e=t.next();break;case 73:i.faceC=e.value,e=t.next();break;case 74:i.faceD=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Kd(c,t){const e=new Zd,i=[];for(;!c.isEOF();)if(t.code===0){if(t.value==="VERTEX")i.push(e.parseEntity(c,t)),t=c.lastReadGroup;else if(t.value==="SEQEND"){$d(c,t);break}}return i}function $d(c,t){const e={type:t.value};for(t=c.next();!c.isEOF()&&t.code!==0;)if(t.code===101)for(;t.code!=0;)t=c.next();else ee(e,t),t=c.next();return e}class Jd{constructor(){g(this,"ForEntityName","POLYLINE")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:e=t.next();break;case 20:e=t.next();break;case 30:e=t.next();break;case 39:e=t.next(),i.thickness=e.value;break;case 40:e=t.next();break;case 41:e=t.next();break;case 70:i.shape=(e.value&1)!==0,i.includesCurveFitVertices=(e.value&2)!==0,i.includesSplineFitVertices=(e.value&4)!==0,i.is3dPolyline=(e.value&8)!==0,i.is3dPolygonMesh=(e.value&16)!==0,i.is3dPolygonMeshClosed=(e.value&32)!==0,i.isPolyfaceMesh=(e.value&64)!==0,i.hasContinuousLinetypePattern=(e.value&128)!==0,e=t.next();break;case 71:e=t.next();break;case 72:e=t.next();break;case 73:e=t.next();break;case 74:e=t.next();break;case 75:e=t.next();break;case 210:i.extrusionDirection=Qd(t),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i.vertices=Kd(t,e),i}}function Qd(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class e1{constructor(){g(this,"ForEntityName","REGION")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 70:i.modelerVersion=e.value,e=t.next();break;case 1:i.proprietaryData=e.value,e=t.next();break;case 3:i.proprietaryData+=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}class t1{constructor(){g(this,"ForEntityName","RAY")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.vertices.unshift(Aa(t)),e=t.lastReadGroup;break;case 11:i.directionVector=Aa(t),e=t.lastReadGroup;break;case 100:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Aa(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class i1{constructor(){g(this,"ForEntityName","SEQEND")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)e.code===-2||(ee(i,e),e=t.next());return i}}class s1{constructor(){g(this,"ForEntityName","SOLID")}parseEntity(t,e){const i={type:e.value,points:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.points[0]=Ki(t),e=t.lastReadGroup;break;case 11:i.points[1]=Ki(t),e=t.lastReadGroup;break;case 12:i.points[2]=Ki(t),e=t.lastReadGroup;break;case 13:i.points[3]=Ki(t),e=t.lastReadGroup;break;case 210:i.extrusionDirection=Ki(t),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Ki(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class n1{constructor(){g(this,"ForEntityName","SPLINE")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.controlPoints||(i.controlPoints=[]),i.controlPoints.push($i(t)),e=t.lastReadGroup;break;case 11:i.fitPoints||(i.fitPoints=[]),i.fitPoints.push($i(t)),e=t.lastReadGroup;break;case 12:i.startTangent=$i(t),e=t.lastReadGroup;break;case 13:i.endTangent=$i(t),e=t.lastReadGroup;break;case 40:i.knotValues||(i.knotValues=[]),i.knotValues.push(e.value),e=t.next();break;case 70:(e.value&1)!=0&&(i.closed=!0),(e.value&2)!=0&&(i.periodic=!0),(e.value&4)!=0&&(i.rational=!0),(e.value&8)!=0&&(i.planar=!0),(e.value&16)!=0&&(i.planar=!0,i.linear=!0),e=t.next();break;case 71:i.degreeOfSplineCurve=e.value,e=t.next();break;case 72:i.numberOfKnots=e.value,e=t.next();break;case 73:i.numberOfControlPoints=e.value,e=t.next();break;case 74:i.numberOfFitPoints=e.value,e=t.next();break;case 210:i.normalVector=$i(t),e=t.lastReadGroup;break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function $i(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}function r1(c,t,e){let i=c;for(;i.code!==304;)switch(i.code){case 301:i=e.next();break;case 93:i=e.next();break;case 90:i=e.next();break;case 1:t.text=i.value,i=e.next();break;case 94:i=e.next();break;case 300:t.attrText=i.value,i=e.next();break;case 302:t.text=i.value?i.value:t.text,i=e.next();break;default:console.log("[DXF ACAD_TABLE] ignore code: "+i.code+", value: "+i.value),i=e.next();break}}function Ia(c,t){const e={};for(c.code===171&&(e.cellType=c.value);!t.isEOF();){const i=t.next();if(i.code===0||i.code===171){t.lastReadGroup=i;break}if(i.code===301){r1(i,e,t);continue}switch(i.code){case 172:e.flagValue=i.value;break;case 173:e.mergedValue=i.value;break;case 174:e.autoFit=i.value;break;case 175:e.borderWidth=i.value;break;case 176:e.borderHeight=i.value;break;case 177:e.overrideFlag=i.value;break;case 178:e.virtualEdgeFlag=i.value;break;case 145:e.rotation=i.value;break;case 140:e.textHeight=i.value;break;case 170:e.attachmentPoint=i.value;break;case 91:e.extendedCellFlags=i.value;break;case 7:e.textStyle=i.value;break;case 340:e.blockTableRecordId=i.value;break;case 345:e.fieldObjetId=i.value;break;case 146:e.blockScale=i.value;break;case 179:e.blockAttrNum=i.value;break;case 1:e.text=i.value;break;case 302:e.attrText=i.value;break}}return e}class a1{constructor(){g(this,"ForEntityName","ACAD_TABLE")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.startPoint=Ba(t),e=t.lastReadGroup;break;case 11:i.directionVector=Ba(t),e=t.lastReadGroup;break;case 90:i.tableValue=e.value,e=t.next();break;case 91:i.rowCount=e.value,e=t.next();break;case 92:i.columnCount=e.value,e=t.next();break;case 93:i.overrideFlag=e.value,e=t.next();break;case 94:i.borderColorOverrideFlag=e.value,e=t.next();break;case 95:i.borderLineWeightOverrideFlag=e.value,e=t.next();break;case 96:i.borderVisibilityOverrideFlag=e.value,e=t.next();break;case 141:i.rowHeightArr?i.rowHeightArr.push(e.value):i.rowHeightArr=[e.value],e=t.next();break;case 142:i.columnWidthArr?i.columnWidthArr.push(e.value):i.columnWidthArr=[e.value],e=t.next();break;case 280:i.version=e.value,e=t.next();break;case 342:i.tableStyleId=e.value,e=t.next();break;case 343:i.blockRecordHandle=e.value,e=t.next();break;case 171:i.cells?i.cells.push(Ia(e,t)):i.cells=[Ia(e,t)],e=t.lastReadGroup;break;default:ee(i,e),e=t.next();break}return i}}function Ba(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class o1{constructor(){g(this,"ForEntityName","TEXT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.startPoint=ka(t),e=t.lastReadGroup;break;case 11:i.endPoint=ka(t),e=t.lastReadGroup;break;case 40:i.textHeight=e.value,e=t.next();break;case 41:i.xScale=e.value,e=t.next();break;case 50:i.rotation=e.value,e=t.next();break;case 1:i.text=e.value,e=t.next();break;case 72:i.halign=e.value,e=t.next();break;case 73:i.valign=e.value,e=t.next();break;case 7:i.textStyle=e.value,e=t.next();break;case 71:i.mirrored=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function ka(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class l1{constructor(){g(this,"ForEntityName","VIEWPORT")}parseEntity(t,e){const i={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 68:i.viewportStatus=e.value,e=t.next();break;case 40:i.width_paperSpace=e.value,e=t.next();break;case 41:i.height_paperSpace=e.value,e=t.next();break;case 69:i.viewportId=e.value,e=t.next();break;case 10:i.centerPoint=ut(t),e=t.lastReadGroup;break;case 12:i.centerPoint_dcs=ut(t),e=t.lastReadGroup;break;case 13:i.snapBasePoint_dcs=ut(t),e=t.lastReadGroup;break;case 14:i.snapSpacing_dcs=ut(t),e=t.lastReadGroup;break;case 15:i.gridSpacing_dcs=ut(t),e=t.lastReadGroup;break;case 16:i.viewDirection=ut(t),e=t.lastReadGroup;break;case 17:i.viewTarget=ut(t),e=t.lastReadGroup;break;case 42:i.perspectiveLens=e.value,e=t.next();break;case 43:i.frontClippingPlaneZ=e.value,e=t.next();break;case 44:i.backClippingPlaneZ=e.value,e=t.next();break;case 45:i.viewHeight=e.value,e=t.next();break;case 50:i.snapAngle=e.value,e=t.next();break;case 51:i.viewTwistAngle=e.value,e=t.next();break;case 72:i.circleZoomPercent=e.value,e=t.next();break;case 331:i.frozenLayerHandles=i.frozenLayerHandles||[],i.frozenLayerHandles.push(e.value),e=t.next();break;case 90:i.viewportStatusFlags=e.value,e=t.next();break;case 340:i.viewportClippingBoundaryhandleId=e.value,e=t.next();break;case 1:i.plotStyleSheetName=e.value,e=t.next();break;case 281:i.renderMode=e.value,e=t.next();break;case 71:i.viewportFlag_ucs=e.value,e=t.next();break;case 74:i.ucsIcon=e.value,e=t.next();break;case 110:i.ucsOrigin=ut(t),e=t.lastReadGroup;break;case 111:i.ucsXAxis=ut(t),e=t.lastReadGroup;break;case 112:i.ucsYAxis=ut(t),e=t.lastReadGroup;break;case 345:i.ucsTableRecordHandle=e.value,e=t.next();break;case 346:i.baseUcsTableRecordHandle=e.value,e=t.next();break;case 79:i.orthographicType=e.value,e=t.next();break;case 146:i.elevation=e.value,e=t.next();break;case 170:i.shadePlotMode=e.value,e=t.next();break;case 61:i.frequency=e.value,e=t.next();break;case 292:i.lightingFlag=e.value,e=t.next();break;case 282:i.lightingType=e.value,e=t.next();break;case 141:i.viewBrightness=e.value,e=t.next();break;case 142:i.viewContrast=e.value,e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function ut(c){const t={};let e=c.lastReadGroup||c.next();for(;!c.isEOF();){switch(e.code){case 10:case 12:case 13:case 14:case 15:case 16:case 17:case 110:case 111:case 112:t.x=e.value;break;case 20:case 22:case 23:case 24:case 25:case 26:case 27:case 120:case 121:case 122:t.y=e.value;break;case 30:case 32:case 33:case 34:case 35:case 36:case 37:case 130:case 131:case 132:t.z=e.value;break;case 42:t.bulge=e.value;break;default:return t}e=c.next()}return t}class c1{constructor(){g(this,"ForEntityName","XLINE")}parseEntity(t,e){const i={type:e.value,vertices:[]};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 10:i.vertices.unshift(Da(t)),e=t.lastReadGroup;break;case 11:i.directionVector=Da(t),e=t.lastReadGroup;break;case 100:e=t.next();break;case 101:for(;e.code!=0;)e=t.next();break;default:ee(i,e),e=t.next();break}return i}}function Da(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class h1{constructor(){g(this,"ForObjectName","DICTIONARY")}parseObject(t,e){const s={type:e.value},n=[],r=[];for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 280:s.isHardOwner=e.value===1,e=t.next();break;case 281:s.cloningFlag=e.value,e=t.next();break;case 3:n.push(e.value),e=t.next();break;case 350:r.push(e.value),e=t.next();break;case 360:r.push(e.value),e=t.next();break;case 100:e=t.next();break;case 102:e=t.next();break;default:zi(s,e),e=t.next();break}if(n.length!==r.length)throw new Error("The number of Dictionary entries does not match !");return s.entries={},n.forEach((a,o)=>{s.entries[r[o]]=a}),s}}class d1{constructor(){g(this,"ForObjectName","IMAGEDEF")}parseObject(t,e){const s={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 90:s.classVersion=e.value,e=t.next();break;case 1:s.filename=e.value,e=t.next();break;case 10:s.imageSize=La(t),e=t.next();break;case 11:s.pixelSize=La(t),e=t.next();break;case 280:s.loaded=e.value,e=t.next();break;case 281:s.resolutionUnits=e.value,e=t.next();break;default:zi(s,e),e=t.next();break}return s}}function La(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class u1{constructor(){g(this,"ForObjectName","LAYOUT")}parseObject(t,e){const s={type:e.value};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 100:e=t.next();break;case 1:s.layoutName=e.value,e=t.next();break;case 70:s.flag=e.value,e=t.next();break;case 71:s.tabOrder=e.value,e=t.next();break;case 76:s.orthographicType=e.value,e=t.next();break;case 10:s.minLimit=kt(t),e=t.lastReadGroup;break;case 11:s.maxLimit=kt(t),e=t.lastReadGroup;break;case 12:s.basePoint=kt(t),e=t.lastReadGroup;break;case 13:s.origin=kt(t),e=t.lastReadGroup;break;case 14:s.minExtent=kt(t),e=t.lastReadGroup;break;case 15:s.maxExtent=kt(t),e=t.lastReadGroup;break;case 16:s.XAxis=kt(t),e=t.lastReadGroup;break;case 17:s.YAxis=kt(t),e=t.lastReadGroup;break;case 146:s.elevation=e.value,e=t.next();break;case 330:s.viewportHandle=e.value,e=t.next();break;default:zi(s,e),e=t.next();break}return s.blockTableHandle=s.ownerHandle,s}}function kt(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class f1{constructor(){g(this,"ForObjectName","SORTENTSTABLE")}parseObject(t,e){const s={type:e.value};let n=!1;s.sortEntsObject={},s.sortEntsObject.entityHandles=[];let r=[];for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 5:n?(r.push(e.value),s.sortEntsObject.entityHandles.push(r),r=[]):s.handle=e.value,e=t.next();break;case 100:e=t.next(),n=!0;break;case 102:e=t.next();break;case 330:n?s.sortEntsObject.ownerHandle=e.value:s.ownerHandle=e.value,e=t.next();break;case 331:r.push(e.value),e=t.next();break;default:zi(s,e),e=t.next();break}return s}}class p1{constructor(){g(this,"ForObjectName","SPATIAL_FILTER")}parseObject(t,e){const s={type:e.value};s.vertices=[];let n,r;for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 11:s.origin=dn(t),e=t.lastReadGroup;break;case 70:s.numberOfPointsOnClipBoundary=e.value,s.numberOfPointsOnClipBoundary===2?(e=t.next(),n=dn(t),e=t.lastReadGroup,r=dn(t),e=t.lastReadGroup,s.vertices.push(n,{x:r.x,y:n.y},r,{x:n.x,y:r.y},n)):s.numberOfPointsOnClipBoundary>2?(s.vertices=m1(s.numberOfPointsOnClipBoundary,t),e=t.lastReadGroup):e=t.next();break;case 71:s.clipBoundaryVisible=e.value===1,e=t.next();break;case 72:s.frontClippingPlaneFlag=e.value===1,e=t.next(),s.frontClippingPlaneFlag&&e.code===40&&(s.frontClippingPlaneDistance=e.value,e=t.next());break;case 73:s.backClippingPlaneFlag=e.value===1,e=t.next(),s.backClippingPlaneFlag&&e.code===41&&(s.backClippingPlaneDistance=e.value,e=t.next());break;case 100:e=t.next();break;case 102:e=t.next();break;case 210:s.extrusionDirectionX=e.value,e=t.next();break;case 220:s.extrusionDirectionY=e.value,e=t.next();break;case 230:s.extrusionDirectionZ=e.value,e=t.next();break;case 40:s.invertBlockMatrix=Ra(t,40),s.matrix=Ra(t,40),e=t.lastReadGroup;break;default:zi(s,e),e=t.next();break}return s}}function m1(c,t){t.next();const e=[];for(;e.length<c;)e.push(dn(t));return e}function Ra(c,t){let e=c.lastReadGroup;const i=[];for(let s=0;s<12;s++){if(e.code!==t)throw new Error("Expected code for matrix value to be "+t+" but got "+e.code);i.push(e.value),e=c.next()}return i}function dn(c){const t={};let e=c.lastReadGroup||c.next();const i=e.code;for(;!c.isEOF();){if(e.code===i)t.x=e.value;else if(e.code===i+10)t.y=e.value;else if(e.code===i+20)t.z=e.value;else if(e.code===42)t.bulge=e.value;else return t;e=c.next()}return t}class g1{constructor(){g(this,"ForObjectName","XRECORD")}parseObject(t,e){const s={type:e.value,binaryData:""};for(e=t.next();!t.isEOF()&&e.code!==0;)switch(e.code){case 100:e=t.next();break;case 280:s.cloningFlag=e.value,e=t.next();break;case 310:s.binaryData+=e.value,e=t.next();break;case 311:e=t.next();break;default:zi(s,e),e=t.next();break}return s}}function y1(c){c.registerEntityHandler(vd),c.registerEntityHandler(Md),c.registerEntityHandler(Cd),c.registerEntityHandler(Sd),c.registerEntityHandler(Ed),c.registerEntityHandler(_d),c.registerEntityHandler(Pd),c.registerEntityHandler(Id),c.registerEntityHandler(Fd),c.registerEntityHandler(zd),c.registerEntityHandler(Vd),c.registerEntityHandler(Ud),c.registerEntityHandler(Hd),c.registerEntityHandler(qd),c.registerEntityHandler(Wd),c.registerEntityHandler(Yd),c.registerEntityHandler(Xd),c.registerEntityHandler(Jd),c.registerEntityHandler(e1),c.registerEntityHandler(t1),c.registerEntityHandler(i1),c.registerEntityHandler(s1),c.registerEntityHandler(n1),c.registerEntityHandler(a1),c.registerEntityHandler(o1),c.registerEntityHandler(l1),c.registerEntityHandler(c1)}function x1(c){c.registerObjectHandler(h1),c.registerObjectHandler(d1),c.registerObjectHandler(u1),c.registerObjectHandler(f1),c.registerObjectHandler(p1),c.registerObjectHandler(g1)}function b1(c){const t=new Uint8Array(c,0,18);let e="";for(let i=0;i<18;i++)e+=String.fromCharCode(t[i]);return e==="AutoCAD Binary DXF"}class Ho{constructor(t){g(this,"_entityHandlers",{});g(this,"_objectHandlers",{});g(this,"_layoutBlocks",{});g(this,"unhandledSections",{});g(this,"unhandledObjects",{});g(this,"unhandledEntities",{});g(this,"unsupportedLineTypes",{});g(this,"encoding");this.encoding=t,y1(this),x1(this)}parse(t){if(typeof t=="string"){const e=this.splitByLineSeparator(t),i=new Ca(e);return this._parse(i)}else{let e;if(b1(t))e=new gd(t);else{const i=new TextDecoder(this.encoding).decode(t),s=Date.now(),n=this.splitByLineSeparator(i);console.info("[DxfParser] string.split took "+(Date.now()-s)/1e3+"s, it is avoidable by using dxf in binary."),e=new Ca(n)}return this._parse(e)}}registerEntityHandler(t){const e=new t;this._entityHandlers[e.ForEntityName]=e}registerObjectHandler(t){const e=new t;this._objectHandlers[e.ForObjectName]=e}parseSync(t){return this.parse(t)}parseStream(t){let e="";const i=this;return new Promise((s,n)=>{t.on("data",r=>{e+=r}),t.on("end",()=>{try{s(i.parse(e))}catch(r){n(r)}}),t.on("error",r=>{n(r)})})}_parse(t){const e={};let i=0;if(!t.hasNext())throw Error("Empty file");const s=this;let n;function r(){for(n=t.next();n.code===999;)n=t.next();for(;!t.isEOF();)if(n.code===0&&n.value==="SECTION"){if(n=t.next(),n.code!==2){console.error("Unexpected code %s after 0:SECTION",Go(n)),n=t.next();continue}if(n.value==="HEADER")P.trace("> HEADER"),e.header=a(),P.trace("<");else if(n.value==="TABLES")P.trace("> TABLES"),e.tables=h(),P.trace("<");else if(n.value==="BLOCKS")P.trace("> BLOCKS"),e.blocks=o(),P.trace("<");else if(n.value==="ENTITIES")P.trace("> ENTITIES"),e.entities=E(!1),P.trace("<");else if(n.value==="OBJECTS")P.trace("> OBJECTS"),e.objects=M(),P.trace("<");else if(n.value==="EOF")P.trace("EOF");else{const T=n.value;s.unhandledSections[T]?s.unhandledSections[T]++:s.unhandledSections[T]=1}}else n=t.next();s.unhandledSections={},s.unhandledEntities={},s.unhandledObjects={},s.unsupportedLineTypes={}}function a(){let T=null,v=null;const C={};for(n=t.next();;){if(Ge(n,0,"ENDSEC")){T&&(C[T]=v);break}else n.code===9?(T&&(C[T]=v),T=n.value):n.code===10?v={x:n.value}:n.code===20?v.y=n.value:n.code===30?v.z=n.value:v=n.value;n=t.next()}return n=t.next(),C}function o(){const T={};for(n=t.next();n.value!=="EOF"&&!Ge(n,0,"ENDSEC");)if(Ge(n,0,"BLOCK")){P.trace("block {");const v=l();P.trace("}"),O(v),v.name?T[v.name]=v:console.error("[DxfParser] Block with handle '"+v.handle+"' is missing a name, ignored!")}else vt(n),n=t.next();return T}function l(){const T={};for(n=t.next();n.value!=="EOF";){switch(n.code){case 1:T.xrefPath=n.value,n=t.next();break;case 2:T.name=n.value,n=t.next();break;case 3:T.name2=n.value,n=t.next();break;case 4:T.description=n.value,n=t.next();break;case 5:T.handle=n.value,n=t.next();break;case 8:T.layer=n.value,n=t.next();break;case 10:T.position=Xe(t),n=t.lastReadGroup;break;case 67:T.paperSpace=!!(n.value&&n.value===1),n=t.next();break;case 70:T.blockType=n.value,n=t.next();break;case 100:n=t.next();break;case 330:T.ownerHandle=n.value,n=t.next();break;case 0:if(n.value==="ENDBLK")break;T.entities=E(!0);break;default:vt(n),n=t.next();break}if(Ge(n,0,"ENDBLK")){n=t.next();break}}return T}function h(){const T={};for(n=t.next();n.value!=="EOF"&&!Ge(n,0,"ENDSEC");)Ge(n,0,"TABLE")?(n=t.next(),x[n.value]?(P.trace(n.value+" Table {"),T[x[n.value].tableName]=u(n),P.trace("}")):P.trace("Unhandled Table "+n.value)):n=t.next();return n=t.next(),T}const d="ENDTAB";function u(T){const v=x[T.value],C={};let _=0;for(n=t.next();!Ge(n,0,d);)switch(n.code){case 5:C.handle=n.value,n=t.next();break;case 330:C.ownerHandle=n.value,n=t.next();break;case 100:n.value==="AcDbSymbolTable"||vt(n),n=t.next();break;case 70:_=n.value,n=t.next();break;case 0:n.value===v.dxfSymbolName?C[v.tableRecordsProperty]=v.parseTableRecords():(vt(n),n=t.next());break;default:vt(n),n=t.next();break}const A=C[v.tableRecordsProperty];if(A){const I=(()=>{if(A.constructor===Array)return A.length;if(typeof A=="object")return Object.keys(A).length})();_!==I&&console.warn("[DxfParser] Parsed "+I+" "+v.dxfSymbolName+"s but expected "+_)}return n=t.next(),C}function f(){const T=[];let v={};for(P.trace("Viewport {"),n=t.next();!Ge(n,0,d);)switch(n.code){case 2:v.name=n.value,n=t.next();break;case 10:v.lowerLeftCorner=Xe(t),n=t.lastReadGroup;break;case 11:v.upperRightCorner=Xe(t),n=t.lastReadGroup;break;case 12:v.center=Xe(t),n=t.lastReadGroup;break;case 13:v.snapBasePoint=Xe(t),n=t.lastReadGroup;break;case 14:v.snapSpacing=Xe(t),n=t.lastReadGroup;break;case 15:v.gridSpacing=Xe(t),n=t.lastReadGroup;break;case 16:v.viewDirectionFromTarget=Xe(t),n=t.lastReadGroup;break;case 17:v.viewTarget=Xe(t),n=t.lastReadGroup;break;case 40:v.viewHeight=n.value,n=t.next();break;case 41:v.aspectRatio=n.value,n=t.next();break;case 42:v.lensLength=n.value,n=t.next();break;case 43:v.frontClippingPlane=n.value,n=t.next();break;case 44:v.backClippingPlane=n.value,n=t.next();break;case 45:v.viewHeight=n.value,n=t.next();break;case 50:v.snapRotationAngle=n.value,n=t.next();break;case 51:v.viewTwistAngle=n.value,n=t.next();break;case 79:v.orthographicType=n.value,n=t.next();break;case 110:v.ucsOrigin=Xe(t),n=t.lastReadGroup;break;case 111:v.ucsXAxis=Xe(t),n=t.lastReadGroup;break;case 112:v.ucsYAxis=Xe(t),n=t.lastReadGroup;break;case 281:v.renderMode=n.value,n=t.next();break;case 282:v.defaultLightingType=n.value,n=t.next();break;case 292:v.defaultLightingOn=n.value,n=t.next();break;case 330:v.ownerHandle=n.value,n=t.next();break;case 63:case 421:case 431:v.ambientColor=n.value,n=t.next();break;case 0:n.value==="VPORT"&&(P.trace("}"),T.push(v),P.trace("Viewport {"),v={},n=t.next());break;default:vt(n),n=t.next();break}return P.trace("}"),T.push(v),T}function m(){const T={};let v={},C=0,_="",A=!1;for(P.trace("LType {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 2:v.name=n.value.toUpperCase(),_=v.name,n=t.next();break;case 3:v.description=n.value,n=t.next();break;case 9:n=t.next();break;case 40:v.patternLength=n.value,n=t.next();break;case 44:n=t.next();break;case 45:n=t.next();break;case 46:n=t.next();break;case 49:let I=n.value;A&&(I=Math.abs(I),A=!1),v.pattern.push(I),n=t.next();break;case 70:n=t.next();break;case 73:C=n.value,C>0&&(v.pattern=[]),n=t.next();break;case 74:n.value!==0&&(A=!0,s.unsupportedLineTypes[v.name]?s.unsupportedLineTypes[v.name]++:s.unsupportedLineTypes[v.name]=1),n=t.next();break;case 75:n=t.next();break;case 0:P.trace("}"),C>0&&C!==v.pattern.length&&console.warn("[DxfParser] lengths do not match on LTYPE pattern"),T[_]=v,v={},P.trace("LType {"),n=t.next();break;default:n=t.next();break}return P.trace("}"),T[_]=v,T}function b(){const T={};let v={},C;for(P.trace("Layer {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 2:v.name=n.value,C=n.value,n=t.next();break;case 5:v.handle=n.value,n=t.next();break;case 62:v.visible=n.value>=0,v.colorIndex=Math.abs(n.value),v.color=ki(v.colorIndex),n=t.next();break;case 70:v.flag=n.value,v.frozen=(v.flag&1)>0,n=t.next();break;case 420:v.color=Math.abs(n.value),n=t.next();break;case 6:v.lineType=n.value.toUpperCase(),n=t.next();break;case 370:v.lineweight=n.value,n=t.next();break;case 0:n.value==="LAYER"&&(P.trace("}"),C&&(T[C]=v),P.trace("Layer {"),v={},C=void 0,n=t.next());break;default:vt(n),n=t.next();break}return P.trace("}"),C&&(T[C]=v),T}function y(){const T={};let v={},C;for(P.trace("Style {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 2:v.styleName=n.value,C=n.value,n=t.next();break;case 3:v.fontFile=n.value,n=t.next();break;case 4:v.bigFontFile=n.value,n=t.next();break;case 5:v.handle=n.value,n=t.next();break;case 40:v.textHeight=n.value,n=t.next();break;case 41:v.xScale=n.value,n=t.next();break;case 42:v.priorTextHeight=n.value,n=t.next();break;case 50:v.rotation=n.value,n=t.next();break;case 70:n=t.next();break;case 71:v.mirrorType=n.value,n=t.next();break;case 330:v.ownerHandle=n.value,n=t.next();break;case 0:n.value==="STYLE"&&(P.trace("}"),C&&(T[C]=v),P.trace("Style {"),v={},C=void 0,n=t.next());break;default:n=t.next();break}return P.trace("}"),C&&(T[C]=v),T}function S(){const T={};let v={},C;for(P.trace("DimStyle {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 2:v.styleName=n.value,C=n.value,n=t.next();break;case 40:v.DIMSCALE=n.value,n=t.next();break;case 41:v.DIMASZ=n.value,n=t.next();break;case 42:v.DIMEXO=n.value,n=t.next();break;case 44:v.DIMEXE=n.value,n=t.next();break;case 75:v.DIMSE1=n.value,n=t.next();break;case 76:v.DIMSE2=n.value,n=t.next();break;case 77:v.DIMTAD=n.value,n=t.next();break;case 140:v.DIMTXT=n.value,n=t.next();break;case 144:v.DIMLFAC=n.value,n=t.next();break;case 147:v.DIMGAP=n.value,n=t.next();break;case 176:v.DIMCLRD=n.value,n=t.next();break;case 178:v.DIMCLRT=n.value,n=t.next();break;case 271:v.DIMDEC=n.value,n=t.next();break;case 341:v.DIMLDRBLK=n.value,n=t.next();break;case 70:n=t.next();break;case 0:n.value==="DIMSTYLE"&&(P.trace("}"),C&&(T[C]=v),P.trace("DimStyle {"),v={},C=void 0,n=t.next());break;default:n=t.next();break}return P.trace("}"),C&&(T[C]=v),T}function w(){const T={};let v={},C;for(P.trace("BlockRecord {"),n=t.next();!Ge(n,0,"ENDTAB");)switch(n.code){case 5:v.handle=n.value,n=t.next();break;case 330:v.ownerHandle=n.value,n=t.next();break;case 2:v.blockName=n.value,C=v.blockName,n=t.next();break;case 340:v.layoutHandle=n.value,n=t.next();break;case 70:v.blockInsertUnits=n.value,n=t.next();break;case 280:v.blockExplodability=n.value,n=t.next();break;case 281:v.blockScalability=n.value,n=t.next();break;case 310:v.bitmap=n.value,n=t.next();break;case 0:if(n.value==="BLOCK_RECORD"){P.trace("}"),C&&(T[C]=v);const A=v.layoutHandle;C&&A&&A.length>0&&A!=="0"&&(s._layoutBlocks[A]=v),P.trace("BlockRecord {"),v={},C=void 0,n=t.next()}else vt(n),n=t.next();break;default:vt(n),n=t.next();break}P.trace("}"),C&&(T[C]=v);const _=v.layoutHandle;return C&&_&&_.length>0&&_!=="0"&&(s._layoutBlocks[_]=v),T}const x={VPORT:{tableRecordsProperty:"viewports",tableName:"viewport",dxfSymbolName:"VPORT",parseTableRecords:f},LTYPE:{tableRecordsProperty:"lineTypes",tableName:"lineType",dxfSymbolName:"LTYPE",parseTableRecords:m},LAYER:{tableRecordsProperty:"layers",tableName:"layer",dxfSymbolName:"LAYER",parseTableRecords:b},BLOCK_RECORD:{tableRecordsProperty:"blockRecords",tableName:"blockRecord",dxfSymbolName:"BLOCK_RECORD",parseTableRecords:w},STYLE:{tableRecordsProperty:"styles",tableName:"style",dxfSymbolName:"STYLE",parseTableRecords:y},DIMSTYLE:{tableRecordsProperty:"dimStyles",tableName:"dimStyle",dxfSymbolName:"DIMSTYLE",parseTableRecords:S}};function E(T){const v=[],C=T?"ENDBLK":"ENDSEC";for(T||(n=t.next());;)if(n.code===0){if(n.value===C)break;const _=s._entityHandlers[n.value];if(_!=null){P.trace(n.value+" {");const A=_.parseEntity(t,n);A&&(A.layer||(A.layer="0"),A.colorIndex===void 0&&(A.colorIndex=256),A.lineType||(A.lineType="BYLAYER"),n=t.lastReadGroup,P.trace("}"),O(A),v.push(A))}else{const A=n.value;s.unhandledEntities[A]||(s.unhandledEntities[A]=0),s.unhandledEntities[A]++,n=t.next();continue}}else n=t.next();return C==="ENDSEC"&&(n=t.next()),v}function M(){const T={},v="ENDSEC";for(n=t.next();n.value!=="EOF";)if(n.code===0){if(n.value===v)break;const C=s._objectHandlers[n.value];if(C!=null){P.trace(n.value+" {");const _=C.parseObject(t,n),A=n.value;n=t.lastReadGroup,P.trace("}"),O(_),T[A]||(T[A]=[]),T[A].push(_)}else{const _=n.value;s.unhandledObjects[_]||(s.unhandledObjects[_]=0),s.unhandledObjects[_]++,n=t.next();continue}}else n=t.next();return n=t.next(),T.LAYOUT&&(Object.keys(s._layoutBlocks).length!==T.LAYOUT.length&&console.warn("[DxfParser] The number of layout and block associations does not match!"),T.LAYOUT.forEach(C=>{s._layoutBlocks[C.handle]&&(C.associatedBlockName=s._layoutBlocks[C.handle].blockName)}),T.LAYOUT.sort((C,_)=>C.tabOrder-_.tabOrder)),T}function O(T){if(!T)throw new TypeError("entity cannot be undefined or null");T.handle||(T.handle=(i++).toString())}return r(),e}splitByLineSeparator(t){const e=[];let i=0;for(let s=0,n=t.length;s<n;++s){const r=t[s];if(r==="\r"||r===`
792
792
  `){let a=t.substring(i,s);a&&a.indexOf("M+")>-1&&(a=hd(a)),a&&(a=a),e.push(a),r==="\r"&&t[s+1]===`
793
793
  `&&s++,i=s+1}}return e.push(t.substring(i,t.length)),e}}function Ge(c,t,e){return c.code===t&&c.value===e}function vt(c){P.trace("unhandled group "+Go(c))}function Go(c){return c.code+":"+c.value}const qo="0.4.0",Wo="VERSION",w1=()=>window.localStorage.getItem(Wo),v1=()=>{window.localStorage.setItem(Wo,qo)},M1=()=>w1()!==qo?(v1(),!0):!1,si=class si{constructor(){g(this,"DATABASE_NAME","x_viewer");g(this,"DEFAULT_TABLES",[{name:"dxf_data",options:{keyPath:"dxfDataId",autoIncrement:!1}},{name:"fonts",options:{keyPath:"fileName",autoIncrement:!0}}]);g(this,"db");g(this,"tables");this.db=void 0,this.tables=this.DEFAULT_TABLES}static instance(){return!si._instance&&(si._instance=new si),si._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(),M1()&&await this.deleteDataBase(this.DATABASE_NAME),t=await this.getUpgradedDB(t)),t.onclose=()=>{this.db=void 0,P.debug("[DB] Db "+t.name+" is closed.")},t.onerror=e=>{this.db=void 0,P.debug("[DB] Db "+t.name+" encountered error.",e)},t.onabort=e=>{this.db=void 0,P.debug("[DB] Db "+t.name+" aborted.",e)},t.onversionchange=e=>{P.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=n=>{P.debug(n),i(n)},s.onsuccess=n=>{const r=n.target;P.debug("[DB] Db "+t+" delete old version "+n.oldVersion+"."),e(r)}})}async getDB(t){return new Promise((e,i)=>{const s=window.indexedDB.open(t);s.onerror=i,s.onsuccess=n=>{const r=n.target.result;P.debug("[DB] Db "+r.name+" opened (version "+r.version+")."),e(r)}})}async getUpgradedDB(t){return new Promise((e,i)=>{P.debug("[DB] Upgrading db "+t.name+" (version "+t.version+")");const s=window.indexedDB.open(t.name,t.version+1);s.onerror=i,s.onblocked=n=>{P.debug("onblocked",n)},s.onupgradeneeded=n=>{const r=n.target.transaction;r.oncomplete=()=>{P.debug("[DB] Upgrade is done (new version: "+a.version+").")};const a=n.target.result,o=[];for(let l=0;l<this.tables.length;++l){const h=this.tables[l];if(!a.objectStoreNames.contains(h.name)){P.debug("[DB] Creating table "+h.name+"...");const d=this.createTable(a,h.name,h.options,h.indexArray);o.push(d)}}o.length>0&&Promise.all(o).then(()=>{P.debug("[DB] All("+o.length+") tables created.")})},s.onsuccess=n=>{const r=n.target.result;P.debug("[DB] Db "+r.name+" opened (version "+r.version+")."),e(r)}})}async createTable(t,e,i,s){return new Promise(n=>{const r=t.createObjectStore(e,i);s&&s.forEach(a=>{r.createIndex(a.name,a.fields,{unique:a.unique})}),P.debug("[DB] Table "+e+" created."),n(t)})}};g(si,"_instance");let ue=si;class Yo{constructor(){g(this,"db");g(this,"isCreatingTable");if(this.db=void 0,this.isCreatingTable=!1,ue.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();ue.instance().getDatabase().then(n=>{const r=n.transaction([s],"readwrite").objectStore(s),a=r.add(t);a.onsuccess=e,a.onerror=i}).finally(()=>{ue.instance().closeDatabase()}).catch(n=>{i&&i(n)})}save(t,e,i){const s=this.tableName();ue.instance().getDatabase().then(n=>{const r=n.transaction([s],"readwrite").objectStore(s),a=r.put(t);a.onsuccess=e,a.onerror=i}).finally(()=>{ue.instance().closeDatabase()})}delete(t,e,i){const s=this.tableName();ue.instance().getDatabase().then(n=>{const r=n.transaction([s],"readwrite").objectStore(s),a=r.delete(t);a.onsuccess=e,a.onerror=i}).finally(()=>{ue.instance().closeDatabase()})}update(){ue.instance().getDatabase().then(()=>{})}query(t,e){const i=this.tableName();ue.instance().getDatabase().then(s=>{const n=s.transaction([i],"readonly").objectStore(i),r=n.openCursor();r.onsuccess=a=>{const o=a.target.result;o&&o.continue(),t&&t(o)},r.onerror=e}).finally(()=>{ue.instance().closeDatabase()})}queryByIndex(t,e,i,s){const n=this.tableName();ue.instance().getDatabase().then(r=>{const a=r.transaction([n],"readonly").objectStore(n),o=a.index(t).get(e);o.onerror=s,o.onsuccess=function(l){const h=l.target?.result;i&&i(h)}}).finally(()=>{ue.instance().closeDatabase()})}queryAll(t,e){const i=this.tableName();ue.instance().getDatabase().then(s=>{const n=s.transaction([i],"readonly").objectStore(i),r=n.getAll();r.onsuccess=a=>{t&&t(a.target.result)},r.onerror=e}).finally(()=>{ue.instance().closeDatabase()})}clearAll(t,e){const i=this.tableName();ue.instance().getDatabase().then(s=>{const n=s.transaction([i],"readwrite").objectStore(i),r=n.clear();r.onsuccess=a=>{t&&t(a)},r.onerror=a=>{e&&e(a)}}).finally(()=>{ue.instance().closeDatabase()})}}const ni=class ni extends Yo{tableName(){return"dxf_data"}static instance(){return!ni._instance&&(ni._instance=new ni),ni._instance}query(t,e,i){const s=[],n=this.tableName();ue.instance().getDatabase().then(r=>{const a=r.transaction([n],"readonly").objectStore(n),o=a.get(t);o.onerror=l=>{i&&i(l),P.info("[DxfDataTable] Failed to query !",l)},o.onsuccess=()=>{o.result&&s.push(o.result),e&&e(s)}}).finally(()=>{ue.instance().closeDatabase()})}};g(ni,"_instance");let pn=ni;const qe=new p.Vector3(1,0,0),Wn=new p.Vector3(0,1,0),mi=new p.Vector3(0,0,1),Fa=new p.Vector3(0,0,0),Rt=16777215,T1="CONTINUOUS",Gs=new p.PointsMaterial({color:Rt}),me=new p.LineBasicMaterial({color:Rt}),gi=new p.MeshBasicMaterial({color:Rt}),za=new p.BufferGeometry().setFromPoints([new p.Vector3]),Va=new p.Matrix4,it=new p.Matrix4,de=new p.Matrix4,U=new p.Vector3,K=new p.Vector3,st=new p.Vector3,Ji=new p.Vector2,ge=new p.Quaternion,qs=new p.Object3D,ft=new p.Box3,ja=new p.PointsMaterial({color:65280,size:5,depthTest:!1}),Ua=new p.PointsMaterial({color:65280,depthTest:!1}),Na=new p.PointsMaterial({color:65280,depthTest:!1}),C1=c=>c.viewDirectionFromTarget!==void 0,S1=c=>{if(c){const t=c.match(/data:([a-zA-Z0-9]+\/[a-zA-Z0-9-.+]+).*,.*/);if(t&&t.length>0){const e=t[1],i=c.replace("data:"+e+";","").split(",");if(i&&i.length===2&&i[0]==="base64"){const s=i[1];return dc.decode(s)}}}return null},Ha=(c,t)=>{const e=new p.Vector2(c.x,c.y),i=new p.Vector2(t.x,t.y);return i.sub(e),i.normalize(),i.y<0?-Math.acos(i.x):Math.acos(i.x)},Ga=(c,t,e)=>({x:c.x+t*Math.cos(e),y:c.y+t*Math.sin(e)}),E1=(c,t,e,i)=>{const s=c?new p.Vector2(c.x,c.y):new p.Vector2(0,0),n=t?new p.Vector2(t.x,t.y):new p.Vector2(1,0);e=e||1;const r=4*Math.atan(e),a=s.distanceTo(n)/2/Math.sin(r/2),o=Ga(c,a,Ha(s,n)+(Math.PI/2-r/2));i=i||Math.max(Math.abs(Math.ceil(r/(Math.PI/18))),6);const l=Ha(o,s),h=r/i,d=[];d.push(new p.Vector3(s.x,s.y,0));for(let u=1;u<=i-1;u++){const f=Ga(o,Math.abs(a),l+h*u);d.push(new p.Vector3(f.x,f.y,0))}return d},qa=(c,t,e,i=c.length*2,s)=>{const n=[];if(!c||c.length<t+1||t<1)return n;const r=c.map(a=>[a.x,a.y]);try{for(let a=0;a<1;a+=1/i){const o=Lo(a,t,r,e,s);n.push(new p.Vector3(o[0],o[1],0))}}catch{if(n.length===0)return n}return n},Yn=(c,t=!1)=>{const e=[],i=c.length;for(let s=0;s<i;s++){const n=c[s];if(n.bulge&&(s!==i-1||t)){const r=n.bulge,a=s+1<i?c[s+1]:e[0],o=E1(n,a,r);e.push(...o)}else e.push(new p.Vector3(n.x,n.y,0))}return e},O1=c=>{const t=[];return c.faceA&&t.push(c.faceA),c.faceB&&t.push(c.faceB),c.faceC&&t.push(c.faceC),c.faceD&&t.push(c.faceD),t},_1=c=>{const t=[],e=[];c.forEach(s=>{s.polyfaceMeshVertex&&(s.threeDPolylineMesh?t.push(new p.Vector3(s.x,s.y,s.z)):e.push(O1(s)))});const i=[];for(let s=0;s<e.length;s++){const n=e[s];if(n.length===0)continue;const r=[];let a=!0;for(let o=0;o<n.length;o++){const l=n[o]-1;if(l>=t.length||l<0){a=!1;break}r.push(t[l])}!a||r.length===0||(r.push(r[0]),i.push(r))}return i},N=class N extends p.Loader{constructor(e,i){super(e);g(this,"timer");g(this,"ignorePaperSpace");g(this,"font");g(this,"encoding");g(this,"overrideColor");g(this,"overrideHatchPatternLineThickness");g(this,"angBase");g(this,"angDir");g(this,"header");g(this,"pointsMaterials");g(this,"lineBasicMaterials");g(this,"lineShaderMaterials");g(this,"meshBasicMaterials");g(this,"meshTextureMaterials");g(this,"hatchShaderMaterials");g(this,"entityCount");g(this,"curveCount");g(this,"averageCurveSize");g(this,"enableRenderOrder");g(this,"enableLocalCache");g(this,"enableReleaseData");g(this,"enableMerge");g(this,"enableRTC");g(this,"enablePlineWidth");g(this,"dxfDataId");g(this,"compareContext");g(this,"statsInfo");g(this,"llbDatas");g(this,"mtextDatas");g(this,"requestHeader");g(this,"blockReferencesCache");g(this,"blockRecordsCache");g(this,"entitiesCache");g(this,"blocksCache");g(this,"dictionaryOwnerHandleAndSpatialFilterHandlesCache");g(this,"spatialFiltersCache");g(this,"entityThreejsCache");g(this,"entityTypesAndTimes");g(this,"nonSnapableTypes");g(this,"layoutsSnapObjectsMap");g(this,"aborted");g(this,"entityHandlesWithRenderOrder");g(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,n)=>{if(s.type==="VIEWPORT"){!n[s.ownerHandle]&&(n[s.ownerHandle]=[]);const r=s;n[s.ownerHandle].push(r)}},i&&(this.ignorePaperSpace=i.ignorePaperSpace===!0,this.enableLocalCache=i.enableLocalCache===!0,this.enableMerge=N.LOADLLDATA?!1:i.enableMerge!==!1,this.encoding=i.encoding||"UTF-8",i.requestHeaders&&(this.requestHeader=i.requestHeaders),i.overrideColor!=null&&(this.overrideColor=Li.rgb2Hex(i.overrideColor)),i.overrideHatchPatternLineThickness!=null&&(this.overrideHatchPatternLineThickness=i.overrideHatchPatternLineThickness)),this.pointsMaterials[Rt]=Gs,this.lineBasicMaterials[Rt]=me,this.meshBasicMaterials[Rt]=gi}setRequestHeader(e){this.requestHeader=e}setFont(e){this.font=e}async download(e,i){let s=S1(e);if(!s){const n=Date.now(),r=new p.FileLoader(this.manager);this.requestHeader&&Object.keys(this.requestHeader).length>0&&r.setRequestHeader(this.requestHeader),r.setResponseType("arraybuffer"),r.setPath(this.path),s=await r.loadAsync(e,i),P.info("[Dxf] "+e+" dxf file downloaded in "+(Date.now()-n)/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=j.getUpdateSubProgressFunc(0,50,i),n=j.getUpdateSubProgressFunc(50,100,i),r=j.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),P.info("[Dxf] Loaded DxfData from indexedDb in "+(Date.now()-this.timer)/1e3+"s");const h=await this.loadEntities(l,r);return Promise.resolve(h)}}catch(h){P.warn("[Dxf] Failed to parse data from indexedDb",h)}}const a=await this.parse(e,s);return this.tryFixDxfData(a),await this.loadEntities(a,n)}async parse(e,i){const s=j.getUpdateProgressFunc(i),n=j.getUpdateSubProgressFunc(0,40,i),r=await this.download(e,n);if(!r)return Promise.reject("[Dxf] Failed to download "+e);if(this.aborted)return Promise.reject("[Dxf] Job aborted");this.timer=Date.now(),P.info("[Dxf] Start parsing...");const a=new Ho(this.encoding).parseSync(r);if(this.tryFixDxfData(a),s(80),P.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),P.info("[Dxf] Saved to indexedDb in "+(Date.now()-o)/1e3+"s")}catch(l){P.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){P.error("[Dxf]: Invalid header!");return}this.header=e;const i=e.$ACADVER.toString();i!=="AC1032"&&P.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&&(P.warn("[Dxf] No objects found, Will add one."),e.objects={}),!e.objects.LAYOUT&&(P.warn("[Dxf] No layout defined! Will add a default 'Model' layout!"),e.objects.LAYOUT=[{layoutName:N.MODEL_LAYOUT_NAME}]),!e.tables&&(P.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 n=0;const r=e.entities.length;this.entityCount=r,Object.keys(e.blocks).forEach(x=>{this.entityCount+=e.blocks[x].entities?.length||0});const a=j.getUpdateProgressFuncForLoop(r,i);let o={};const l=x=>{const E=x.userData.layerName;let M=o[E];!M&&(M=[],o[E]=M),M.push(x)},h={},d={},u=new V;for(let x=0;x<r&&!this.aborted;x++){const E=e.entities[x];this.addViewport(E,h);const M=this.loadEntity(E,e);if(!M&&await a(x),!M)continue;const O=this.getLayout(e,E),T=O.layoutName;let v=u.children.find(C=>C.name===T);if(!v&&(v=new V,v.name=T,v.userData.isLayoutLevelObject=!0,u.add(v)),M.traverse(C=>{C.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[T]&&(this.layoutsSnapObjectsMap[T]=[]),this.layoutsSnapObjectsMap[T].push(C))}),this.enableMerge){Tt.merge(M,!1),!d[T]&&(d[T]={object:v,layerObjects:{}});const _=d[T];if(M.geometry){const A=M.userData.layerName;!_.layerObjects[A]&&(_.layerObjects[A]=[]),_.layerObjects[A].push(M),M.children.forEach(I=>{I.userData.isSnapObject&&l(I)})}else M.children.length>0&&(v.add(M),M.traverse(A=>{A.geometry&&l(A)}))}else v.add(M),M.traverse(C=>{C.geometry&&l(C)});n++,await a(x)}e.objects.LAYOUT.forEach(x=>{const E=x,M=E.layoutName;if(this.ignorePaperSpace&&M!==N.MODEL_LAYOUT_NAME)return;const O=E.associatedBlockName,T=e.blocks[O];T&&this.loadLayout(T,e,E,u,o,h)}),P.debug("[Dxf] Drew entities in "+(Date.now()-s)/1e3+"s");for(const x in this.layoutsSnapObjectsMap){const E=u.children.find(T=>T.name===x),M=new V;M.name=N.SNAP_GROUP_NAME,M.userData.isSnapGroup=!0,E.add(M);const O=this.layoutsSnapObjectsMap[x];for(let T=0;T<O.length;T++){const v=O[T],C=v.userData.layerName;this.getLayerVisible(e,C)===!1&&v.layers.disable(je),N.SHOW_SNAP_OBJECT&&(v.layers.enableAll(),v.material instanceof p.PointsMaterial?v.material=ja:v.material instanceof p.LineBasicMaterial?v.material=Ua:v.material instanceof p.MeshBasicMaterial&&(v.material=Na));let _=v;const A=de.identity();for(;_&&_.userData.isLayoutLevelObject!==!0;)A.premultiply(_.matrix),_=_.parent;v.matrix.copy(A),M.add(v)}}if(this.enableMerge)for(const x in d){const E=d[x],M=E.object;for(const O in E.layerObjects){const T=E.layerObjects[O],v=Tt.deepMerge(T,void 0,!1,!1,!0),C=v.added,_=v.removed;if(_.length!==T.length){let A=_;_.length>=100&&(A=new Set(_));const I=B=>Array.isArray(A)?A.indexOf(B)>=0:A.has(B);for(let B=0,k=T.length;B<k;B++){const D=T[B];!I(D)&&(M.add(D),l(D))}}for(let A=0;A<C.length;A++){const I=C[A];M.add(I),l(I)}E.layerObjects[O]=[]}}this.printStatsInfo(),this.enableReleaseData&&(this.releaseCachedData(),this.releaseDxfData(e)),this.enableMerge&&N.mergeDxfObjects({root:u,layersAndObjects:o});const m=u.convertToThreejsObject();u.clear(),o={};const b={};e.objects.LAYOUT.forEach(x=>{const E=x;b[E.layoutName]=E});const y={},S=x=>{const E=x.userData.layerName;let M=y[E];!M&&(M=[],y[E]=M),M.push(x)};m.children.forEach(x=>{if(J.setSharedVariablesOfObject(x),!x.userData.isLayoutLevelObject)return;const E=x.name;let M;if(E!==N.MODEL_LAYOUT_NAME){const O=b[E];!O.directAssociatedLeafObjectSet&&(O.directAssociatedLeafObjectSet=new Set),M=O.directAssociatedLeafObjectSet}x.traverse(O=>{if(J.setSharedVariablesOfObject(O),O.userData.isSnapGroup&&(O.visible=N.SHOW_SNAP_OBJECT),O.geometry){const T=O.userData.layerName;this.getLayerVisible(e,T)===!1&&(O.visible=!1,O.userData.layerVisible=!1),S(O),M&&M.add(O)}})}),P.info("[Dxf] loadEntities() done in "+(Date.now()-s)/1e3+"s");const w=Object.assign(Object.assign({},e),{threejsObject:m,layersAndThreejsObjects:y,loadedEntityCount:n,layoutViewportsMap:h});if(N.LOADLLDATA){const x=m.children[0].children,E=[];for(let M=0;M<x.length;M++){const O=x[M];if(O?.userData?.llbData){const T=new p.Box3().setFromObject(O);T.getSize(new p.Vector3);const v=T.getCenter(new p.Vector3);E.push({...O,boundingBox:{max:T.max,min:T.min,center:v}})}else if(O.children&&O.children.some(T=>T.userData?.llbData))for(let T=0;T<O.children.length;T++){const v=O.children[T];if(v.userData?.llbData){v.updateWorldMatrix(!0,!0);const C=new p.Box3().setFromObject(v);C.getSize(new p.Vector3);const _=C.getCenter(new p.Vector3);E.push({...v,boundingBox:{max:C.max,min:C.min,center:_}})}}}w.llbMesh=E}return Promise.resolve(w)}getFontFilesFromDxf(e){const i=new Set,s=e.tables?.style?.styles;if(s)for(const n in s){const r=s[n],a=r.fontFile,o=r.bigFontFile;a&&i.add(a),o&&i.add(o)}P.info("[Dxf] Fonts used by dxf: "+Array.from(i).join())}async loadEntitiesForCompare(e,i,s,n=!0,r){const a=e.entities.length,o=i.entities.length,l=async()=>{const d=this.compareContext,u=d.isTheFirstFile,f=u?e:i,m=new V,b=u?a:o;this.entityCount=b,Object.keys(f.blocks).forEach(v=>{this.entityCount+=f.blocks[v].entities?.length||0});const y=Math.round(Math.pow(b,.5));let S=Date.now();const w=async v=>{if(r&&(v%y===0||v===b-1)){let C=v+1;!u&&(C+=a),r(new ProgressEvent("parseProgress",{loaded:C,total:a+o}));const _=500,A=Date.now();(A-S>_||v===b-1)&&(await j.sleep(0),S=A)}};this.parseHeader(f.header);let x={};for(let v=0;v<b;v++){if(this.aborted)return;const C=f.entities[v],_=this.getLayout(f,C);if(_.layoutName!==N.MODEL_LAYOUT_NAME){await w(v);continue}const A=this.loadEntity(C,f);if(!A){await w(v);continue}let I=m.children.find(B=>B.name===N.MODEL_LAYOUT_NAME);!I&&(I=new V,I.name=N.MODEL_LAYOUT_NAME,I.userData.isLayoutLevelObject=!0,m.add(I)),I.add(A),A.traverse(B=>{if(B.geometry){const k=B.userData.layerName,D=this.getLayerVisible(f,k);B.userData.isSnapObject&&(!this.layoutsSnapObjectsMap[_.layoutName]&&(this.layoutsSnapObjectsMap[_.layoutName]=[]),this.layoutsSnapObjectsMap[_.layoutName].push(B),D===!1&&A.layers.disable(je));let F=x[k];!F&&(F=[],x[k]=F),F.push(B)}}),await w(v)}n&&u&&!d.preservedHandles&&(d.preservedHandles=new Set);for(const v in s){const C=s[v];u&&(C.type===Ve.Added||C.type===Ve.Modified)&&(d.preservedHandles?.add(C.handle),C.parentHandles&&C.parentHandles.forEach(A=>d.preservedHandles?.add(A)));let _=this.entityThreejsCache&&this.entityThreejsCache[C.handle];if(C.parentHandles&&(_=this.entityThreejsCache&&this.entityThreejsCache[C.parentHandles[C.parentHandles.length-1]]),_){if(_.parent&&_.parent.userData.originalType){this.setObjectColorByChange(_,{type:Ve.NoChange});continue}_=this.setObjectColorByChange(_,C)}if(C.type!==Ve.NoChange&&_){let A=_.parent;const I=de.identity();for(;A&&A.userData.isLayoutLevelObject!==!0;)I.premultiply(A.matrix),A=A.parent;ft.makeEmpty();const B=V.getBox(_,ft);B.applyMatrix4(I),C.type===Ve.Added?!u&&(C.box=new p.Box3().copy(B)):C.type===Ve.Removed?u&&(C.box=new p.Box3().copy(B)):C.type===Ve.Modified&&(C.box?C.box.union(B):C.box=new p.Box3().copy(B))}}for(const v in this.layoutsSnapObjectsMap){const C=m.children.find(I=>I.name===v),_=new V;_.name=N.SNAP_GROUP_NAME,C.add(_);const A=this.layoutsSnapObjectsMap[v];for(let I=0;I<A.length;I++){const B=A[I];N.SHOW_SNAP_OBJECT&&(B.layers.enableAll(),B.material instanceof p.PointsMaterial?B.material=ja:B.material instanceof p.LineBasicMaterial?B.material=Ua:B.material instanceof p.MeshBasicMaterial&&(B.material=Na));let k=B;const D=de.identity();for(;k&&k.userData.isLayoutLevelObject!==!0;)D.premultiply(k.matrix),k=k.parent;B.matrix.copy(D),_.add(B)}}this.enableMerge&&N.mergeDxfObjects({root:m,layersAndObjects:x});const E=m.convertToThreejsObject();m.clear(),x={};const M={},O=v=>{const C=v.userData.layerName;let _=M[C];!_&&(_=[],M[C]=_),_.push(v)};E.children.forEach(v=>{J.setSharedVariablesOfObject(v),v.userData.isLayoutLevelObject&&v.traverse(C=>{if(J.setSharedVariablesOfObject(C),C.userData.isSnapGroup&&(C.visible=N.SHOW_SNAP_OBJECT),C.geometry){const _=C.userData.layerName;this.getLayerVisible(f,_)===!1&&(C.visible=!1,C.userData.layerVisible=!1),O(C)}})});const T=f;T.threejsObject=E,T.layersAndThreejsObjects=M,T.layoutViewportsMap={}};let h=Date.now();this.compareContext={changes:s,isTheFirstFile:!0},j.printMemory("Before loading entities for first dxf"),await l(),P.info("[Dxf] loadEntities for first dxf in "+(Date.now()-h)/1e3+"s"),j.printMemory("After loading entities for first dxf"),this.releaseCachedData(!1),this.releaseDxfData(e),j.printMemory("Before loading entities for second dxf"),h=Date.now(),this.compareContext.isTheFirstFile=!1,await l(),P.info("[Dxf] loadEntities for second dxf in "+(Date.now()-h)/1e3+"s"),this.printStatsInfo();for(const d of Object.values(s))!d.box&&delete s[d.id];this.compareContext.preservedHandles=void 0,this.enableReleaseData&&(this.releaseCachedData(),this.releaseDxfData(i)),j.printMemory("After loading entities for second dxf")}setObjectColorByChange(e,i){const s=a=>{let o=ot.ENTITY_COLOR_NO_CHANGE;return a.type===Ve.Added?o=ot.ENTITY_COLOR_ADDED:a.type===Ve.Removed?o=ot.ENTITY_COLOR_REMOVED:a.type===Ve.Modified&&(o=this.compareContext?.isTheFirstFile?ot.ENTITY_COLOR_REMOVED:ot.ENTITY_COLOR_ADDED),o},n=(a,o)=>{a.traverse(l=>{if(l.material){if(l.material instanceof p.LineBasicMaterial)l.material=this.getLineBasicMaterial(o);else if(l.material instanceof p.MeshBasicMaterial)l.material=this.getMeshBasicMaterial(o);else if(l.material instanceof p.PointsMaterial)l.material=this.getPointsMaterial(o);else if(l.material instanceof p.ShaderMaterial){const h=l.material.clone();N.updateMaterialUniforms(h),h.uniforms.u_color.value.set(o),l.material=h}}})},r=s(i);return e.traverse(a=>{i.parentHandles?a.userData&&a.userData.handle&&a.userData.handle===i.handle&&(n(a,r),e=a):n(a,r)}),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,n=!1){if(this.compareContext&&this.compareContext.preservedHandles&&this.compareContext.preservedHandles.has(e.handle)&&os.includes(e.type)&&(n=!0),!n&&this.compareContext&&this.compareContext.preservedHandles&&!os.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 f=e.layer;return!this.statsInfo.ignoredFrozenLayersAndEntityCount[f]&&(this.statsInfo.ignoredFrozenLayersAndEntityCount[f]=0),this.statsInfo.ignoredFrozenLayersAndEntityCount[f]++,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 f=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,n);else if(e.type==="SPLINE")o=this.loadSpline(e,s);else if(e.type==="MTEXT")f?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 m=0;m<i.entities.length;m++){const b=i.entities[m];if(e.ownerHandle===b.handle&&(s=b,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 f=this.getLayerName(e,i,s);if(o.userData.handle=e.handle,e.type!=="INSERT"&&e.type!=="DIMENSION"&&o.traverse(m=>{m.geometry&&(m.userData.layerName=f,m.userData.handle=e.handle,m.userData.dxfType=e.type,this.setMaterial(m,e,i,s))}),!l&&(this.nonSnapableTypes.has(e.type)&&o.traverse(m=>{m.layers.disable(je)}),this.enableRenderOrder&&(this.entityHandlesWithRenderOrder[e.handle]?o.renderOrder=parseInt(this.entityHandlesWithRenderOrder[e.handle],16)+.1:o.renderOrder=parseInt(e.handle,16))),e.type==="INSERT"&&!s&&!this.enableRenderOrder){const m=e.block?i.blocks[e.block]?.entities:void 0;let b=!0;if(m?.length)for(const w of m){const x=w;if(x.type==="ATTDEF"||x.type==="SEQEND")continue;if(!(x.type==="LINE"||x.type==="SPLINE"||(x.type==="LWPOLYLINE"||x.type==="POLYLINE")&&!x.shape)){b=!1;break}}else b=!1;const y=Math.min(parseInt(e.handle,16)||0,3999),S=b?ye.InsertLine+y*1e-5:ye.InsertSymbol+y*1e-4;o.traverse(w=>{if(w.geometry&&w.renderOrder<ye.Text&&(w.renderOrder=S,b)){const x=w.geometry.getAttribute("position");if(x){let E=!1;for(let M=0;M<x.count;M++)x.getZ(M)!==0&&(x.setZ(M,0),E=!0);E&&(x.needsUpdate=!0,w.geometry.computeBoundingBox(),w.geometry.computeBoundingSphere())}}})}}const h=e.type,d=e.handle,u=os.includes(h);if(!u){this.entityTypesAndTimes||(this.entityTypesAndTimes={}),this.entityTypesAndTimes[h]||(this.entityTypesAndTimes[h]={createCount:0,totalTime:0,averageTime:0});const f=this.entityTypesAndTimes[h];f.createCount++,f.totalTime+=Date.now()-a}return o?this.statsInfo.entityTypesAndMeshCount[h]?this.statsInfo.entityTypesAndMeshCount[h]++:this.statsInfo.entityTypesAndMeshCount[h]=1:(this.statsInfo.unsupportedEntityTypes[h]?this.statsInfo.unsupportedEntityTypes[h]++:this.statsInfo.unsupportedEntityTypes[h]=1,u||(this.statsInfo.unsupportedEntity[d]?this.statsInfo.unsupportedEntity[d]++:this.statsInfo.unsupportedEntity[d]=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 n=e.startAngle,r=e.endAngle;if(e.extrusionDirection&&e.extrusionDirection.z<0&&(n=Math.PI*2-e.endAngle,r=Math.PI*2-e.startAngle),z.areNumbersEqual(n,r,1e-5))return P.warn("[Dxf] Ellipse entity (handle '%s') contains the same start and end angle, ignored!",e.handle),void 0;let a=r-n;for(;a>Math.PI*2;)a-=Math.PI*2;Math.abs(a)<=1e-5&&(r=z.floorNumber(n+Math.PI*2,5));const o=Math.sqrt(Math.pow(e.majorAxisEndPoint.x,2)+Math.pow(e.majorAxisEndPoint.y,2)),l=o*e.axisRatio,h=Math.atan2(e.majorAxisEndPoint.y,e.majorAxisEndPoint.x),d=new p.EllipseCurve(e.center.x,e.center.y,o,l,n,r,!1,h);let u=1;const f=s;f?.xScale&&f?.yScale&&(u=Math.max(Math.abs(f.xScale),Math.abs(f.yScale)));const m=this.getDivision(n,r,Math.max(o,l)*u),b=d.getPoints(m),y=[],S=b.length;for(let T=0;T<S-1;T++)z.areVector2sEqual(b[T],b[T+1],1e-9)||y.push(b[T]);if(y.push(b[S-1]),y.length<2)return P.warn("[Dxf] Ellipse entity (handle '%s') contains less than 2 points, ignored!",e.handle),void 0;const w=new p.Vector3;let x=!1;this.enableRTC&&(x=H.checkAndRebasePositionsOnRTC(y,w));const E=new p.BufferGeometry().setFromPoints(y),M=new V(G.Line);M.geometry=E,M.material=me;const O=new V(G.Point);return O.geometry=za,O.material=Gs,O.matrix.setPosition(e.center.x,e.center.y,e.center.z),O.userData.isSnapObject=!0,O.userData.type="CircleCenter",O.layers.set(je),M.add(O),x&&(this.setRTCUserData(M),M.matrix.setPosition(w.x,w.y,0)),M.layers.enableAll(),M}loadMText(e,i,s){if(!e.text)return;if(!this.font)return P.info("[Dxf] Font file not set, ignoring text entity."),void 0;const n=this.getTextStyle(i,e),r=ls(e.text,{encoding:this.getTextEncoding(n)}),a=this.getMTextGroup(r,e,n,i,s),o=a&&a.object;if(!o)return;o.matrix.decompose(K,ge,st),e.position&&(K.x+=e.position.x,K.y+=e.position.y,o.matrix.compose(K,ge,st)),ft.makeEmpty();const l=V.getBox(o,ft),h=l.getSize(U),d=e.width||h.x,u=e.height||h.y,f=h.y>0?h.y:u,m=e.text;let b=0,y=0;switch(document.createElement("canvas").getContext("2d"),e.attachmentPoint){case 1:b=0,y=0;break;case 2:b-=d/2,y=0;break;case 3:b-=d,y=0;break;case 4:b=0,y+=f/2;break;case 5:b-=d/2,y+=f/2;break;case 6:b-=d,y+=f/2;break;case 7:b=0,y+=f;break;case 8:b-=d/2,y+=f;break;case 9:b-=d,y+=f;break;default:return}switch(e.drawingDirection){case 1:break;case 2:break;case 3:y+=u;break;case 4:break;case 5:const I=m.split("\\P");let B=0;I>1&&(B=I-1),B>1?y+=u*(B-1):y-=u/4;break;default:return}o.traverse(I=>{I.geometry&&I.geometry.translate(b,y,0),I.layers.enableAll()});let w=0;if(e.rotation&&(w=e.rotation*Math.PI/180),e.directionVector){const I=e.directionVector,B=new p.Vector3(I.x,I.y,I.z),k=B.clone().cross(qe),D=qe.angleTo(B);w=k.z>0?-D:D}H.shouldRebasePositionOnRTC(K)&&this.setRTCUserData(o),o.matrix.compose(K,ge,st);const x=e.position?K.clone().sub(e.position):K;it.makeTranslation(-x.x,-x.y,0),de.makeRotationZ(w),o.matrix.multiply(it),o.matrix.multiply(de),o.matrix.multiply(it.invert()),o.userData||(o.userData={});const E=o.matrix.elements,M=E&&E[12]||0,O=E&&E[13]||0,T=E&&E[14]||0,v=new p.Box3;V.getBox(o,v);const C=new p.Vector3;v.getCenter(C);const _=new p.Vector3;v.getSize(_),o.userData.renderArea={position:{x:M,y:O,z:T},bbox:{min:{x:v.min.x,y:v.min.y,z:v.min.z},max:{x:v.max.x,y:v.max.y,z:v.max.z},center:{x:C.x,y:C.y,z:C.z},width:_.x,height:_.y,depth:_.z},textSize:{width:d,height:u},rotation:w,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 P.info("[Dxf] Font file not set, ignoring text entity."),void 0;const n=this.getTextStyle(i,e),r=ls(e.text,{encoding:this.getTextEncoding(n)}),a=this.getMTextGroup(r,e,n,i,s),o=a&&a.object;if(!o)return;o.matrix.decompose(K,ge,st),e.position&&(K.x+=e.position.x,K.y+=e.position.y,o.matrix.compose(K,ge,st)),ft.makeEmpty();const l=V.getBox(o,ft),h=l.getSize(U),d=e.width||h.x,u=e.height||h.y,f=h.y>0?h.y:u;let m=0,b=0;switch(e.attachmentPoint){case 1:m=0,b=0;break;case 2:m-=d/2,b=0;break;case 3:m-=d,b=0;break;case 4:m=0,b+=f/2;break;case 5:m-=d/2,b+=f/2;break;case 6:m-=d,b+=f/2;break;case 7:m=0,b+=f;break;case 8:m-=d/2,b+=f;break;case 9:m-=d,b+=f;break;default:return}switch(e.drawingDirection){case 1:break;case 2:break;case 3:b+=u;break;case 4:break;case 5:break;default:return}o.traverse(w=>{w.geometry&&w.geometry.translate(m,b,0),w.layers.enableAll()});let y=0;if(e.rotation&&(y=e.rotation*Math.PI/180),e.directionVector){const w=e.directionVector,x=new p.Vector3(w.x,w.y,w.z),E=x.clone().cross(qe),M=qe.angleTo(x);y=E.z>0?-M:M}H.shouldRebasePositionOnRTC(K)&&this.setRTCUserData(o),o.matrix.compose(K,ge,st);const S=e.position?K.clone().sub(e.position):K;return it.makeTranslation(-S.x,-S.y,0),de.makeRotationZ(y),o.matrix.multiply(it),o.matrix.multiply(de),o.matrix.multiply(it.invert()),o}getMTextGroup(e,i,s,n,r,a=0,o=0,l=[]){if(e.length===0)return;let h=i.height||i.contextData&&i.contextData.textHeight||0;if(i.textStyle){if(s&&s.fontFile&&s.fontFile.endsWith(".shx")){const M=s.fontFile+"_"+s.styleName;!this.statsInfo.unsupportedTextStyles[M]&&(this.statsInfo.unsupportedTextStyles[M]=0),this.statsInfo.unsupportedTextStyles[M]++}h=h||s.textHeight}let d="Left";i.width&&i.attachmentPoint&&([1,4,7].includes(i.attachmentPoint)?d="Left":[2,5,8].includes(i.attachmentPoint)?d="Center":[3,6,9].includes(i.attachmentPoint)&&(d="Right"));const u=i.width||0,f=new V;let m,b=s.fontFile,y=1,S=1,w=256,x=h*.8,E=x+h;for(let M=0;M<e.length;M++){const O=e[M];if(typeof O=="string"){const T=[],v=(A,I)=>{let B;if(A.forEach((k,D)=>{!k.boundingBox&&k.computeBoundingBox(),D===0?B=k.boundingBox:B.union(k.boundingBox)}),B)switch(d){case"Left":break;case"Center":A.forEach(k=>k.translate((u-I)/2,0,0));break;case"Right":A.forEach(k=>k.translate(u-I,0,0));break}T.push(...A)};let C;for(let A=0;A<O.length;A++){const I=O[A];if(I===`
794
794
  `){const k=a;a=0,o-=E,l.length>0&&v(l,k),l=[];continue}if(x=h*.8,E=x+h,C=this.font?.getCharShape(I,b,h),s.bigFontFile&&!C&&(C=this.font?.getCharShape(I,s.bigFontFile,h)),!C&&(C=this.font?.getCharShape(I,"",h)),!C&&(C=this.font?.getNotFoundTextShape(h)),!C){a+=h+S*(h/3.5);continue}a>(u||1/0)&&(l.length>0&&v(l,a),a=0,o-=E,l=[]),C.translate(a,o,0),C.scale(y,1,1),C.boundingBox||C.computeBoundingBox(),O.T&&(S=O.T);const B=cd(I,C,h,S,b);a+=B,l.push(C)}l.length>0&&(v(l,a),l=[]);const _=new V;if(T.length>0){!m&&(m=i.colorIndex),w!==void 0&&w!==256?(i.color=ki(w),i.colorIndex=w):i.colorIndex=m;const A=this.getColor(i,n,r),I=T.filter(k=>k instanceof p.ExtrudeGeometry),B=T.filter(k=>!(k instanceof p.ExtrudeGeometry));if(I.length>0){const k=new V(G.Mesh);k.geometry=Pe.mergeGeometries(I),k.material=this.getMeshBasicMaterial(A),_.add(k)}if(B.length>0){const k=new V(G.LineSegment);k.geometry=Pe.mergeGeometries(B),k.material=this.getLineBasicMaterial(A),_.add(k)}}_.matrix.makeTranslation(0,-h,0),f.add(_),y=1,S=1,w=256}else if(Array.isArray(O)){const T=this.getMTextGroup(O,i,s,n,r,a,o,l);T&&(f.add(T.object),a=T.hOffset,o=T.vOffset)}else typeof O=="object"&&(O.f&&(b=O.f,b&&b.includes(".shx")&&P.info("[Dxf] Doesn't support custom fonts: "+b)),O.C&&(w=O.C),O.W&&(O.W[1]==="x"?y=O.W[0]*i.width:y=O.W[0]),O.H&&(O.H[1]==="x"?h=O.H[0]*i.height:h=O.H[0]),O.T&&(S=O.T))}if(f.children.length!==0)return Tt.merge(f,!1),m&&(i.colorIndex=m),f.children.length===1?{object:f.children[0],hOffset:a,vOffset:o}:{object:f,hOffset:a,vOffset:o}}mtextContentAndFormattingToTextAndStyle(e,i){const s={horizontalAlignment:"",textHeight:i.height||i.contextData&&i.contextData.textHeight},n={};let r=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 h=this.getTextLineNum(l);a.push({font:n.f,colorIndex:n.C,text:l,lineNum:r}),r+=h}}}}else if(Array.isArray(l)){const h=this.mtextContentAndFormattingToTextAndStyle(l,i);h.text.forEach(d=>{a.push(d)}),r=h.lineLength}else if(typeof l=="object")if(l.S&&l.S.length===3){const h=l.S[0]+"/"+l.S[2],d=this.getTextLineNum(h);a.push({text:l.S[0]+"/"+l.S[2],lineNum:r}),r+=d}else l.C!==void 0?n.C=l.C:l.W!==void 0?n.W=l.W:l.H!==void 0?n.H=l.H:l.f!==void 0&&(n.f=l.f)}return{text:a,lineLength:r,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 P.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=e.vertices.map(o=>new p.Vector3(o.x,o.y,o.z));if(i.length===0)return;!z.areVector3sEqual(i[0],i[i.length-1])&&i.push(i[0]);const s=new p.Vector3;let n=!1;this.enableRTC&&(n=H.checkAndRebasePositionsOnRTC(i,s));const r=new p.BufferGeometry().setFromPoints(i),a=new V(G.Line);return a.geometry=r,a.material=me,n&&(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 P.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,n=1/0,r=-1/0,a=-1/0;for(const w of e.controlPoints)w.x<s&&(s=w.x),w.y<n&&(n=w.y),w.x>r&&(r=w.x),w.y>a&&(a=w.y);let o=1;const l=i;l?.xScale&&l?.yScale&&(o=Math.max(Math.abs(l.xScale),Math.abs(l.yScale)));const h=Math.max(r-s,a-n),d=this.getBSplineInterpolationsPerSplineSegment(e.controlPoints.length,h*o),u=qa(e.controlPoints,e.degreeOfSplineCurve,e.knotValues,d),f=new p.Vector3;let m=!1;this.enableRTC&&(m=H.checkAndRebasePositionsOnRTC(u,f));const b=H.getAdjacentNonRepeatPoints(u);if(b.length<2)return P.warn("[Dxf] Spline entity (handle '%s') contains less than 2 points, ignored!",e.handle),void 0;const y=new p.BufferGeometry().setFromPoints(b),S=new V(G.Line);return S.geometry=y,S.material=me,m&&(this.setRTCUserData(S),S.matrix.setPosition(f.x,f.y,0)),S.layers.enableAll(),S}loadXLine(e){if(!e.vertices||e.vertices.length===0)return P.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=j.arrayOrObjectToVector3(e.directionVector),s=new p.Vector3(e.vertices[0].x,e.vertices[0].y,0),n=[];if(n.push(i.clone().multiplyScalar(-1e6).add(s)),n.push(i.clone().multiplyScalar(1e6).add(s)),n.length===0)return;const r=new p.Vector3;let a=!1;this.enableRTC&&(a=H.checkAndRebasePositionsOnRTC(n,r));const o=new p.BufferGeometry().setFromPoints(n),l=new V(G.Line);return l.geometry=o,l.material=me,a&&(this.setRTCUserData(l),l.matrix.setPosition(r.x,r.y,0)),l.layers.enableAll(),l}loadRay(e){if(!e.vertices||e.vertices.length===0)return P.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;const i=j.arrayOrObjectToVector3(e.directionVector),s=e.vertices.map(l=>new p.Vector3(l.x,l.y,0));if(s.push(i.multiplyScalar(1e6).add(s[0])),s.length===0)return;const n=new p.Vector3;let r=!1;this.enableRTC&&(r=H.checkAndRebasePositionsOnRTC(s,n));const a=new p.BufferGeometry().setFromPoints(s),o=new V(G.Line);return o.geometry=a,o.material=me,r&&(this.setRTCUserData(o),o.matrix.setPosition(n.x,n.y,0)),o.layers.enableAll(),o}loadLine(e,i){if(!e.vertices||e.vertices.length===0){P.warn("[Dxf] Entity is missing vertices:",e.handle);return}let s=[];if(e.isPolyfaceMesh)s=_1(e.vertices);else{const h=Yn(e.vertices,e.shape);e.shape&&h.length>0&&h.push(h[0]),h.length>0&&(s=[h])}if(s.length===0)return;const n=[];for(let h=0;h<s.length;){const[d,u]=s[h];z.areVector3sEqual(d,u)&&s[h].length<=2?(n.push(d.clone()),s.splice(h,1)):h++}const r=new p.Vector3;let a=!1,o=0;s.forEach(h=>{h.forEach(d=>r.add(d)),o+=h.length}),o>0&&(r.divideScalar(o),a=this.enableRTC&&H.shouldRebasePositionOnRTC(r));let l=null;if(s.length>0){let h=function(w){return Array.isArray(w.pattern)&&w.pattern.length>0};const d=[],u=[];let f=0;s.forEach(w=>{w.forEach(x=>{a?d.push(new p.Vector3(x.x-r.x,x.y-r.y,x.z-r.z)):d.push(x.clone())});for(let x=1;x<w.length;x++)u.push(f+x-1,f+x);f+=w.length});const m=this.getLineType(e,i),b=i.tables?.lineType?.lineTypes?.[m],y=new p.BufferGeometry().setFromPoints(d);let S=me;if(b&&h(b)){let w=function(O){const T=O.attributes.position,v=T.count,C=new Float32Array(v);for(let _=0;_<v;_+=2){const A=_*3,I=(_+1)*3,B=T.array[I]-T.array[A],k=T.array[I+1]-T.array[A+1],D=T.array[I+2]-T.array[A+2],F=Math.sqrt(B*B+k*k+D*D);C[_]=_===0?0:C[_-1],C[_+1]=C[_]+F}O.setAttribute("lineDistance",new p.Float32BufferAttribute(C,1))};const x=b.pattern?.[0]||.5,E=b.pattern?.[1]||.5,M=.1;S=new p.LineDashedMaterial({color:me.color,linewidth:me.linewidth||1,dashSize:x*M,gapSize:E*M,scale:M}),w(y)}else y.setIndex(u);l=new V(G.LineSegment),l.geometry=y,l.material=S}if(n.length>0){a&&H.checkAndRebasePositionsOnRTC(n,r);const h=new p.BufferGeometry().setFromPoints(n),d=new V(G.Point);d.geometry=h,d.material=Gs,l?console.warn("Line has both segments and points – consider using a Group"):l=d}if(l)return a&&(this.setRTCUserData(l),l.matrix.setPosition(r.x,r.y,r.z)),l.layers.enableAll(),l}loadLWPolyline(e,i,s){if(!e.vertices||e.vertices.length<2){P.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}const n=[...e.vertices];if(e.extrusionDirectionX!==void 0&&e.extrusionDirectionY!==void 0&&e.extrusionDirectionZ!==void 0){U.set(e.extrusionDirectionX,e.extrusionDirectionY,e.extrusionDirectionZ);const b=N.getOcsMatrix(U).invert(),y=e.elevation!==void 0?e.elevation:0;n.forEach(S=>{U.set(S.x,S.y,y).applyMatrix4(b),S.x=U.x,S.y=U.y})}let r=Yn(n,e.shape);if(e.shape&&r.length>0&&!z.areVector3sEqual(r[0],r[r.length-1])&&r.push(r[0]),r.length<2){P.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}let a=new V;const o=e.extendedData;if(o?.outlines){const b=o.outlines,y=[];b.forEach(x=>{const E=new p.Shape;x.forEach((M,O)=>{O===0?E.moveTo(M[0],M[1]):E.lineTo(M[0],M[1])}),E.closePath(),y.push(new p.ShapeGeometry(E))});const S=Pe.mergeGeometries(y),w=new V(G.Mesh);w.geometry=S,w.material=gi,w.layers.enableAll(),w.layers.disable(je),a.add(w)}let l=!1;const h=new p.Vector3;this.enableRTC&&(l=H.checkAndRebasePositionsOnRTC(r,h));const d=H.getAdjacentNonRepeatPoints(r);if(d.length<2){P.warn("[Dxf] Invalid LWPolyline entity (handle '%s'), ignored!",e.handle);return}const u=e.constantWidth,f=d.length>2&&z.areVector3sEqual(d[0],d[d.length-1]);if(this.enablePlineWidth&&!f){const b=n.some(y=>y.startWidth!==void 0||y.endWidth!==void 0);if(b||u!==void 0&&u>0){let y;const S=i.tables?.lineType?.lineTypes,w=this.getLineType(e,i,s),x=S?.[w];if(!x||!x.pattern||x.pattern.length===0)if(this.statsInfo.unsupportedPolylineCount++,b?y=this.createTaperedPolylineGeometry(n,u):y=H.convertWidthLineToMeshGeometry(d,u),!y)P.warn("[Dxf] Failed to convert line with width to mesh geometry: %s",e.handle);else{const E=new V(G.Mesh);E.geometry=y,E.material=gi,E.layers.enableAll(),E.layers.disable(je),a.add(E);const M=J.createOutline(y,me,E.matrix),O=new V(G.LineSegment);O.geometry=M.geometry,O.material=M.material,O.matrix=M.matrix,O.layers.enableAll(),O.layers.disable(je),a.add(O)}}}const m=new V(G.Line);return m.geometry=new p.BufferGeometry().setFromPoints(d),m.material=me,m.layers.enableAll(),a.children.length>0?a.add(m):a=m,l&&(this.setRTCUserData(a),a.matrix.setPosition(h)),a}createTaperedPolylineGeometry(e,i){if(!e||e.length<2)return null;const s=[],n=[];for(let a=0;a<e.length-1;a++){const o=e[a],l=e[a+1],h=l.x-o.x,d=l.y-o.y,u=Math.hypot(h,d);if(u===0)continue;const f=o.startWidth??i??0,m=o.endWidth??i??0;if(f<=0&&m<=0)continue;const b=-d/u,y=h/u,S=f/2,w=m/2,x={x:o.x+b*S,y:o.y+y*S},E={x:o.x-b*S,y:o.y-y*S},M={x:l.x+b*w,y:l.y+y*w},O={x:l.x-b*w,y:l.y-y*w},T=s.length/3;s.push(x.x,x.y,0,E.x,E.y,0,M.x,M.y,0,O.x,O.y,0),n.push(T,T+1,T+2),n.push(T+1,T+3,T+2)}if(!n.length)return null;const r=new p.BufferGeometry;return r.setAttribute("position",new p.Float32BufferAttribute(s,3)),r.setIndex(n),r}loadMLeader(e,i,s){const n=i.tables.dimStyle.dimStyles[e.dimensionStyle]||this.getDefaultDimensionStyle(i),r=e.contextData?.defaultTextContents;if(!r)return;const a=new V,o=ls(r),l=this.getTextStyle(i,e),h=this.getMTextGroup(o,e,l,i,s),d=h&&h.object;if(d){d.matrix.decompose(K,ge,st),e.contextData?.textLocation&&(K.x+=e.contextData.textLocation.x,K.y+=e.contextData.textLocation.y,d.matrix.compose(K,ge,st)),ft.makeEmpty();const u=V.getBox(d,ft),f=u.getSize(U),m=f.x,b=f.y;let y=0,S=0;switch(e.contextData?.textAttachment){case 1:y=0,S=0;break;case 2:y-=m/2,S=0;break;case 3:y-=m,S=0;break;case 4:y=0,S+=b/2;break;case 5:y-=m/2,S+=b/2;break;case 6:y-=m,S+=b/2;break;case 7:y=0,S+=b;break;case 8:y-=m/2,S+=b;break;case 9:y-=m,S+=b;break;default:return}d.traverse(E=>{E.geometry&&E.geometry.translate(y,S,0)});let w=0;if(e.contextData?.textRotation&&(w=e.contextData.textRotation*Math.PI/180),e.contextData?.textDirection){const E=e.contextData.textDirection,M=new p.Vector3(E.x,E.y,E.z),O=M.clone().cross(qe),T=qe.angleTo(M);w+=O.z>0?-T:T}H.shouldRebasePositionOnRTC(K)&&this.setRTCUserData(d),d.matrix.compose(K,ge,st),e.contextData?.textLocation?U.set(e.contextData.textLocation.x,e.contextData.textLocation.y,0):U.set(0,0,0);const x=K.clone().sub(U);it.makeTranslation(-x.x,-x.y,0),de.makeRotationZ(w),d.matrix.multiply(it),d.matrix.multiply(de),d.matrix.multiply(it.invert()),d.renderOrder=ye.Text,a.add(d)}if(e.leaderLineType!==0){const u=[],f=e.contextData?.leaders[0];if(!f)return a;const m=f.lastLeaderLinePoint;if(!m)return a;if(e.enableDogLeg&&f.doglegVector){const E=new p.Vector3(m.x,m.y,m.z),M=f.doglegLength,O=new p.Vector3(f.doglegVector.x,f.doglegVector.y,f.doglegVector.z),T=O.multiplyScalar(M),v=E.clone().add(T);u.push(v,E)}const b=e.contextData?.leaders[0].leaderLines||[];for(let E=0;E<b.length;E++){const M=b[E].vertices?.[0];if(!M||M.length===0)continue;const O=M.reverse().map(B=>new p.Vector3(B.x,B.y,B.z));let T=new p.Vector3(m.x,m.y,m.z);for(let B=0;B<O.length;B++)u.push(T,O[B]),T=O[B];if(u.length<2)continue;const v=U.subVectors(u[0],u[1]).length(),C=e.arrowHeadSize||n.DIMASZ||2.5,_=e.arrowHeadScale||n.DIMSCALE||1,A=C*_;e.leaderLineType;let I="";if(e.arrowHeadId?I=e.arrowHeadId:n&&n.DIMLDRBLK&&(I=n.DIMLDRBLK),I){const B=this.getBlockByHandle(i.blocks,I);if(B&&B.entities)for(let k=0;k<B.entities.length;k++){const D=this.loadEntity(B.entities[k],i,e);if(D){const F=new p.Vector3(u[u.length-1].x,u[u.length-1].y,u[u.length-1].z),ie=new p.Vector3(u[u.length-2].x,u[u.length-2].y,u[u.length-2].z),se=Math.atan2(F.y-ie.y,F.x-ie.x);U.copy(F),K.setScalar(A),ge.setFromAxisAngle(mi,se),D.matrix.compose(U,ge,K),a.add(D)}}}else this.loadDefaultLeadArrow(u[u.length-2],u[u.length-1],v/2e3,u)}const y=new p.Vector3;let S=!1;this.enableRTC&&(S=H.checkAndRebasePositionsOnRTC(u,y));const w=new p.BufferGeometry().setFromPoints(u),x=new V(G.LineSegment);x.geometry=w,x.material=me,x.renderOrder=ye.Line,S&&(this.setRTCUserData(x),x.matrix.setPosition(y.x,y.y,0)),a.add(x)}else return d?.traverse(u=>{u.layers.enableAll()}),d;return Tt.merge(a,!1),a.traverse(u=>{u.layers.enableAll()}),a.children.length===1?a.children[0]:a}loadLeader(e,i,s){const n=[];if(!e.vertices)return P.warn("[Dxf] Entity is missing vertices:",e.handle),void 0;if(e.vertices.length<2)return P.warn("leader's vertices number must be greater than 2"),void 0;const r=i.tables.dimStyle.dimStyles[e.dimensionStyle]||this.getDefaultDimensionStyle(i);let a=e.vertices;if(e.pathType===1&&(a=new p.SplineCurve(e.vertices).getPoints(50)),e.textWidth){const S=e.textWidth,w=new p.Vector3(a[a.length-1].x,a[a.length-1].y,a[a.length-1].z);if(e.direction===0){const x=new p.Vector3(1,0,0).multiplyScalar(S);a.push(x.add(w))}else{const x=new p.Vector3(-1,0,0).multiplyScalar(S);a.push(x.add(w))}}for(let S=0;S<a.length-1;S++){const w=a[S],x=a[S+1];n.push(w,x)}const o=U.subVectors(n[0],n[1]).setZ(0).length(),l=e.arrowHeight||r.DIMASZ||2.5,h=e.arrowHeadScale||r.DIMSCALE||1,d=l*h,u=new V;if(e.arrowFlag===1){let S="";e.arrowHeadBlockHandle?S=e.arrowHeadBlockHandle:r&&r.DIMLDRBLK&&(S=r.DIMLDRBLK);const w=this.getBlockByHandle(i.blocks,S);if(w&&w.entities){r&&(e.colorIndex=r.DIMCLRD||256,e.color=ki(e.colorIndex));for(let x=0;x<w.entities.length;x++){const E=this.loadEntity(w.entities[x],i,e);if(E){const M=new p.Vector3(n[0].x,n[0].y,n[0].z),O=new p.Vector3(n[1].x,n[1].y,n[1].z),T=Math.atan2(M.y-O.y,M.x-O.x);U.copy(M),K.setScalar(d),ge.setFromAxisAngle(mi,T),E.matrix.compose(U,ge,K),u.add(E)}}}else this.loadDefaultLeadArrow(n[1],n[0],d/o/2,n)}if(n.length===0)return;const f=new p.Vector3;let m=!1;this.enableRTC&&(m=H.checkAndRebasePositionsOnRTC(n,f));const b=new p.BufferGeometry().setFromPoints(n),y=new V(G.Line);return y.geometry=b,y.material=me,y.renderOrder=ye.Line,m&&(this.setRTCUserData(y),y.matrix.setPosition(f.x,f.y,0)),u.children.length>0?(u.add(y),Tt.merge(u,!1),u.traverse(S=>{S.layers.enableAll()}),u.children.length===1?u.children[0]:u):(y.layers.enableAll(),y)}getTableTextOffset(e,i,s){const n=new p.Vector3;switch(e){case 1:break;case 2:n.setX(i/2);break;case 3:n.setX(i);break;case 4:n.setY(-s/2);break;case 5:n.set(i/2,-s/2,0);break;case 6:n.set(i,-s/2,0);break;case 7:n.setY(-s);break;case 8:n.set(i/2,-s,0);break;case 9:n.set(i,-s,0);break}return n}loadTable(e,i,s){if(!e.startPoint){P.warn("[Dxf] Entity is missing startPoint:",e.handle);return}if(e.cells.length===0){P.warn("[Dxf] Entity is missing cells:",e.handle);return}if(e.rowHeightArr.length===0){P.warn("[Dxf] Entity is missing rowHeightArr:",e.handle);return}if(e.columnWidthArr.length===0){P.warn("[Dxf] Entity is missing columnWidthArr:",e.handle);return}const n=new V,{cells:r,rowCount:a,columnCount:o,rowHeightArr:l,columnWidthArr:h}=e,d=[];let u=0;for(let y=0;y<a;y++){d[y]=[];for(let S=0;S<o;S++)d[y][S]=u<r.length?r[u++]:null}for(let y=0;y<a;y++)for(let S=0;S<o;S++){const w=d[y][S];if(!w||w.mergedValue!==0)continue;let x=1,E=1;for(;y+x<a&&d[y+x][S]&&d[y+x][S].mergedValue===1;)x++;for(;S+E<o&&d[y][S+E]&&d[y][S+E].mergedValue===1;)E++;w.rowSpan=x,w.colSpan=E}const f=[0];for(let y=0;y<a;y++)f.push(f[y]-l[y]);const m=[0];for(let y=0;y<o;y++)m.push(m[y]+h[y]);const b=[];for(let y=0;y<=a;y++){let S=m[0],w=!1;for(let x=0;x<o;x++){y>0&&d[y-1][x],y<a&&d[y][x];let E=!0;if(y===0||y===a)E=!0;else{const M=this._getMergeOwner(d,y-1,x,a,o),O=this._getMergeOwner(d,y,x,a,o);E=M!==O}E?w||(w=!0,S=m[x]):w&&(b.push(new p.Vector3(S,f[y],0),new p.Vector3(m[x],f[y],0)),w=!1)}w&&b.push(new p.Vector3(S,f[y],0),new p.Vector3(m[o],f[y],0))}for(let y=0;y<=o;y++){let S=f[0],w=!1;for(let x=0;x<a;x++){y>0&&d[x][y-1],y<o&&d[x][y];let E=!0;if(y===0||y===o)E=!0;else{const M=this._getMergeOwner(d,x,y-1,a,o),O=this._getMergeOwner(d,x,y,a,o);E=M!==O}E?w||(w=!0,S=f[x]):w&&(b.push(new p.Vector3(m[y],S,0),new p.Vector3(m[y],f[x],0)),w=!1)}w&&b.push(new p.Vector3(m[y],S,0),new p.Vector3(m[y],f[a],0))}if(b.length>0){const y=new p.BufferGeometry().setFromPoints(b),S=new V(G.LineSegment);S.geometry=y,S.material=me,S.layers.enableAll(),n.add(S)}for(let y=0;y<a;y++)for(let S=0;S<o;S++){const w=d[y][S];if(!w||w.mergedValue!==0)continue;const x=m[S],E=f[y];let M=0;for(let C=0;C<(w.colSpan||1);C++)M+=h[S+C];let O=0;for(let C=0;C<(w.rowSpan||1);C++)O+=l[y+C];w.colorIndex=e.colorIndex,w.height=w.textHeight||2.5;const T=this.getTableTextOffset(w.attachmentPoint||1,M,O);U.set(x,E,0),U.add(T),w.position=U.clone();const v=this.loadMText(w,i,s);v&&n.add(v)}if(e.blockRecordHandle){const y=this.getBlockByHandle(i.blocks,e.blockRecordHandle);if(y&&y.entities)for(const S of y.entities){S.isTable=!0;const w=this.loadEntity(S,i,e);w&&n.add(w)}}return n.matrix.decompose(U,ge,st),U.x+=e.startPoint.x,U.y+=e.startPoint.y,n.matrix.compose(U,ge,st),n}_getMergeOwner(e,i,s,n,r){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,n){const r=s*(e.x-i.x),a=s*(e.y-i.y),o=a,l=-r,h=new p.Vector3(i.x+r+o/6,i.y+a+l/6,0),d=new p.Vector3(i.x+r-o/6,i.y+a-l/6,0);n.push(i,h),n.push(i,d),n.push(h,d)}getBlockByHandle(e,i){if(!this.blocksCache){this.blocksCache={};for(const s in e){const n=e[s];!this.blocksCache[n.ownerHandle]&&(this.blocksCache[n.ownerHandle]=n)}}return this.blocksCache[i]}static updateMaterialUniforms(e){e instanceof p.ShaderMaterial&&(e.uniforms.u_cameraZoom&&(e.uniforms.u_cameraZoom=N.CameraZoomUniform),e.uniforms.u_viewportScale&&(e.uniforms.u_viewportScale=N.ViewportScaleUniform))}static transformAngleByOcsMatrix(e,i){const s=U.set(Math.cos(i)*1,Math.sin(i)*1,0),n=s.applyMatrix4(e);return Math.atan2(n.y,n.x)}static getArcAnglesByOcsMatrix(e,i,s){let n=z.getArcAngleSpanInRadian(i,s);const r=N.transformAngleByOcsMatrix(e,i),a=N.transformAngleByOcsMatrix(e,s);let o;if(z.areNumbersClose(n,Math.PI)){n=1;const l=N.transformAngleByOcsMatrix(e,i+n);o=z.getArcAngleSpanInRadian(r,l)}else{if(z.areNumbersClose(n,Math.PI*2))return[r,r+Math.PI*2];o=z.getArcAngleSpanInRadian(r,a)}return z.areNumbersClose(n,o,1e-5)?[r,a]:[a,r]}loadArc(e,i,s){if(!e.radius||e.radius<.001)return P.warn("[Dxf] The radius of arc (handle '"+e.handle+"') is undefined, ignored!"),void 0;if(!e.radius||e.radius<.001)return P.warn("[Dxf] The radius of arc (handle '"+e.handle+"') is too small, ignored!"),void 0;const n=new p.Vector3(0,0,1);e.extrusionDirectionX!==void 0&&e.extrusionDirectionY!==void 0&&e.extrusionDirectionZ!==void 0&&n.set(e.extrusionDirectionX,e.extrusionDirectionY,e.extrusionDirectionZ);const r=N.getOcsMatrix(n);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,z.areNumbersEqual(a,o,1e-6)))return;if(!z.areNumbersClose(z.getArcAngleSpanInRadian(a,o),Math.PI*2)){const O=N.getArcAnglesByOcsMatrix(r,a,o);a=O[0],o=O[1]}}const l=new p.ArcCurve(0,0,e.radius,a,o,this.angBase!==0);let h=1;const d=s;d?.xScale&&d?.yScale&&(h=Math.max(Math.abs(d.xScale),Math.abs(d.yScale)));const u=this.getDivision(a,o,e.radius*h),f=l.getPoints(u),m=new p.Vector3;let b=!1;this.enableRTC&&(b=H.checkAndRebasePositionsOnRTC(f,m));const y=new p.BufferGeometry().setFromPoints(f),S=new V(G.Line);S.geometry=y,S.material=me;const w=new p.Vector3;e.center&&(w.x=e.center.x,w.y=e.center.y);const x=new p.Vector3(e.center?.x,e.center?.y,e.center?.z).applyMatrix4(r.invert());w.x=x.x,w.y=x.y;const E=w,M=new V(G.Point);return M.geometry=za,M.material=Gs,M.userData.handle=e.handle,M.userData.isSnapObject=!0,M.userData.type="CircleCenter",M.layers.set(je),S.add(M),b?(this.setRTCUserData(S),E.x+=m.x,E.y+=m.y):H.shouldRebasePositionOnRTC(E)&&this.setRTCUserData(S),S.matrix.setPosition(E),S.layers.enableAll(),S}addTriangleFacingCamera(e,i,s,n){const r=new p.Vector3,a=new p.Vector3;r.subVectors(s,i),a.subVectors(n,i),r.cross(a);const o=new p.Vector3(i.x,i.y,i.z),l=new p.Vector3(s.x,s.y,s.z),h=new p.Vector3(n.x,n.y,n.z);r.z<0?e.push(h,l,o):e.push(o,l,h)}loadSolid(e,i,s){const n=e.points;if(!n||n.length<4)return;if(e.extrusionDirection&&e.extrusionDirection.z){U.set(0,0,e.extrusionDirection.z);const u=N.getOcsMatrix(U).invert();n.forEach(f=>{const m=U.set(f.x,f.y,0).applyMatrix4(u);f.x=m.x,f.y=m.y})}const r=[],a=[];this.addTriangleFacingCamera(r,n[0],n[1],n[2]),a.push(0,1,2),this.addTriangleFacingCamera(r,n[1],n[2],n[3]),a.push(3,4,5);const o=new p.Vector3;let l=!1;this.enableRTC&&(l=H.checkAndRebasePositionsOnRTC(r,o));const h=new p.BufferGeometry().setFromPoints(r);h.setIndex(a);const d=new V(G.Mesh);return d.geometry=h,d.material=gi,l&&(this.setRTCUserData(d),d.matrix.setPosition(o.x,o.y,0)),d.layers.enableAll(),d}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,n){if(!e)return;const r=s?.styleName||"";if(s&&s.fontFile&&s.fontFile.endsWith(".shx")){const h=s.fontFile+"_"+s.styleName;!this.statsInfo.unsupportedTextStyles[h]&&(this.statsInfo.unsupportedTextStyles[h]=0),this.statsInfo.unsupportedTextStyles[h]++}let a=.8;const o={_TCH_DIM:1.45,ROMANS:1};r&&o[r]&&(a=o[r]),n.xScale&&(a*=n.xScale),a>1&&r&&(a*=s?.xScale||1,i=i||s?.textHeight||0),i===0&&(r?i=1:i=.2);const l=this.createTextMeshByText(e,s,i,0,i/12,a);return l.traverse(h=>{h.geometry&&h.geometry.scale(a,1,1)}),l}createTextMeshByText(e,i,s=12,n=0,r=0,a=1,o=1/0,l=0){const h=new V,d=[];let u=0,f=0;i?.xScale;const m=n+s,b=i?.fontFile||"",y=typeof b=="string"&&b.toLowerCase().endsWith(".shx"),S=y?s*.06:s*.04,w=[];for(let M=0;M<e.length;M++){const O=e[M];O!==" "&&O!==`
@@ -1530,4 +1530,4 @@ message PBTileContent {\r
1530
1530
  }\r
1531
1531
  `,Qo=Symbol("INITIAL_FRUSTUM_CULLED");function Q1(c,t){c.traverse(e=>{e.frustumCulled=e[Qo]&&t})}const Ws=new p.Vector3,Ys=new p.Vector3,Zn=new p.Box3;class el extends jl.TilesRenderer{constructor(e,i){super(e);g(this,"highlighUsage");g(this,"transparentUsage");g(this,"pickUsage");g(this,"materialManager");g(this,"baseUrl");g(this,"propertyParser");g(this,"tilesetId");g(this,"onBeforeParseTile");g(this,"protoRoot");this.downloadQueue.maxJobs=6,this.parseQueue.maxJobs=4,this.optimizeRaycast=!1,this.errorTarget=8,this.loadSiblings=!1,this.tilesetId=i,this.baseUrl=e.replace(/\/[^\\/]*\/?$/,"/"),this.highlighUsage=new p.Group,this.highlighUsage.name="highlighUsage-"+this.tilesetId,this.group.add(this.highlighUsage),this.transparentUsage=new p.Group,this.transparentUsage.name="transparentUsage-"+this.tilesetId,this.group.add(this.transparentUsage),this.pickUsage=new p.Group,this.protoRoot=uc.parse(J1).root,this.propertyParser=new X1(this.baseUrl,this.protoRoot)}getVertexColorArray(e,i=new p.Color(16777215)){const s=[],{r:n,g:r,b:a}=i;for(let o=0;o<e;o+=3)s.push(n,r,a);return new Float32Array(s)}createBatchedMesh(e){const{position:i,uv:s,normal:n,indice:r,barycentric:a,userIds:o,materialId:l,batchTable:h}=e;let d=e.color;const u=o.map(x=>Xa(this.tilesetId,x)),f=new p.BufferGeometry;f.setAttribute("position",new p.Float32BufferAttribute(i,3)),f.setAttribute("normal",new p.Float32BufferAttribute(n,3)),f.setAttribute("uv",new p.Float32BufferAttribute(s,2)),f.setAttribute("tileObjectId",new p.Int32BufferAttribute(u,1)),f.setIndex(Array.from(r));const m=this.propertyParser.getMaterialParameters(l);d.length===0&&(d=this.getVertexColorArray(i.length,m?.color)),f.setAttribute("color",new p.Float32BufferAttribute(d,3));const b=a.length>0;b&&f.setAttribute("barycentric",new p.BufferAttribute(a,1));const y=this.materialManager?.createBatchMaterial(l,m,b),S=new p.Mesh(f,y),w=new p.Mesh(f,this.materialManager?.pickMaterial);return{mesh:S,pickMesh:w,batchTable:h}}createInstancedMesh(e){const{position:i,uv:s,color:n,normal:r,indice:a,barycentric:o,matrices:l,userIds:h,materialId:d}=e,u=h.map(M=>Xa(this.tilesetId,M)),f=h.length,m=new p.BufferGeometry;m.setIndex(Array.from(a)),m.setAttribute("position",new p.Float32BufferAttribute(i,3)),m.setAttribute("uv",new p.Float32BufferAttribute(s,2)),m.setAttribute("normal",new p.Float32BufferAttribute(r,3)),m.setAttribute("tileObjectId",new p.InstancedBufferAttribute(new Int32Array(u),1));const b=o.length>0;b&&m.setAttribute("barycentric",new p.BufferAttribute(o,1));const y=this.propertyParser.getMaterialParameters(d),S=this.materialManager?.createInstanceMaterial(d,y,b),w=new p.InstancedMesh(m,S,f);w.instanceMatrix=new p.InstancedBufferAttribute(new Float32Array(l),16);let x=n;x.length===0&&(x=this.getVertexColorArray(f*3,y?.color)),w.instanceColor=new p.InstancedBufferAttribute(x,3);const E=new p.InstancedMesh(m,this.materialManager?.pickMaterial,f);return E.instanceMatrix=new p.InstancedBufferAttribute(new Float32Array(l),16),{mesh:w,pickMesh:E,userIds:h}}getGeometryByUserIds(e){const i=Date.now(),s=[];return this.visibleTiles.forEach(n=>{const r=n.cached.scene.children;for(let a=0;a<r.length;a++){const o=r[a];if(!o||o.sourceMesh)continue;const l=o.userData.userIds;if(l)for(let h=0;h<e.length;h++){const d=e[h],u=l.indexOf(d);if(u>-1){const f=new p.BufferGeometry,m=o.geometry.getAttribute("position"),b=o.geometry.index,y=o.geometry.getAttribute("tileObjectId");if(o instanceof p.InstancedMesh){const S=new p.Matrix4;o.getMatrixAt(u,S),f.setAttribute("position",m.clone());const w=y.array[u*y.itemSize];f.setAttribute("tileObjectId",new p.Int32BufferAttribute(new Array(m.array.length/3).fill(w),1)),b&&f.setIndex(b),f.applyMatrix4(S)}else{const{indexStart:S,indexCount:w,positionStart:x,positionCount:E}=o.userData.batchTable.find(_=>_.userId===d),M=m.itemSize,O=m.array.slice(x*M,x*M+E*M),T=new p.Float32BufferAttribute(O,M);f.setAttribute("position",T);const v=y.array.slice(x,x+E),C=new p.Int32BufferAttribute(v,1);if(f.setAttribute("tileObjectId",C),b){const _=b.array.slice(S,S+w);for(let A=0;A<_.length;A++)_[A]-=x;f.setIndex(new p.BufferAttribute(_,1))}}f.applyMatrix4(o.matrixWorld),s.push(f)}}}}),P.info("[BimTiles] getGeometryByUserIds took "+(Date.now()-i)/1e3+"s"),s.length>1?Pe.mergeGeometries(s):s[0]}parseTile(e,i,s){this.onBeforeParseTile&&this.onBeforeParseTile(i),i._loadIndex=i._loadIndex||0,i._loadIndex++;const n=i.cached,r=n.transform;return new $1().parse(e,this.baseUrl,this.protoRoot).then(({batchedMeshes:o,instancedMeshes:l})=>{P.debug("[BimTiles] batchedMeshes:",o),P.debug("[BimTiles] instancedMeshes:",l);const h=new p.Group;h.name="TileGroup";const d=new p.Group;d.name="TileGroup-pick",o.forEach(f=>{const{mesh:m,pickMesh:b,batchTable:y}=this.createBatchedMesh(f);h.add(m),m.userData.batchTable=y,m.userData.userIds=y.map(S=>S.userId),d.add(b)}),l.forEach(f=>{const{mesh:m,pickMesh:b,userIds:y}=this.createInstancedMesh(f);h.add(m),m.userData.userIds=y,d.add(b)});const u=f=>{f.applyMatrix4(r)};u(h),h.traverse(f=>{f[Qo]=f.frustumCulled}),Q1(h,!this.autoDisableRendererCulling),u(d),n.scene=h,n.pickScene=d,this.onLoadModel&&this.onLoadModel(h,i)})}disposeTile(e){const i=e.cached;if(i.scene){const s=n=>{n.traverse(r=>{r.geometry&&r.geometry.dispose()}),n.removeFromParent()};s(i.scene),i.pickScene&&s(i.pickScene),this.onDisposeModel&&this.onDisposeModel(i.scene,e),i.scene=null,i.pickScene=null,i.materials=null,i.textures=null,i.geometry=null}this.activeTiles.delete(e),this.visibleTiles.delete(e),e._loadIndex++}preprocessNode(e,i,s){super.preprocessNode(e,i,s),Array.isArray(e.boundingVolume)&&(Zn.setFromArray(e.boundingVolume),e.cached&&e.cached.boundingVolume&&(Zn.getCenter(Ws),Zn.getSize(Ys),e.cached.boundingVolume.setObbData([Ws.x,Ws.y,Ws.z,Ys.x/2,0,0,0,Ys.y/2,0,0,0,Ys.z/2],e.cached.transform)))}async fetchTileSet(e,i,s){return fetch(e,i).then(n=>{if(n.ok)return n.json();throw new Error('BimTilesRenderer: Failed to load tileset "'+e+'" with status '+n.status+" : "+n.statusText)}).then(async n=>{const{material:r,userData:a,userId:o,userIdBox:l}=n.properties,h=[];if(r.url){const u=this.propertyParser.getProperty(r.url,i,"PBMaterials").then(f=>this.propertyParser.parseMaterial(f));h.push(u)}if(a.url){const u=this.propertyParser.getProperty(a.url,i,"PBUserData").then(f=>this.propertyParser.parseUserData(f));h.push(u)}if(o.url){const u=this.propertyParser.getProperty(o.url,i,"PBUserId").then(f=>this.propertyParser.parseUserId(f));h.push(u)}if(l.url){const u=this.propertyParser.getProperty(l.url,i,"PBUserIdBox").then(f=>this.propertyParser.parseUserIdBox(f,this.group.matrix));h.push(u)}await Promise.all(h);let d=e.replace(/\/[^\\/]*\/?$/,"");return d=new URL(d,window.location.href).toString(),this.preprocessNode(n.root,d,s),this.onLoadTileSet&&Promise.resolve().then(()=>{this.onLoadTileSet(n)}),n})}loadRootTileSet(e){const i=this.tileSets;if(e in i)return i[e]instanceof Error?Promise.reject(i[e]):Promise.resolve(i[e]);{const s=this.fetchTileSet(this.preprocessURL?this.preprocessURL(e):e,this.fetchOptions).then(n=>{i[e]=n,this.materialManager=new q1(this,{maxId:n.properties.userId.maxUserIdIndex})});return s.catch(n=>{P.error("[BimTiles] loadRootTileSet error:",n),i[e]=n}),i[e]=s,s}}update(){super.update()}setTileVisible(e,i){const{scene:s,pickScene:n}=e.cached,r=this.visibleTiles,a=this.group;i?(r.add(e),a.add(s),this.pickUsage.add(n),s.updateMatrixWorld(!0),n.updateMatrixWorld(!0)):(r.delete(e),a.remove(s),this.pickUsage.remove(n)),this.onTileVisibilityChange&&this.onTileVisibilityChange(s,e,i)}calculateError(e){const i=e.cached,s=i.inFrustum,n=this.cameras,r=this.cameraInfo,a=i.boundingVolume;let o=-1/0,l=1/0;for(let h=0,d=n.length;h<d;h++){if(!s[h])continue;const u=r[h],f=u.invScale;let m;if(u.isOrthographic){const b=u.pixelSize;m=e.geometricError/(b*f)}else{const b=a.distanceToPoint(u.position),y=b*f,S=u.sseDenominator;m=e.geometricError/(y*S),l=Math.min(l,y)}o=Math.max(o,m)}e.__distanceFromCamera=l,e.__error=o}}class Lr extends vn{constructor(e,i,s){super();g(this,"modelId");g(this,"_bbox");g(this,"tilesRenderer");g(this,"metadata");g(this,"statistics");this.modelId=e.modelId;const n=i+s.getMetadata().root;this.tilesRenderer=new el(n,Number(this.modelId)),this._bbox=e.bbox,this.metadata=s.getMetadata(),this.statistics=s.getStatistics()}getTilesRenderer(){return this.tilesRenderer}get materialManager(){return this.tilesRenderer.materialManager}get propertyParser(){return this.tilesRenderer.propertyParser}get highlighUsageGroup(){return this.tilesRenderer.highlighUsage}get transparentUsageGroup(){return this.tilesRenderer.transparentUsage}get pickUsageGroup(){return this.tilesRenderer.pickUsage}getModelObject(){return this.tilesRenderer.group}traverseObjectByUserId(e,i){if(i.userData.userIds){const n=i.userData.userIds;for(let r=0,a=n.length;r<a;r++)if(n[r]===e)return i}const s=i.children;for(let n=0,r=s.length;n<r;n++)if(this.traverseObjectByUserId(e,s[n]))return s[n]}getObjectByUserId(e){let i;return this.tilesRenderer.visibleTiles.forEach(s=>{i=this.traverseObjectByUserId(e,s.cached.scene)}),i}getBBox(){return this._bbox||(this._bbox=new p.Box3,this._bbox.setFromObject(this.getModelObject())),this._bbox}setObjectHoveredByUserId(e,i){this.materialManager.updateState(ii.Hovered,[e],i)}clearHovered(){this.materialManager.clearHovered()}setObjectHighlightedByUserIds(e,i){this.materialManager.updateState(ii.Highlighted,e,i)}clearHighlight(){this.materialManager.clearState(ii.Highlighted)}setDoubleSidedMaterials(){this.materialManager.setDoubleSidedMaterials()}revertDoubleSidedMaterials(){this.materialManager.revertDoubleSidedMaterials()}setObjectOpacityByUserIds(e,i){this.materialManager.updateState(ii.Transparent,e,!0,i)}clearObjectOpacityByUserIds(e){this.materialManager.updateState(ii.Transparent,e,!1)}setOpacity(e){this.materialManager.setOpacity(e)}clearOpacity(){this.materialManager.setOpacity(1)}setVisible(e){this.materialManager.setHidden(!e)}setObjectVisibleByUserIds(e,i){this.materialManager.updateState(ii.Hidden,e,!i)}hasVisibleObject(){return this.materialManager.hasVisibleObject()}hasInvisibleObject(){return this.materialManager.hasInvisibleObject()}getHoveredObject(){return this.materialManager?.getHoveredObject()}getBBoxByUserId(e){return this.propertyParser.getUserIdBox(e)}getUserDataByUserId(e){return this.propertyParser.getUserData(e)}getUserIds(){return this.propertyParser.getUserIds()}getUserId(e,i){return this.propertyParser.getUserIdsByFamilyInstanceId(e,i)}getUserData(e,i){const s=this.getUserId(e,i);if(s.length>0)return this.getUserDataByUserId(s[0])}getUserIdByFilter(e){return this.propertyParser.getUserIdByFilter(e)}setClipPlanes(e){this.materialManager.setClipPlanes(e)}}function eu(){let c=new Map;return{on(t,e){const i=c.get(t);i?i.push(e):c.set(t,[e])},off(t,e){const i=c.get(t);i&&(e?i.splice(i.indexOf(e)>>>0,1):c.set(t,[]))},emit(t,e){const i=c.get(t);i&&i.slice().map(s=>s(e)),c.get("*")&&c.get("*").slice().map(s=>s(t,e))}}}class tu{constructor(t){g(this,"viewer");g(this,"element");g(this,"content");g(this,"itemList");g(this,"handleMouseWheel");this.viewer=t,this.itemList={},this.handleMouseWheel=e=>{e.preventDefault(),this.element&&(this.element.scrollLeft+=e.deltaY)},t.addEventListener(le.ModelLoad,()=>{this.init()})}init(){this.destroy();const t=document.createElement("div");t.classList.add("model-layout-switch-bar");const e=document.createElement("div");e.classList.add("model-layout-switch-bar-content"),e.addEventListener("wheel",this.handleMouseWheel),this.viewer.getLayoutNames().forEach((i,s)=>{const n=this.createItem(i,s);this.itemList[i]=n,n.resetActivate=()=>{for(const r in this.itemList)this.itemList[r].resetActive()},e?.appendChild(n.element)}),this.element=t,this.content=e,this.element.appendChild(this.content),this.viewer.widgetContainer?.appendChild(this.element)}createItem(t,e){const i=new iu(this.viewer,t);return e===0&&i.setActive(!0),i}destroy(){for(const t in this.itemList){const e=this.itemList[t];e.destroy(),this.content?.removeChild(e.element)}this.itemList={},this.element&&this.content&&(this.element.removeChild(this.content),this.element.removeEventListener("wheel",this.handleMouseWheel),this.viewer.widgetContainer?.removeChild(this.element),this.element=void 0)}show(){this.element&&(this.element.style.display="block")}hide(){this.element&&(this.element.style.display="none")}}class iu{constructor(t,e){g(this,"viewer");g(this,"eventBus");g(this,"element");g(this,"resetActivate");g(this,"active");this.viewer=t,this.eventBus=eu(),this.active=!1,this.element=this.createItem(e),this.eventBus.on("activechange",i=>{this.resetActivate&&this.resetActivate(),i?(this.element.classList.add("activate"),this.viewer.activateLayout(e)):this.element.classList.remove("activate")})}createItem(t){const e=document.createElement("div"),i=document.createElement("span");return e.classList.add("model-layout-switch-item"),e.onclick=()=>{this.active=!this.active,this.eventBus.emit("activechange",this.active)},i.innerText=t,e.appendChild(i),e}setActive(t){this.active!==t&&(this.active=t,this.eventBus.emit("activechange",t))}resetActive(){this.active=!1,this.element.classList.remove("activate")}destroy(){this.eventBus.off("activechange")}}class tl{constructor(t){g(this,"element");g(this,"jobCount");this.jobCount=0;const e=document.createElement("div");e.classList.add("x-spinner");for(let s=0;s<4;s++)e.appendChild(document.createElement("span"));const i=t?.widgetContainer;i&&i.appendChild(e),this.element=e,this.setSpinnerVisibility(this.jobCount>0)}setSpinnerVisibility(t){t?this.element.classList.remove("hidden"):this.element.classList.add("hidden")}increaseJobCount(){this.setSpinnerVisibility(++this.jobCount>0)}decreaseJobCount(){if(this.jobCount<=0){console.warn("[Viewer] jobCount should be at least 1 here!");return}this.setSpinnerVisibility(--this.jobCount>0)}destroy(){this.element.remove(),this.jobCount=0}}class Rr{constructor(t){g(this,"width");g(this,"height");g(this,"container");g(this,"viewerContainer");g(this,"widgetContainer");this.width=0,this.height=0;let e=document.getElementById(t);e||(P.warn("[Container] containerId:",t,"is not found in dom tree! will append to document body"),e=document.body);const i=document.createElement("div");i.classList.add("x-container"),i.style.cssText="width: 100%; height: 100%; position: relative;",e.appendChild(i),this.container=i,this.width=e.clientWidth,this.height=e.clientHeight,this.initViewerContainer(),this.initWidgetContainer()}initViewerContainer(){const t=this.container;if(!t)return;const e=document.createElement("div");e.classList.add("x-viewer-container"),e.style.cssText="width: 100%; height: 100%; display: inline-block; position: relative; overflow: hidden;",t.appendChild(e),this.viewerContainer=e}initWidgetContainer(){const t=this.container;if(!t)return;const e=document.createElement("div");e.classList.add("x-widget-container"),t.appendChild(e),this.widgetContainer=e}get needResize(){const t=this.width!==this.container.clientWidth||this.height!==this.container.clientHeight;return t&&(this.width=this.container.clientWidth,this.height=this.container.clientHeight),t}destroy(){this.widgetContainer&&(this.widgetContainer.remove(),this.widgetContainer=void 0),this.viewerContainer&&(this.viewerContainer.remove(),this.viewerContainer=void 0),this.container.remove()}}class Fr{constructor(t){g(this,"element");g(this,"progressItems");g(this,"replaceReg");this.progressItems=new Map,this.replaceReg=new RegExp(/<em>[\s\S]*<\/em>/,"g");const e=document.createElement("div");e.classList.add("progress-bar"),t?.widgetContainer?.appendChild(e),this.element=e}addProgressItem(t,e="ProgressBar.Loading",i){this.progressItems.get(t)&&P.error("[Viewer] ProgressItem with id "+t+" already exists!");const s=document.createElement("div");s.classList.add("progress-bar-item"),s.innerHTML=We.t(e)+": <em></em>",this.element.append(s),this.progressItems.set(t,{div:s,onProgress:i})}removeProgressItem(t){this.progressItems.get(t)?.div.remove(),this.progressItems.delete(t),this.progressItems.size===0&&this.setVisible(!1)}updateProgress(t,e,i){const s=this.progressItems.get(t);if(!s)return;let n=e?""+e:"";e&&i!=null&&(n+=": "),i!=null&&(i<0||i>100?(console.warn("[ProgressBar] Invalid progress value: "+i),n+="--%"):n+=i.toFixed(2)+"%"),s.div.innerHTML=n}updateProgressBar(t,e,i=0,s=100){const n=this.progressItems.get(t);if(!n)return;const r=e instanceof ProgressEvent?e.loaded:e,a=e instanceof ProgressEvent?e.total:100,o=r*100/a*(s-i)/100+i;n.div.innerHTML=n.div.innerHTML.replace(this.replaceReg,"<em>"+(o<0||o>100?"--":o.toFixed(2))+"%</em>"),n.onProgress?.call(n,new ProgressEvent("LoadProgress",{loaded:r,total:100}))}setVisible(t){t?this.element.classList.remove("hidden"):this.element.classList.add("hidden")}delayRemoveProgressItem(t,e=3e3){setTimeout(()=>{this.progressItems.get(t)?.div.remove(),this.progressItems.delete(t)},e)}destroy(){this.progressItems.forEach(t=>{t.div.remove()}),this.progressItems.clear(),this.element.remove()}}var $e=(c=>(c.BaseViewer="BaseViewer",c.Viewer3d="Viewer3d",c.Viewer2d="Viewer2d",c.BimTilesViewer="BimTilesViewer",c))($e||{}),bt=(c=>(c.Perspective="Perspective",c.Orthographic="Orthographic",c))(bt||{});const su={enableSpinner:!0,containerId:"myCanvas"},W={LEFT:1,RIGHT:2,MIDDLE:4},R=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,OFFSET:4,DOLLY:8,ZOOM:16,TOUCH_ROTATE:32,TOUCH_TRUCK:64,TOUCH_OFFSET:128,TOUCH_DOLLY:256,TOUCH_ZOOM:512,TOUCH_DOLLY_TRUCK:1024,TOUCH_DOLLY_OFFSET:2048,TOUCH_DOLLY_ROTATE:4096,TOUCH_ZOOM_TRUCK:8192,TOUCH_ZOOM_OFFSET:16384,TOUCH_ZOOM_ROTATE:32768});function at(c){return c.isPerspectiveCamera}function Ue(c){return c.isOrthographicCamera}class nu{constructor(){g(this,"_listeners");this._listeners={}}addEventListener(t,e){const i=this._listeners;i[t]===void 0&&(i[t]=[]),i[t].indexOf(e)===-1&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return i[t]!==void 0&&i[t].indexOf(e)!==-1}removeEventListener(t,e){const s=this._listeners[t];if(s!==void 0){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}}removeAllEventListeners(t){if(!t){this._listeners={};return}Array.isArray(this._listeners[t])&&(this._listeners[t].length=0)}dispatchEvent(t){const i=this._listeners[t.type];if(i!==void 0){t.target=this;const s=i.slice(0);for(let n=0,r=s.length;n<r;n++)s[n].call(this,t)}}}const xi=Math.PI*2,Ka=Math.PI/2;function Kn(c,t){t.set(0,0),c.forEach(e=>{t.x+=e.clientX,t.y+=e.clientY}),t.x/=c.length,t.y/=c.length}function $n(c,t){return Ue(c)?(console.warn(t+" is not supported in OrthographicCamera"),!0):!1}const il=1e-5,Qi=Math.PI/180;function Ei(c,t,e){return Math.max(t,Math.min(e,c))}function ae(c,t=il){return Math.abs(c)<t}function re(c,t,e=il){return ae(c-t,e)}function $a(c,t){return Math.round(c/t)*t}function es(c){return isFinite(c)?c:c<0?-Number.MAX_VALUE:Number.MAX_VALUE}function ts(c){return Math.abs(c)<Number.MAX_VALUE?c:c*(1/0)}function Xs(c,t,e,i,s=1/0,n){i=Math.max(1e-4,i);const r=2/i,a=r*n,o=1/(1+a+.48*a*a+.235*a*a*a);let l=c-t;const h=t,d=s*i;l=Ei(l,-d,d),t=c-l;const u=(e.value+r*l)*n;e.value=(e.value-r*u)*o;let f=t+(l+u)*o;return h-c>0==f>h&&(f=h,e.value=(f-h)/n),f}function Ja(c,t,e,i,s=1/0,n,r){i=Math.max(1e-4,i);const a=2/i,o=a*n,l=1/(1+o+.48*o*o+.235*o*o*o);let h=t.x,d=t.y,u=t.z,f=c.x-h,m=c.y-d,b=c.z-u;const y=h,S=d,w=u,x=s*i,E=x*x,M=f*f+m*m+b*b;if(M>E){const D=Math.sqrt(M);f=f/D*x,m=m/D*x,b=b/D*x}h=c.x-f,d=c.y-m,u=c.z-b;const O=(e.x+a*f)*n,T=(e.y+a*m)*n,v=(e.z+a*b)*n;e.x=(e.x-a*O)*l,e.y=(e.y-a*T)*l,e.z=(e.z-a*v)*l,r.x=h+(f+O)*l,r.y=d+(m+T)*l,r.z=u+(b+v)*l;const C=y-c.x,_=S-c.y,A=w-c.z,I=r.x-y,B=r.y-S,k=r.z-w;return C*I+_*B+A*k>0&&(r.x=y,r.y=S,r.z=w,e.x=(r.x-y)/n,e.y=(r.y-S)/n,e.z=(r.z-w)/n),r}const Zs=1/8,ru=Be.isBrowser&&/Mac/.test(navigator.platform),au=!(Be.isBrowser&&"PointerEvent"in window);let q,Qa,Ks,Jn,ze,Y,te,bi,pt,mt,Qt,eo,to,nt,is,wi,io,Qn,so,er,tr,$s;class $ extends nu{constructor(e,i){super();g(this,"minPolarAngle");g(this,"maxPolarAngle");g(this,"minAzimuthAngle");g(this,"maxAzimuthAngle");g(this,"minDistance");g(this,"maxDistance");g(this,"infinityDolly");g(this,"minZoom");g(this,"maxZoom");g(this,"smoothTime");g(this,"draggingSmoothTime");g(this,"maxSpeed");g(this,"azimuthRotateSpeed");g(this,"polarRotateSpeed");g(this,"dollySpeed");g(this,"truckSpeed");g(this,"dollyToCursor");g(this,"dragToOffset");g(this,"verticalDragToForward");g(this,"boundaryFriction");g(this,"restThreshold");g(this,"colliderMeshes");g(this,"mouseButtons");g(this,"touches");g(this,"cancel");g(this,"_enabled");g(this,"_camera");g(this,"_yAxisUpSpace");g(this,"_yAxisUpSpaceInverse");g(this,"_state");g(this,"_domElement");g(this,"_viewport");g(this,"_target");g(this,"_targetEnd");g(this,"_focalOffset");g(this,"_focalOffsetEnd");g(this,"_spherical");g(this,"_sphericalEnd");g(this,"_zoom");g(this,"_zoomEnd");g(this,"_target0");g(this,"_position0");g(this,"_zoom0");g(this,"_focalOffset0");g(this,"_dollyControlAmount");g(this,"_dollyControlCoord");g(this,"_nearPlaneCorners");g(this,"_hasRested");g(this,"_boundary");g(this,"_boundaryEnclosesCamera");g(this,"_needsUpdate");g(this,"_updatedLastTime");g(this,"_elementRect");g(this,"_activePointers");g(this,"_isUserControllingRotate");g(this,"_isUserControllingDolly");g(this,"_isUserControllingTruck");g(this,"_isUserControllingOffset");g(this,"_isUserControllingZoom");g(this,"_thetaVelocity");g(this,"_phiVelocity");g(this,"_radiusVelocity");g(this,"_targetVelocity");g(this,"_focalOffsetVelocity");g(this,"_zoomVelocity");g(this,"_truckInternal");g(this,"_rotateInternal");g(this,"_dollyInternal");g(this,"_zoomInternal");this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.minDistance=0,this.maxDistance=1/0,this.infinityDolly=!1,this.minZoom=.01,this.maxZoom=1/0,this.smoothTime=.25,this.draggingSmoothTime=.125,this.maxSpeed=1/0,this.azimuthRotateSpeed=1,this.polarRotateSpeed=1,this.dollySpeed=1,this.truckSpeed=2,this.dollyToCursor=!1,this.dragToOffset=!1,this.verticalDragToForward=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=R.NONE,this._viewport=null,this._dollyControlAmount=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=Be.isBrowser?new DOMRect:{x:0,y:0,width:0,height:0,left:0,right:0,top:0,bottom:0},this._activePointers=[],this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new q.Vector3,this._focalOffsetVelocity=new q.Vector3,this._zoomVelocity={value:0},this._truckInternal=(x,E,M)=>{if(at(this._camera)){const O=Y.copy(this._camera.position).sub(this._target),T=this._camera.getEffectiveFOV()*Qi,v=O.length()*Math.tan(T*.5),C=this.truckSpeed*x*v/this._elementRect.height,_=this.truckSpeed*E*v/this._elementRect.height;this.verticalDragToForward?(M?this.setFocalOffset(this._focalOffsetEnd.x+C,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(C,0,!0),this.forward(-_,!0)):M?this.setFocalOffset(this._focalOffsetEnd.x+C,this._focalOffsetEnd.y+_,this._focalOffsetEnd.z,!0):this.truck(C,_,!0)}else if(Ue(this._camera)){const O=this._camera,T=this.truckSpeed*x*(O.right-O.left)/O.zoom/this._elementRect.width,v=this.truckSpeed*E*(O.top-O.bottom)/O.zoom/this._elementRect.height;M?this.setFocalOffset(this._focalOffsetEnd.x+T,this._focalOffsetEnd.y+v,this._focalOffsetEnd.z,!0):this.truck(T,v,!0)}},this._rotateInternal=(x,E)=>{const M=xi*this.azimuthRotateSpeed*x/this._elementRect.height,O=xi*this.polarRotateSpeed*E/this._elementRect.height;this.rotate(M,O,!0)},this._dollyInternal=(x,E,M)=>{const O=Math.pow(.95,-x*this.dollySpeed),T=this._sphericalEnd.radius*O,v=this._sphericalEnd.radius,C=v*(x>=0?-1:1);this.dollyTo(T),this.infinityDolly&&(T<this.minDistance||this.maxDistance===this.minDistance)&&(this._camera.getWorldDirection(Y),this._targetEnd.add(Y.normalize().multiplyScalar(C)),this._target.add(Y.normalize().multiplyScalar(C))),this.dollyToCursor&&(this._dollyControlAmount+=this._sphericalEnd.radius-v,this.infinityDolly&&(T<this.minDistance||this.maxDistance===this.minDistance)&&(this._dollyControlAmount-=C),this._dollyControlCoord.set(E,M))},this._zoomInternal=(x,E,M)=>{const O=Math.pow(.95,x*this.dollySpeed),T=this._zoomEnd;this.zoomTo(this._zoom*O),this.dollyToCursor&&(this._dollyControlAmount+=this._zoomEnd-T,this._dollyControlCoord.set(E,M))},typeof q>"u"&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=e,this._yAxisUpSpace=new q.Quaternion().setFromUnitVectors(this._camera.up,Ks),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=R.NONE,this._target=new q.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new q.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=new q.Spherical().setFromVector3(Y.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._nearPlaneCorners=[new q.Vector3,new q.Vector3,new q.Vector3,new q.Vector3],this._updateNearPlaneCorners(),this._boundary=new q.Box3(new q.Vector3(-1/0,-1/0,-1/0),new q.Vector3(1/0,1/0,1/0)),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlAmount=0,this._dollyControlCoord=new q.Vector2,this.mouseButtons={left:R.ROTATE,middle:R.DOLLY,right:R.TRUCK,wheel:at(this._camera)?R.DOLLY:Ue(this._camera)?R.ZOOM:R.NONE},this.touches={one:R.TOUCH_ROTATE,two:at(this._camera)?R.TOUCH_DOLLY_TRUCK:Ue(this._camera)?R.TOUCH_ZOOM_TRUCK:R.NONE,three:R.TOUCH_TRUCK};const s=new q.Vector2,n=new q.Vector2,r=new q.Vector2,a=x=>{if(!this._enabled||!this._domElement)return;const E=x.pointerType!=="mouse"?null:(x.buttons&W.LEFT)===W.LEFT?W.LEFT:(x.buttons&W.MIDDLE)===W.MIDDLE?W.MIDDLE:(x.buttons&W.RIGHT)===W.RIGHT?W.RIGHT:null;if(E!==null){const O=this._findPointerByMouseButton(E);O&&this._activePointers.splice(this._activePointers.indexOf(O),1)}const M={pointerId:x.pointerId,clientX:x.clientX,clientY:x.clientY,deltaX:0,deltaY:0,mouseButton:E};this._activePointers.push(M),this._domElement.removeEventListener("pointermove",l),this._domElement.removeEventListener("pointerup",d),this._domElement.addEventListener("pointermove",l),this._domElement.addEventListener("pointerup",d),y(x)},o=x=>{if(!this._enabled||!this._domElement)return;const E=(x.buttons&W.LEFT)===W.LEFT?W.LEFT:(x.buttons&W.MIDDLE)===W.MIDDLE?W.MIDDLE:(x.buttons&W.RIGHT)===W.RIGHT?W.RIGHT:null;if(E!==null){const O=this._findPointerByMouseButton(E);O&&this._activePointers.splice(this._activePointers.indexOf(O),1)}const M={pointerId:0,clientX:x.clientX,clientY:x.clientY,deltaX:0,deltaY:0,mouseButton:(x.buttons&W.LEFT)===W.LEFT?W.LEFT:(x.buttons&W.MIDDLE)===W.LEFT?W.MIDDLE:(x.buttons&W.RIGHT)===W.LEFT?W.RIGHT:null};this._activePointers.push(M),this._domElement.removeEventListener("mousemove",h),this._domElement.removeEventListener("mouseup",u),this._domElement.addEventListener("mousemove",h),this._domElement.addEventListener("mouseup",u),y(x)},l=x=>{const E=x.pointerId,M=this._findPointerById(E);if(M){if(M.clientX=x.clientX,M.clientY=x.clientY,M.deltaX=x.movementX,M.deltaY=x.movementY,x.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=0,(x.buttons&W.LEFT)===W.LEFT&&(this._state=this._state|this.mouseButtons.left),(x.buttons&W.MIDDLE)===W.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(x.buttons&W.RIGHT)===W.RIGHT&&(this._state=this._state|this.mouseButtons.right);S()}},h=x=>{const E=this._findPointerById(0);E&&(E.clientX=x.clientX,E.clientY=x.clientY,E.deltaX=x.movementX,E.deltaY=x.movementY,this._state=0,(x.buttons&W.LEFT)===W.LEFT&&(this._state=this._state|this.mouseButtons.left),(x.buttons&W.MIDDLE)===W.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(x.buttons&W.RIGHT)===W.RIGHT&&(this._state=this._state|this.mouseButtons.right),S())},d=x=>{const E=x.pointerId,M=this._findPointerById(E);if(M&&this._activePointers.splice(this._activePointers.indexOf(M),1),x.pointerType==="touch")switch(this._activePointers.length){case 0:this._state=R.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=R.NONE;w()},u=()=>{const x=this._findPointerById(0);x&&this._activePointers.splice(this._activePointers.indexOf(x),1),this._state=R.NONE,w()};let f=-1;const m=x=>{if(!this._enabled||this.mouseButtons.wheel===R.NONE)return;if(this.dollyToCursor||this.mouseButtons.wheel===R.ROTATE||this.mouseButtons.wheel===R.TRUCK){const v=performance.now();f-v<1e3&&this._getClientRect(this._elementRect),f=v}const E=ru?-1:-3,M=x.deltaMode===1?x.deltaY/E:x.deltaY/(E*10),O=this.dollyToCursor?(x.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(x.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case R.ROTATE:{this._rotateInternal(x.deltaX,x.deltaY),this._isUserControllingRotate=!0;break}case R.TRUCK:{this._truckInternal(x.deltaX,x.deltaY,!1),this._isUserControllingTruck=!0;break}case R.OFFSET:{this._truckInternal(x.deltaX,x.deltaY,!0),this._isUserControllingOffset=!0;break}case R.DOLLY:{this._dollyInternal(-M,O,T),this._isUserControllingDolly=!0;break}case R.ZOOM:{this._zoomInternal(-M,O,T),this._isUserControllingZoom=!0;break}}this.dispatchEvent({type:"control"})},b=x=>{if(!(!this._domElement||!this._enabled)&&this.mouseButtons.right===$.ACTION.NONE){const E=x instanceof PointerEvent?x.pointerId:(x instanceof MouseEvent,0),M=this._findPointerById(E);M&&this._activePointers.splice(this._activePointers.indexOf(M),1),this._domElement.removeEventListener("pointermove",l),this._domElement.removeEventListener("pointerup",d),this._domElement.removeEventListener("mousemove",h),this._domElement.removeEventListener("mouseup",u);return}},y=x=>{if(!this._enabled)return;if(Kn(this._activePointers,ze),this._getClientRect(this._elementRect),s.copy(ze),n.copy(ze),this._activePointers.length>=2){const M=ze.x-this._activePointers[1].clientX,O=ze.y-this._activePointers[1].clientY,T=Math.sqrt(M*M+O*O);r.set(0,T);const v=(this._activePointers[0].clientX+this._activePointers[1].clientX)*.5,C=(this._activePointers[0].clientY+this._activePointers[1].clientY)*.5;n.set(v,C)}if("pointerType"in x&&x.pointerType==="touch")switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three;break}else this._state=0,(x.buttons&W.LEFT)===W.LEFT&&(this._state=this._state|this.mouseButtons.left),(x.buttons&W.MIDDLE)===W.MIDDLE&&(this._state=this._state|this.mouseButtons.middle),(x.buttons&W.RIGHT)===W.RIGHT&&(this._state=this._state|this.mouseButtons.right);((this._state&R.ROTATE)===R.ROTATE||(this._state&R.TOUCH_ROTATE)===R.TOUCH_ROTATE||(this._state&R.TOUCH_DOLLY_ROTATE)===R.TOUCH_DOLLY_ROTATE||(this._state&R.TOUCH_ZOOM_ROTATE)===R.TOUCH_ZOOM_ROTATE)&&(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),((this._state&R.TRUCK)===R.TRUCK||(this._state&R.TOUCH_TRUCK)===R.TOUCH_TRUCK||(this._state&R.TOUCH_DOLLY_TRUCK)===R.TOUCH_DOLLY_TRUCK||(this._state&R.TOUCH_ZOOM_TRUCK)===R.TOUCH_ZOOM_TRUCK)&&(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),((this._state&R.DOLLY)===R.DOLLY||(this._state&R.TOUCH_DOLLY)===R.TOUCH_DOLLY||(this._state&R.TOUCH_DOLLY_TRUCK)===R.TOUCH_DOLLY_TRUCK||(this._state&R.TOUCH_DOLLY_OFFSET)===R.TOUCH_DOLLY_OFFSET||(this._state&R.TOUCH_DOLLY_ROTATE)===R.TOUCH_DOLLY_ROTATE)&&(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),((this._state&R.ZOOM)===R.ZOOM||(this._state&R.TOUCH_ZOOM)===R.TOUCH_ZOOM||(this._state&R.TOUCH_ZOOM_TRUCK)===R.TOUCH_ZOOM_TRUCK||(this._state&R.TOUCH_ZOOM_OFFSET)===R.TOUCH_ZOOM_OFFSET||(this._state&R.TOUCH_ZOOM_ROTATE)===R.TOUCH_ZOOM_ROTATE)&&(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),((this._state&R.OFFSET)===R.OFFSET||(this._state&R.TOUCH_OFFSET)===R.TOUCH_OFFSET||(this._state&R.TOUCH_DOLLY_OFFSET)===R.TOUCH_DOLLY_OFFSET||(this._state&R.TOUCH_ZOOM_OFFSET)===R.TOUCH_ZOOM_OFFSET)&&(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},S=()=>{if(!this._enabled)return;Kn(this._activePointers,ze);const x=Be.isBrowser?this._domElement&&document.pointerLockElement===this._domElement:!1,E=x?-this._activePointers[0].deltaX:n.x-ze.x,M=x?-this._activePointers[0].deltaY:n.y-ze.y;if(n.copy(ze),((this._state&R.ROTATE)===R.ROTATE||(this._state&R.TOUCH_ROTATE)===R.TOUCH_ROTATE||(this._state&R.TOUCH_DOLLY_ROTATE)===R.TOUCH_DOLLY_ROTATE||(this._state&R.TOUCH_ZOOM_ROTATE)===R.TOUCH_ZOOM_ROTATE)&&(this._rotateInternal(E,M),this._isUserControllingRotate=!0),(this._state&R.DOLLY)===R.DOLLY||(this._state&R.ZOOM)===R.ZOOM){const O=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,T=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&R.DOLLY)===R.DOLLY?(this._dollyInternal(M*Zs,O,T),this._isUserControllingDolly=!0):(this._zoomInternal(M*Zs,O,T),this._isUserControllingZoom=!0)}if((this._state&R.TOUCH_DOLLY)===R.TOUCH_DOLLY||(this._state&R.TOUCH_ZOOM)===R.TOUCH_ZOOM||(this._state&R.TOUCH_DOLLY_TRUCK)===R.TOUCH_DOLLY_TRUCK||(this._state&R.TOUCH_ZOOM_TRUCK)===R.TOUCH_ZOOM_TRUCK||(this._state&R.TOUCH_DOLLY_OFFSET)===R.TOUCH_DOLLY_OFFSET||(this._state&R.TOUCH_ZOOM_OFFSET)===R.TOUCH_ZOOM_OFFSET||(this._state&R.TOUCH_DOLLY_ROTATE)===R.TOUCH_DOLLY_ROTATE||(this._state&R.TOUCH_ZOOM_ROTATE)===R.TOUCH_ZOOM_ROTATE){const O=ze.x-this._activePointers[1].clientX,T=ze.y-this._activePointers[1].clientY,v=Math.sqrt(O*O+T*T),C=r.y-v;r.set(0,v);const _=this.dollyToCursor?(n.x-this._elementRect.x)/this._elementRect.width*2-1:0,A=this.dollyToCursor?(n.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&R.TOUCH_DOLLY)===R.TOUCH_DOLLY||(this._state&R.TOUCH_DOLLY_ROTATE)===R.TOUCH_DOLLY_ROTATE||(this._state&R.TOUCH_DOLLY_TRUCK)===R.TOUCH_DOLLY_TRUCK||(this._state&R.TOUCH_DOLLY_OFFSET)===R.TOUCH_DOLLY_OFFSET?(this._dollyInternal(C*Zs,_,A),this._isUserControllingDolly=!0):(this._zoomInternal(C*Zs,_,A),this._isUserControllingZoom=!0)}((this._state&R.TRUCK)===R.TRUCK||(this._state&R.TOUCH_TRUCK)===R.TOUCH_TRUCK||(this._state&R.TOUCH_DOLLY_TRUCK)===R.TOUCH_DOLLY_TRUCK||(this._state&R.TOUCH_ZOOM_TRUCK)===R.TOUCH_ZOOM_TRUCK)&&(this._truckInternal(E,M,!1),this._isUserControllingTruck=!0),((this._state&R.OFFSET)===R.OFFSET||(this._state&R.TOUCH_OFFSET)===R.TOUCH_OFFSET||(this._state&R.TOUCH_DOLLY_OFFSET)===R.TOUCH_DOLLY_OFFSET||(this._state&R.TOUCH_ZOOM_OFFSET)===R.TOUCH_ZOOM_OFFSET)&&(this._truckInternal(E,M,!0),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},w=()=>{Kn(this._activePointers,ze),n.copy(ze),this._activePointers.length===0&&this._domElement&&(this._domElement.removeEventListener("pointermove",l),this._domElement.removeEventListener("mousemove",h),this._domElement.removeEventListener("pointerup",d),this._domElement.removeEventListener("mouseup",u),this.dispatchEvent({type:"controlend"}))};this._addAllEventListeners=x=>{this._domElement=x,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",a),au&&this._domElement.addEventListener("mousedown",o),this._domElement.addEventListener("pointercancel",d),this._domElement.addEventListener("wheel",m,{passive:!1}),this._domElement.addEventListener("contextmenu",b)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",a),this._domElement.removeEventListener("mousedown",o),this._domElement.removeEventListener("pointercancel",d),this._domElement.removeEventListener("wheel",m),this._domElement.removeEventListener("contextmenu",b),this._domElement.removeEventListener("pointermove",l),this._domElement.removeEventListener("mousemove",h),this._domElement.removeEventListener("pointerup",d),this._domElement.removeEventListener("mouseup",u))},this.cancel=()=>{this._state!==R.NONE&&(this._state=R.NONE,this._activePointers.length=0,w())},i&&this.connect(i),this.update(0)}static install(e){q=e.THREE,Qa=Object.freeze(new q.Vector3(0,0,0)),Ks=Object.freeze(new q.Vector3(0,1,0)),Jn=Object.freeze(new q.Vector3(0,0,1)),ze=new q.Vector2,Y=new q.Vector3,te=new q.Vector3,bi=new q.Vector3,pt=new q.Vector3,mt=new q.Vector3,Qt=new q.Vector3,eo=new q.Vector3,to=new q.Vector3,nt=new q.Spherical,is=new q.Spherical,wi=new q.Box3,io=new q.Box3,Qn=new q.Sphere,so=new q.Quaternion,er=new q.Quaternion,tr=new q.Matrix4,$s=new q.Raycaster}static get ACTION(){return R}get camera(){return this._camera}set camera(e){this._camera=e,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this._domElement&&(e?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(e){this._spherical.radius===e&&this._sphericalEnd.radius===e||(this._spherical.radius=e,this._sphericalEnd.radius=e,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(e){this._spherical.theta===e&&this._sphericalEnd.theta===e||(this._spherical.theta=e,this._sphericalEnd.theta=e,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(e){this._spherical.phi===e&&this._sphericalEnd.phi===e||(this._spherical.phi=e,this._sphericalEnd.phi=e,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(e){this._boundaryEnclosesCamera=e,this._needsUpdate=!0}addEventListener(e,i){super.addEventListener(e,i)}removeEventListener(e,i){super.removeEventListener(e,i)}rotate(e,i,s=!1){return this.rotateTo(this._sphericalEnd.theta+e,this._sphericalEnd.phi+i,s)}rotateAzimuthTo(e,i=!1){return this.rotateTo(e,this._sphericalEnd.phi,i)}rotatePolarTo(e,i=!1){return this.rotateTo(this._sphericalEnd.theta,e,i)}rotateTo(e,i,s=!1){this._isUserControllingRotate=!1;const n=Ei(e,this.minAzimuthAngle,this.maxAzimuthAngle),r=Ei(i,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=n,this._sphericalEnd.phi=r,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,s||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const a=!s||re(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&re(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(a)}dolly(e,i=!1){return this.dollyTo(this._sphericalEnd.radius-e,i)}dollyTo(e,i=!1){this._isUserControllingDolly=!1;const s=this._sphericalEnd.radius,n=Ei(e,this.minDistance,this.maxDistance);if(this.colliderMeshes.length>=1){const o=this._collisionTest(),l=re(o,this._spherical.radius);if(!(s>n)&&l)return Promise.resolve();this._sphericalEnd.radius=Math.min(n,o)}else this._sphericalEnd.radius=n;this._needsUpdate=!0,i||(this._spherical.radius=this._sphericalEnd.radius);const a=!i||re(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(a)}zoom(e,i=!1){return this.zoomTo(this._zoomEnd+e,i)}zoomTo(e,i=!1){this._isUserControllingZoom=!1,this._zoomEnd=Ei(e,this.minZoom,this.maxZoom),this._needsUpdate=!0,i||(this._zoom=this._zoomEnd);const s=!i||re(this._zoom,this._zoomEnd,this.restThreshold);return this._createOnRestPromise(s)}truck(e,i,s=!1){this._camera.updateMatrix(),pt.setFromMatrixColumn(this._camera.matrix,0),mt.setFromMatrixColumn(this._camera.matrix,1),pt.multiplyScalar(e),mt.multiplyScalar(-i);const n=Y.copy(pt).add(mt),r=te.copy(this._targetEnd).add(n);return this.moveTo(r.x,r.y,r.z,s)}forward(e,i=!1){Y.setFromMatrixColumn(this._camera.matrix,0),Y.crossVectors(this._camera.up,Y),Y.multiplyScalar(e);const s=te.copy(this._targetEnd).add(Y);return this.moveTo(s.x,s.y,s.z,i)}elevate(e,i=!1){return Y.copy(this._camera.up).multiplyScalar(e),this.moveTo(this._targetEnd.x+Y.x,this._targetEnd.y+Y.y,this._targetEnd.z+Y.z,i)}moveTo(e,i,s,n=!1){this._isUserControllingTruck=!1;const r=Y.set(e,i,s).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,r,this.boundaryFriction),this._needsUpdate=!0,n||this._target.copy(this._targetEnd);const a=!n||re(this._target.x,this._targetEnd.x,this.restThreshold)&&re(this._target.y,this._targetEnd.y,this.restThreshold)&&re(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(a)}lookInDirectionOf(e,i,s,n=!1){const o=Y.set(e,i,s).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius);return this.setPosition(o.x,o.y,o.z,n)}fitToBox(e,i,{cover:s=!1,paddingLeft:n=0,paddingRight:r=0,paddingBottom:a=0,paddingTop:o=0}={}){const l=[],h=e.isBox3?wi.copy(e):wi.setFromObject(e);h.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const d=$a(this._sphericalEnd.theta,Ka),u=$a(this._sphericalEnd.phi,Ka);l.push(this.rotateTo(d,u,i));const f=Y.setFromSpherical(this._sphericalEnd).normalize(),m=so.setFromUnitVectors(f,Jn),b=re(Math.abs(f.y),1);b&&m.multiply(er.setFromAxisAngle(Ks,d)),m.multiply(this._yAxisUpSpaceInverse);const y=io.makeEmpty();te.copy(h.min).applyQuaternion(m),y.expandByPoint(te),te.copy(h.min).setX(h.max.x).applyQuaternion(m),y.expandByPoint(te),te.copy(h.min).setY(h.max.y).applyQuaternion(m),y.expandByPoint(te),te.copy(h.max).setZ(h.min.z).applyQuaternion(m),y.expandByPoint(te),te.copy(h.min).setZ(h.max.z).applyQuaternion(m),y.expandByPoint(te),te.copy(h.max).setY(h.min.y).applyQuaternion(m),y.expandByPoint(te),te.copy(h.max).setX(h.min.x).applyQuaternion(m),y.expandByPoint(te),te.copy(h.max).applyQuaternion(m),y.expandByPoint(te),y.min.x-=n,y.min.y-=a,y.max.x+=r,y.max.y+=o,m.setFromUnitVectors(Jn,f),b&&m.premultiply(er.invert()),m.premultiply(this._yAxisUpSpace);const S=y.getSize(Y),w=y.getCenter(te).applyQuaternion(m);if(at(this._camera)){const x=this.getDistanceToFitBox(S.x,S.y,S.z,s);l.push(this.moveTo(w.x,w.y,w.z,i)),l.push(this.dollyTo(x,i)),l.push(this.setFocalOffset(0,0,0,i))}else if(Ue(this._camera)){const x=this._camera,E=x.right-x.left,M=x.top-x.bottom,O=s?Math.max(E/S.x,M/S.y):Math.min(E/S.x,M/S.y);l.push(this.moveTo(w.x,w.y,w.z,i)),l.push(this.zoomTo(O,i)),l.push(this.setFocalOffset(0,0,0,i))}return Promise.all(l)}fitToSphere(e,i){const s=[],r=e instanceof q.Sphere?Qn.copy(e):$.createBoundingSphere(e,Qn);if(s.push(this.moveTo(r.center.x,r.center.y,r.center.z,i)),at(this._camera)){const a=this.getDistanceToFitSphere(r.radius);s.push(this.dollyTo(a,i))}else if(Ue(this._camera)){const a=this._camera,o=a.right-a.left,l=a.top-a.bottom,h=2*r.radius,d=Math.min(o/h,l/h);s.push(this.zoomTo(d,i))}return s.push(this.setFocalOffset(0,0,0,i)),Promise.all(s)}setLookAt(e,i,s,n,r,a,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1;const l=te.set(n,r,a),h=Y.set(e,i,s);this._targetEnd.copy(l),this._sphericalEnd.setFromVector3(h.sub(l).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const d=!o||re(this._target.x,this._targetEnd.x,this.restThreshold)&&re(this._target.y,this._targetEnd.y,this.restThreshold)&&re(this._target.z,this._targetEnd.z,this.restThreshold)&&re(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&re(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&re(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(d)}lerpLookAt(e,i,s,n,r,a,o,l,h,d,u,f,m,b=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1;const y=Y.set(n,r,a),S=te.set(e,i,s);nt.setFromVector3(S.sub(y).applyQuaternion(this._yAxisUpSpace));const w=bi.set(d,u,f),x=te.set(o,l,h);is.setFromVector3(x.sub(w).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(y.lerp(w,m));const E=is.theta-nt.theta,M=is.phi-nt.phi,O=is.radius-nt.radius;this._sphericalEnd.set(nt.radius+O*m,nt.phi+M*m,nt.theta+E*m),this.normalizeRotations(),this._needsUpdate=!0,b||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const T=!b||re(this._target.x,this._targetEnd.x,this.restThreshold)&&re(this._target.y,this._targetEnd.y,this.restThreshold)&&re(this._target.z,this._targetEnd.z,this.restThreshold)&&re(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&re(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&re(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(T)}setPosition(e,i,s,n=!1){return this.setLookAt(e,i,s,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,n)}setTarget(e,i,s,n=!1){const r=this.getPosition(Y),a=this.setLookAt(r.x,r.y,r.z,e,i,s,n);return this._sphericalEnd.phi=Ei(this.polarAngle,this.minPolarAngle,this.maxPolarAngle),a}setFocalOffset(e,i,s,n=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(e,i,s),this._needsUpdate=!0,n||this._focalOffset.copy(this._focalOffsetEnd);const r=!n||re(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&re(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&re(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}setOrbitPoint(e,i,s){this._camera.updateMatrixWorld(),pt.setFromMatrixColumn(this._camera.matrixWorldInverse,0),mt.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Qt.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const n=Y.set(e,i,s),r=n.distanceTo(this._camera.position),a=n.sub(this._camera.position);pt.multiplyScalar(a.x),mt.multiplyScalar(a.y),Qt.multiplyScalar(a.z),Y.copy(pt).add(mt).add(Qt),Y.z=Y.z+r,this.dollyTo(r,!1),this.setFocalOffset(-Y.x,Y.y,-Y.z,!1),this.moveTo(e,i,s,!1)}setBoundary(e){if(!e){this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),this._needsUpdate=!0;return}this._boundary.copy(e),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(e,i,s,n){if(e===null){this._viewport=null;return}this._viewport=this._viewport||new q.Vector4,typeof e=="number"?this._viewport.set(e,i,s,n):this._viewport.copy(e)}getDistanceToFitBox(e,i,s,n=!1){if($n(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const r=e/i,a=this._camera.getEffectiveFOV()*Qi,o=this._camera.aspect;return((n?r>o:r<o)?i:e/o)*.5/Math.tan(a*.5)+s*.5}getDistanceToFitSphere(e){if($n(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const i=this._camera.getEffectiveFOV()*Qi,s=Math.atan(Math.tan(i*.5)*this._camera.aspect)*2,n=1<this._camera.aspect?i:s;return e/Math.sin(n*.5)}getTarget(e){return(e&&e.isVector3?e:new q.Vector3).copy(this._targetEnd)}getPosition(e){return(e&&e.isVector3?e:new q.Vector3).setFromSpherical(this._sphericalEnd).applyQuaternion(this._yAxisUpSpaceInverse).add(this._targetEnd)}getFocalOffset(e){return(e&&e.isVector3?e:new q.Vector3).copy(this._focalOffsetEnd)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%xi,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=xi),this._spherical.theta+=xi*Math.round((this._sphericalEnd.theta-this._spherical.theta)/xi)}reset(e=!1){const i=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,e),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,e),this.zoomTo(this._zoom0,e)];return Promise.all(i)}saveState(){this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Ks),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert}update(e){const i=this._sphericalEnd.theta-this._spherical.theta,s=this._sphericalEnd.phi-this._spherical.phi,n=this._sphericalEnd.radius-this._spherical.radius,r=eo.subVectors(this._targetEnd,this._target),a=to.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(ae(i))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=Xs(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,u,1/0,e),this._needsUpdate=!0}if(ae(s))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const u=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=Xs(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,u,1/0,e),this._needsUpdate=!0}if(ae(n))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const u=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=Xs(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,u,this.maxSpeed,e),this._needsUpdate=!0}if(ae(r.x)&&ae(r.y)&&ae(r.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const u=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;Ja(this._target,this._targetEnd,this._targetVelocity,u,this.maxSpeed,e,this._target),this._needsUpdate=!0}if(ae(a.x)&&ae(a.y)&&ae(a.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const u=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;Ja(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,u,this.maxSpeed,e,this._focalOffset),this._needsUpdate=!0}if(this._dollyControlAmount!==0){if(at(this._camera)){const u=this._camera,f=Y.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).normalize().negate(),m=te.copy(f).cross(u.up).normalize();m.lengthSq()===0&&(m.x=1);const b=bi.crossVectors(m,f),y=this._sphericalEnd.radius*Math.tan(u.getEffectiveFOV()*Qi*.5),w=(this._sphericalEnd.radius-this._dollyControlAmount-this._sphericalEnd.radius)/this._sphericalEnd.radius,x=Y.copy(this._targetEnd).add(m.multiplyScalar(this._dollyControlCoord.x*y*u.aspect)).add(b.multiplyScalar(this._dollyControlCoord.y*y));this._targetEnd.lerp(x,w)}else if(Ue(this._camera)){const u=this._camera,f=Y.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(u.near+u.far)/(u.near-u.far)).unproject(u),m=te.set(0,0,-1).applyQuaternion(u.quaternion),b=bi.copy(f).add(m.multiplyScalar(-f.dot(u.up))),S=-(this._zoom-this._dollyControlAmount-this._zoomEnd)/this._zoom,w=Y.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).normalize().negate(),x=this._targetEnd.dot(w);this._targetEnd.lerp(b,S);const E=this._targetEnd.dot(w),M=w.multiplyScalar(E-x);this._targetEnd.sub(M)}this._target.copy(this._targetEnd),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._dollyControlAmount=0}if(ae(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const u=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=Xs(this._zoom,this._zoomEnd,this._zoomVelocity,u,1/0,e)}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0);const l=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,l),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target),(!ae(this._focalOffset.x)||!ae(this._focalOffset.y)||!ae(this._focalOffset.z))&&(this._camera.updateMatrixWorld(),pt.setFromMatrixColumn(this._camera.matrix,0),mt.setFromMatrixColumn(this._camera.matrix,1),Qt.setFromMatrixColumn(this._camera.matrix,2),pt.multiplyScalar(this._focalOffset.x),mt.multiplyScalar(-this._focalOffset.y),Qt.multiplyScalar(this._focalOffset.z),Y.copy(pt).add(mt).add(Qt),this._camera.position.add(Y)),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),Y.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const d=this._needsUpdate;return d&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):d?(this.dispatchEvent({type:"update"}),ae(i,this.restThreshold)&&ae(s,this.restThreshold)&&ae(n,this.restThreshold)&&ae(r.x,this.restThreshold)&&ae(r.y,this.restThreshold)&&ae(r.z,this.restThreshold)&&ae(a.x,this.restThreshold)&&ae(a.y,this.restThreshold)&&ae(a.z,this.restThreshold)&&ae(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!d&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._updatedLastTime=d,this._needsUpdate=!1,d}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:es(this.maxDistance),minZoom:this.minZoom,maxZoom:es(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:es(this.maxPolarAngle),minAzimuthAngle:es(this.minAzimuthAngle),maxAzimuthAngle:es(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,verticalDragToForward:this.verticalDragToForward,target:this._targetEnd.toArray(),position:Y.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(e,i=!1){const s=JSON.parse(e),n=Y.fromArray(s.position);this.enabled=s.enabled,this.minDistance=s.minDistance,this.maxDistance=ts(s.maxDistance),this.minZoom=s.minZoom,this.maxZoom=ts(s.maxZoom),this.minPolarAngle=s.minPolarAngle,this.maxPolarAngle=ts(s.maxPolarAngle),this.minAzimuthAngle=ts(s.minAzimuthAngle),this.maxAzimuthAngle=ts(s.maxAzimuthAngle),this.smoothTime=s.smoothTime,this.draggingSmoothTime=s.draggingSmoothTime,this.dollySpeed=s.dollySpeed,this.truckSpeed=s.truckSpeed,this.dollyToCursor=s.dollyToCursor,this.verticalDragToForward=s.verticalDragToForward,this._target0.fromArray(s.target0),this._position0.fromArray(s.position0),this._zoom0=s.zoom0,this._focalOffset0.fromArray(s.focalOffset0),this.moveTo(s.target[0],s.target[1],s.target[2],i),nt.setFromVector3(n.sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(nt.theta,nt.phi,i),this.zoomTo(s.zoom,i),this.setFocalOffset(s.focalOffset[0],s.focalOffset[1],s.focalOffset[2],i),this._needsUpdate=!0}connect(e){if(this._domElement){console.warn("camera-controls is already connected.");return}this._addAllEventListeners(e)}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&(this._domElement=void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_findPointerById(e){return this._activePointers.find(i=>i.pointerId===e)}_findPointerByMouseButton(e){return this._activePointers.find(i=>i.mouseButton===e)}_encloseToBoundary(e,i,s){const n=i.lengthSq();if(n===0)return e;const r=te.copy(i).add(e),o=this._boundary.clampPoint(r,bi).sub(r),l=o.lengthSq();if(l===0)return e.add(i);if(l===n)return e;if(s===0)return e.add(i).add(o);{const h=1+s*l/i.dot(o);return e.add(te.copy(i).multiplyScalar(h)).add(o.multiplyScalar(1-s))}}_updateNearPlaneCorners(){if(at(this._camera)){const e=this._camera,i=e.near,s=e.getEffectiveFOV()*Qi,n=Math.tan(s*.5)*i,r=n*e.aspect;this._nearPlaneCorners[0].set(-r,-n,0),this._nearPlaneCorners[1].set(r,-n,0),this._nearPlaneCorners[2].set(r,n,0),this._nearPlaneCorners[3].set(-r,n,0)}else if(Ue(this._camera)){const e=this._camera,i=1/e.zoom,s=e.left*i,n=e.right*i,r=e.top*i,a=e.bottom*i;this._nearPlaneCorners[0].set(s,r,0),this._nearPlaneCorners[1].set(n,r,0),this._nearPlaneCorners[2].set(n,a,0),this._nearPlaneCorners[3].set(s,a,0)}}_collisionTest(){let e=1/0;if(!(this.colliderMeshes.length>=1)||$n(this._camera,"_collisionTest"))return e;const s=Y.setFromSpherical(this._spherical).divideScalar(this._spherical.radius);tr.lookAt(Qa,s,this._camera.up);for(let n=0;n<4;n++){const r=te.copy(this._nearPlaneCorners[n]);r.applyMatrix4(tr);const a=bi.addVectors(this._target,r);$s.set(a,s),$s.far=this._spherical.radius+1;const o=$s.intersectObjects(this.colliderMeshes);o.length!==0&&o[0].distance<e&&(e=o[0].distance)}return e}_getClientRect(e){if(!this._domElement)return;const i=this._domElement.getBoundingClientRect();return e.x=i.left,e.y=i.top,this._viewport?(e.x+=this._viewport.x,e.y+=i.height-this._viewport.w-this._viewport.y,e.width=this._viewport.z,e.height=this._viewport.w):(e.width=i.width,e.height=i.height),e}_createOnRestPromise(e){return e?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(i=>{const s=()=>{this.removeEventListener("rest",s),i()};this.addEventListener("rest",s)}))}_addAllEventListeners(e){}_removeAllEventListeners(){}static createBoundingSphere(e,i=new q.Sphere){const s=i,n=s.center;wi.makeEmpty(),e.traverseVisible(a=>{a.isMesh&&wi.expandByObject(a)}),wi.getCenter(n);let r=0;return e.traverseVisible(a=>{if(!a.isMesh)return;const o=a,l=o.geometry.clone();if(l.applyMatrix4(o.matrixWorld),l.isBufferGeometry){const d=l.attributes.position;for(let u=0,f=d.count;u<f;u++)Y.fromBufferAttribute(d,u),r=Math.max(r,n.distanceToSquared(Y))}else{const d=l.attributes.position;for(let u=0,f=d.count;u<f;u++)Y.fromBufferAttribute(d,u),r=Math.max(r,n.distanceToSquared(Y))}}),s.radius=Math.sqrt(r),s}}var lt=(c=>(c[c.Orbit=0]="Orbit",c[c.FirstPerson=1]="FirstPerson",c[c.Plan=2]="Plan",c))(lt||{});class sl{constructor(t){g(this,"mode");g(this,"cameraManager");this.mode=lt.Orbit,this.cameraManager=t}setupControl(){const t=this.cameraManager.camera,e=this.cameraManager.cameraControls;e.mouseButtons={left:$.ACTION.ROTATE,middle:$.ACTION.DOLLY,right:$.ACTION.TRUCK,wheel:at(t)?$.ACTION.DOLLY:Ue(t)?$.ACTION.ZOOM:$.ACTION.NONE},e.touches={one:$.ACTION.TOUCH_ROTATE,two:at(t)?$.ACTION.TOUCH_DOLLY_TRUCK:Ue(t)?$.ACTION.TOUCH_ZOOM_TRUCK:$.ACTION.NONE,three:$.ACTION.TOUCH_TRUCK},e.dollyToCursor=!0,e.azimuthRotateSpeed=1,e.polarRotateSpeed=1,e.minDistance=1,e.maxDistance=300,e.minZoom=3,this.cameraManager.cameraControls.truckSpeed=2}adjustCameraByBBox(t){const e=this.cameraManager.cameraControls,i=new p.Vector3;t.getSize(i);const s=i.length();e.minDistance=1,e.maxDistance=s*10,e.minZoom=3}}class nl{constructor(t){g(this,"mode");g(this,"cameraManager");this.mode=lt.Plan,this.cameraManager=t}setupControl(){const t=this.cameraManager.camera,e=this.cameraManager.cameraControls;e.mouseButtons={left:$.ACTION.TRUCK,middle:$.ACTION.TRUCK,right:$.ACTION.TRUCK,wheel:at(t)?$.ACTION.DOLLY:Ue(t)?$.ACTION.ZOOM:$.ACTION.NONE},e.touches={one:$.ACTION.TOUCH_TRUCK,two:at(t)?$.ACTION.TOUCH_DOLLY_TRUCK:Ue(t)?$.ACTION.TOUCH_ZOOM_TRUCK:$.ACTION.NONE,three:$.ACTION.NONE},e.dollyToCursor=!0,e.azimuthRotateSpeed=0,e.polarRotateSpeed=0,e.truckSpeed=1,e.maxZoom=1/0,e.minZoom=-1/0}adjustCameraByBBox(t){}}const vi=50,ir=new p.Vector3;class ou{constructor(t){g(this,"viewer");g(this,"perspectiveCamera");g(this,"orthographicCamera");g(this,"activeCamera");g(this,"cameraControls");g(this,"previousDistance");g(this,"previousAzimuthRotateSpeed");g(this,"previousPolarRotateSpeed");g(this,"previousDollySpeed");g(this,"previousTruckSpeed");g(this,"previousMouseLeft");g(this,"enableKeyDown");g(this,"controlsMap");g(this,"activeControls");g(this,"projection");g(this,"anchor");g(this,"onKeyDown");g(this,"onChange");this.previousDistance=-1,this.previousAzimuthRotateSpeed=1,this.previousPolarRotateSpeed=1,this.previousDollySpeed=1,this.previousTruckSpeed=2,this.previousMouseLeft=$.ACTION.NONE,this.enableKeyDown=!0,this.projection=bt.Perspective,this.onKeyDown=s=>{if(!this.enableKeyDown)return;const n=this.cameraControls,r=this.viewer.getPixelSizeInWorldCoord()*10,a=this.viewer.name===$e.Viewer3d||this.viewer.name===$e.BimTilesViewer;switch(s.code){case"ArrowLeft":a?n.rotate(.1,0,!0):this.viewer.name===$e.Viewer2d&&n.truck(r,0,!0);break;case"ArrowRight":a?n.rotate(-.1,0,!0):this.viewer.name===$e.Viewer2d&&n.truck(-r,0,!0);break;case"ArrowUp":a?n.rotate(0,.1,!0):this.viewer.name===$e.Viewer2d&&n.truck(0,r,!0);break;case"ArrowDown":a?n.rotate(0,-.1,!0):this.viewer.name===$e.Viewer2d&&n.truck(0,-r,!0);break;case"KeyW":a&&(Ue(this.activeCamera)?n.zoom(.01,!0):n.dolly(1,!0));break;case"KeyA":a&&n.truck(-r,0,!0);break;case"KeyS":a&&(Ue(this.activeCamera)?n.zoom(-.01,!0):n.dolly(-1,!0));break;case"KeyD":a&&n.truck(r,0,!0);break;case"KeyQ":a&&n.truck(0,-r,!0);break;case"KeyE":a&&n.truck(0,r,!0);break}},this.onChange=()=>{this.viewer.enableRender()},this.viewer=t;const e=t.viewerContainer,i=e.clientWidth/e.clientHeight;this.perspectiveCamera=new p.PerspectiveCamera(Oo,i,on,ln),this.orthographicCamera=new p.OrthographicCamera(vi*i/-2,vi*i/2,vi/2,vi/-2,on,ln),this.activeCamera=this.perspectiveCamera,this.setupCameras(),$.install({THREE:p}),this.cameraControls=new $(this.perspectiveCamera,t.getInputManager()),this.controlsMap={[lt.Orbit]:new sl(this),[lt.Plan]:new nl(this)},this.activeControls=this.controlsMap[lt.Orbit],this.setupControls(),this.setProjection(bt.Perspective),this.anchor=this.createAnchor()}get viewerContainer(){return this.viewer.viewerContainer}get inputManager(){return this.viewer.getInputManager()}createAnchor(){const t=document.createElement("div");return t.className="anchor",this.viewerContainer?.appendChild(t),this.cameraControls.addEventListener("control",()=>{if(this.isOrbitPointVisible()){const e=this.getTarget(),i=Oe.world2Screen(e,this.activeCamera,this.viewerContainer);this.setAnchorPosition(i.x,i.y)}}),t}setAnchorPosition(t,e){this.anchor.style.left=t+"px",this.anchor.style.top=e+"px"}setOrbitPointVisible(t){t?this.anchor.classList.add("active"):this.anchor.classList.remove("active")}isOrbitPointVisible(){return this.anchor.classList.contains("active")}setOrthoCameraAspect(t,e){const i=t/e;this.orthographicCamera.left=-50*i/2,this.orthographicCamera.right=vi*i/2,this.orthographicCamera.top=vi/2,this.orthographicCamera.bottom=-50/2,this.orthographicCamera.updateProjectionMatrix()}setupCameras(){this.setCameraPositionAndTarget(this.perspectiveCamera)}setCameraPositionAndTarget(t){t.position.z=10,t.position.y=10,t.position.x=10,t.lookAt(new p.Vector3(0,0,0))}setupControls(){const t=this.cameraControls;t.smoothTime=.1,t.draggingSmoothTime=0,t.infinityDolly=!0,t.setTarget(0,0,0),t.addEventListener("controlstart",()=>this.onChange),t.addEventListener("control",()=>this.onChange),t.addEventListener("update",()=>this.viewer.dispatchEvent(le.ControlChange)),t.addEventListener("rest",()=>this.onChange),this.inputManager.addEventListener("keydown",this.onKeyDown)}setOrthoCamera(){if(this.activeControls.mode===lt.FirstPerson)return;this.previousDistance=this.cameraControls.distance,this.cameraControls.distance=200;const{width:t,height:e}=this.getDims();this.setupOrthoCamera(e,t),this.activeCamera=this.orthographicCamera,this.projection=bt.Orthographic}getDims(){const t=new p.Vector3;this.perspectiveCamera.getWorldDirection(t);const e=new p.Vector3;this.cameraControls.getTarget(e);const i=e.clone().sub(this.perspectiveCamera.position),s=i.dot(t),{clientWidth:n,clientHeight:r}=this.viewer.viewerContainer,a=n/r,o=this.perspectiveCamera.fov,l=s*2*Math.atan(o*(Math.PI/180)/2);return{width:l*a,height:l}}setupOrthoCamera(t,e){this.cameraControls.mouseButtons.wheel=$.ACTION.ZOOM;const i=this.perspectiveCamera,s=this.orthographicCamera;s.zoom=1,s.left=e/-2,s.right=e/2,s.top=t/2,s.bottom=t/-2,s.updateProjectionMatrix(),s.position.copy(i.position),s.quaternion.copy(i.quaternion),this.cameraControls.camera=s}setPerspectiveCamera(){const t=this.cameraControls;t.mouseButtons.wheel=$.ACTION.DOLLY;const e=this.perspectiveCamera,i=this.orthographicCamera;e.position.copy(i.position),e.quaternion.copy(i.quaternion),e.updateProjectionMatrix(),t.camera=e,t.mouseButtons.wheel=$.ACTION.DOLLY,this.activeCamera=e,this.projection=bt.Perspective,t.distance=this.previousDistance,t.zoomTo(1)}update(t){const e=this.cameraControls.update(t);return this.camera.updateMatrixWorld(),e}updateAspect(){const{clientWidth:t,clientHeight:e}=this.viewer.viewerContainer;this.perspectiveCamera.aspect=t/e,this.perspectiveCamera.updateProjectionMatrix(),this.setOrthoCameraAspect(t,e)}get camera(){return this.activeCamera}enableKeyControl(t){this.enableKeyDown=t}getTarget(){return this.cameraControls.getTarget(ir)}getPosition(){return this.cameraControls.getPosition(ir)}adjustCameraByBBox(t){const e=this.camera.near,i=this.camera.far,s=new p.Vector3;t.getSize(s);const n=s.length(),r=5,a=n/r,o=n*r;if(e>a||i<o){const l=h=>j.numberToString(h);P.info("[Viewer] BBox's longest side is: "+l(n)),e>a&&(P.warn("[Viewer] camera.near("+l(e)+") shouldn't bigger than "+l(a)+", will change it!"),this.camera.near=a),i<o&&(P.warn("[Viewer] camera.far("+l(i)+") shouldn't smaller than "+l(o)+", will change it!"),this.camera.far=o)}this.activeControls.adjustCameraByBBox(t),this.cameraControls.update(0)}enableControl(t){this.cameraControls.enabled=t}get enableRotate(){const t=this.cameraControls;return!!t.azimuthRotateSpeed||!!t.polarRotateSpeed}set enableRotate(t){const e=this.cameraControls;t?(e.azimuthRotateSpeed=this.previousAzimuthRotateSpeed,e.polarRotateSpeed=this.previousPolarRotateSpeed):(this.previousAzimuthRotateSpeed=e.azimuthRotateSpeed,this.previousPolarRotateSpeed=e.polarRotateSpeed,e.azimuthRotateSpeed=0,e.polarRotateSpeed=0)}enableZoom(t){const e=this.cameraControls;t?e.dollySpeed=this.previousDollySpeed:(this.previousDollySpeed=e.dollySpeed,e.dollySpeed=0)}enablePan(t){const e=this.cameraControls;t?e.truckSpeed=this.previousTruckSpeed:(this.previousTruckSpeed=e.dollySpeed,e.truckSpeed=0)}enableMouseLeft(t){const e=this.cameraControls;t?e.mouseButtons.left=this.previousMouseLeft:(this.previousMouseLeft=e.mouseButtons.left,e.mouseButtons.left=$.ACTION.NONE)}setCameraPosition(t){this.cameraControls.setPosition(t.x,t.y,t.z)}setCameraTarget(t){this.cameraControls.setTarget(t.x,t.y,t.z)}flyTo(t,e,i=!0){const s=this.cameraControls;s.setLookAt(t.x,t.y,t.z,e.x,e.y,e.z,i),s.setFocalOffset(0,0,0,!0)}flyToPosition(t,e,i){this.cameraControls.moveTo(t,e,i,!0)}flyToBox(t,e){const i=new p.Sphere;t.getBoundingSphere(i),this.cameraControls.fitToBox(t,!0,e)}fitToSphere(t){this.cameraControls.fitToSphere(t,!0)}flyToObject(t){const e=new p.Box3().setFromObject(t),i=new p.Sphere;e.getBoundingSphere(i),this.cameraControls.fitToSphere(i,!0)}flyToViewpoint(t){this.flyTo(t.eye,t.look),t.zoom!=null&&(this.orthographicCamera.zoom=t.zoom)}getDistanceToFitSphere(t){return this.cameraControls.getDistanceToFitSphere(t)}setNavigationMode(t){this.activeControls.mode!==t&&(this.activeControls=this.controlsMap[t],this.activeControls.setupControl())}getProjection(){return this.projection}setProjection(t){this.projection!==t&&(this.projection=t,t===bt.Orthographic?this.setOrthoCamera():this.setPerspectiveCamera())}setOrbitPoint(t){this.cameraControls.setOrbitPoint(t.x,t.y,t.z)}getCameraDirection(){return this.activeCamera.getWorldDirection(ir)}getCameraConfig(){return{eye:this.activeCamera.position,look:this.getTarget(),up:this.activeCamera.up,near:this.activeCamera.near,far:this.activeCamera.far,zoom:this.activeCamera.zoom}}getCurrentViewpoint(){return{eye:this.activeCamera.position,look:this.getTarget(),up:this.activeCamera.up,zoom:this.activeCamera.zoom}}setCameraConfig(t){const e=this.cameraControls,{near:i=on,far:s=ln,up:n=new p.Vector3(0,1,0),zoom:r=1,eye:a,look:o}=t;this.activeCamera.near=i,this.activeCamera.far=s,this.activeCamera.up.set(n.x,n.y,n.z),this.activeCamera.updateProjectionMatrix(),e.updateCameraUp(),e.zoomTo(r),e.setLookAt(a.x,a.y,a.z,o.x,o.y,o.z,!0),e.setFocalOffset(0,0,0,!0)}destroy(){this.anchor.remove(),this.inputManager.removeEventListener("keydown",this.onKeyDown),this.perspectiveCamera.removeFromParent(),this.orthographicCamera.removeFromParent()}}const ai=class ai extends Yo{tableName(){return"fonts"}static instance(){return!ai._instance&&(ai._instance=new ai),ai._instance}query(t){let e;return new Promise((i,s)=>{super.query(n=>{if(!n){i(e);return}!n.value||n.value.fileName!==t||(e=n.value)},n=>{s(n)})})}queryAll(){const t=Object.create(null,{queryAll:{get:()=>super.queryAll}});return new Promise((e,i)=>{t.queryAll.call(this,s=>{e(s)},s=>{i(s)})})}};g(ai,"_instance");let Fi=ai;var rl=(c=>(c[c.Horizontal=0]="Horizontal",c[c.Vertical=1]="Vertical",c[c.All=2]="All",c))(rl||{}),Ne=(c=>(c[c.Shapes=0]="Shapes",c[c.Bigfont=1]="Bigfont",c[c.Unifont=2]="Unifont",c))(Ne||{});class al extends ql.Font{constructor(e,i){super(i);g(this,"info");g(this,"orientation");g(this,"baseUp");g(this,"baseDown");g(this,"fileHeader");g(this,"fileVersion");g(this,"fileName");g(this,"data");g(this,"order");g(this,"unsupportedChars");this.info="",this.orientation=rl.Horizontal,this.baseUp=0,this.baseDown=0,this.fileHeader="",this.fileVersion="",this.order=0,this.unsupportedChars={},this.fileName=e}addUnsupportedChar(e){!this.unsupportedChars[e]&&(this.unsupportedChars[e]=0),this.unsupportedChars[e]++}getFontFile(){return{order:this.order,data:this.data,info:this.info,orientation:this.orientation,baseUp:this.baseUp,baseDown:this.baseDown,fileName:this.fileName,fileHeader:this.fileHeader,fileVersion:this.fileVersion}}setFontFile(e){this.fileName=e.fileName,this.data=e.data,this.info=e.info,this.order=e.order,this.orientation=e.orientation,this.baseUp=e.baseUp,this.baseDown=e.baseDown,this.fileHeader=e.fileHeader,this.fileVersion=e.fileVersion}async setFontDataToIndexedDb(){const e=this.getFontFile();return new Promise((i,s)=>{Fi.instance().save(e,()=>{console.log("[FontFile] Saved '"+this.fileName+"' ("+this.fileHeader+") to indexedDb"),i()},n=>s("[FontFile] Failed to save '"+this.fileName+"' ("+this.fileHeader+") to indexedDb! "+n))})}async getFontDataByIndexedDb(){return Fi.instance().query(this.fileName)}releaseFontData(){this.data={}}}class ei extends al{constructor(e,i){super(e,i);g(this,"reversed");this.reversed=!1,i instanceof ArrayBuffer?this.data=this.parseTTF(i):i.fileName?this.setFontFile(i):this.data=i,this.type="MeshFont"}generateShapes(e,i){return super.generateShapes(e,i)}getCharShape(e,i){const s=no(e,i,0,0,this.data)?.path;return!s&&this.addUnsupportedChar(e),s}getNotFoundTextShape(e){return no("?",e,0,0,this.data)?.path}parseTTF(e){function i(n,r){const a=Math.round,o={},l=1e5/((n.unitsPerEm||2048)*72),h=n.encoding.cmap.glyphIndexMap,d=Object.keys(h);for(let u=0;u<d.length;u++){const f=d[u],m=n.glyphs.glyphs[h[f]];if(f!==void 0){const b={ha:a(m.advanceWidth*l),x_min:a(m.xMin*l),x_max:a(m.xMax*l),o:""};r&&(m.path.commands=s(m.path.commands)),m.path.commands.forEach(function(y){y.type.toLowerCase()==="c"&&(y.type="b"),b.o+=y.type.toLowerCase()+" ",y.x!==void 0&&y.y!==void 0&&(b.o+=a(y.x*l)+" "+a(y.y*l)+" "),y.x1!==void 0&&y.y1!==void 0&&(b.o+=a(y.x1*l)+" "+a(y.y1*l)+" "),y.x2!==void 0&&y.y2!==void 0&&(b.o+=a(y.x2*l)+" "+a(y.y2*l)+" ")}),o[String.fromCodePoint(m.unicode)]=b}}return{glyphs:o,familyName:n.getEnglishName("fullName"),ascender:a(n.ascender*l),descender:a(n.descender*l),underlinePosition:n.tables.post.underlinePosition,underlineThickness:n.tables.post.underlineThickness,boundingBox:{xMin:n.tables.head.xMin,xMax:n.tables.head.xMax,yMin:n.tables.head.yMin,yMax:n.tables.head.yMax},resolution:1e3,original_font_information:n.tables.name}}function s(n){const r=[];let a;n.forEach(function(l){l.type.toLowerCase()==="m"?(a=[l],r.push(a)):l.type.toLowerCase()!=="z"&&a.push(l)});const o=[];return r.forEach(function(l){const h={type:"m",x:l[l.length-1].x,y:l[l.length-1].y};o.push(h);for(let d=l.length-1;d>0;d--){const u=l[d],f={type:u.type};u.x2!==void 0&&u.y2!==void 0?(f.x1=u.x2,f.y1=u.y2,f.x2=u.x1,f.y2=u.y1):u.x1!==void 0&&u.y1!==void 0&&(f.x1=u.x1,f.y1=u.y1),f.x=l[d-1].x,f.y=l[d-1].y,o.push(f)}}),o}return i(Gl.parse(e),this.reversed)}}function no(c,t,e,i,s){const n=s.glyphs[c];if(!n)return;const r=new p.ShapePath;let a,o,l,h,d,u,f,m;if(n.o){const b=n._cachedOutline||(n._cachedOutline=n.o.split(" "));for(let y=0,S=b.length;y<S;)switch(b[y++]){case"m":a=b[y++]*t+e,o=b[y++]*t+i,r.moveTo(a,o);break;case"l":a=b[y++]*t+e,o=b[y++]*t+i,r.lineTo(a,o);break;case"q":l=b[y++]*t+e,h=b[y++]*t+i,d=b[y++]*t+e,u=b[y++]*t+i,r.quadraticCurveTo(d,u,l,h);break;case"b":l=b[y++]*t+e,h=b[y++]*t+i,d=b[y++]*t+e,u=b[y++]*t+i,f=b[y++]*t+e,m=b[y++]*t+i,r.bezierCurveTo(d,u,f,m,l,h);break}}return{offsetX:n.ha*t,path:r}}class Q{static GetBytes(t){switch(typeof t){case"string":{const e=new Uint16Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return new Uint8Array(e.buffer)}case"number":return t-Math.floor(t)==0?t>4294967295?(function(e){return e[0]=t,new Uint8Array(e.buffer)})(new Float64Array(1)):(function(e){return e[0]=t,new Uint8Array(e.buffer)})(new Int32Array(1)):(function(e){return e[0]=t,new Uint8Array(e.buffer)})(new Float64Array(1));case"boolean":return(function(e){return e[0]=Number(t),e})(new Uint8Array(1));default:if(t instanceof Array){const e=[];for(let r=0;r<t.length;r++)e.push(Q.GetBytes(t[r]));let i=0;for(let r=0;r<e.length;r++)i+=e[r].length;const s=new Uint8Array(i);let n=0;for(let r=0;r<e.length;r++)for(let a=0;a<e[r].length;a++)s[n++]=e[r][a];return s}throw"Can't Convert To Bytes!!"}}static Get1Bytes(t){switch(typeof t){case"number":case"boolean":return new Uint8Array([Number(t)]);default:if(t instanceof Array){const e=[];for(let r=0;r<t.length;r++)e.push(this.Get1Bytes(t[r]));let i=0;for(let r=0;r<e.length;r++)i+=e[r].length;const s=new Uint8Array(i);let n=0;for(let r=0;r<e.length;r++)for(let a=0;a<e[r].length;a++)s[n++]=e[r][a];return s}throw"Can't Convert To Bytes!!"}}static byteTosbyte(t){return(t&127)-(t&128?128:0)}static ToBoolean(t,e){return e=e||0,!!t[e]}static ToInt8(t,e){return e=e||0,t[e]&128?-((t[e]^255)+1):t[e]}static ToUInt8(t,e){return e=e||0,t[e]}static ToInt16(t,e){e=e||0;const i=t.slice(e,e+2);return new Int16Array(i.buffer,0,1)[0]}static ToInt32(t,e){e=e||0;const i=t.slice(e,e+4);return new Int32Array(i.buffer,0,1)[0]}static ToUInt16(t,e){e=e||0;const i=t.slice(e,e+2);return new Uint16Array(i.buffer,0,1)[0]}static ToUInt32(t,e){e=e||0;const i=t.slice(e,e+4);return new Uint32Array(i.buffer,0,1)[0]}static ToChar(t,e){e=e||0;const i=t.slice(e,e+2);return String.fromCharCode(new Uint16Array(i.buffer,0,1)[0])}static ToAscii(t,e){return e=e||0,String.fromCharCode(t[e])}static ToAsciiString(t,e,i){e=e||0,i=i||t.length,i+e>t.length&&(i-=e);let s="";for(let n=0;n<i;n++)s+=String.fromCharCode(t[e+n]||0);return s}static ToUTF16String(t,e,i){e=e||0,i=i||t.length,i+e>t.length&&(i-=e);const s=new Uint8Array(i);for(let n=0;n<i;n++)s[n]=t[e+n]||0;return String.fromCharCode.apply(null,Array.from(new Uint16Array(s.buffer,0,i/2)))}static ToFloat32(t,e){e=e||0;const i=t.slice(e,e+4);return new Float32Array(i.buffer,0,1)[0]}static ToFloat64(t,e){e=e||0;const i=t.slice(e,e+8);return new Float64Array(i.buffer,0,1)[0]}}let gn;function lu(){const c=[[161,169,161,254],[176,247,161,254],[129,160,64,254],[170,254,64,160],[168,169,64,160],[170,175,161,254],[248,254,161,254],[161,167,64,160]],t=new Uint16Array(23940);let e=0;for(const[s,n,r,a]of c)for(let o=r;o<=a;o++)if(o!==127)for(let l=s;l<=n;l++)t[e++]=o<<8|l;const i=new TextDecoder("gbk").decode(t);for(gn=new Uint16Array(65536),e=0;e<i.length;e++)gn[i.charCodeAt(e)]=t[e]}function cu(c){!gn&&lu();const t=new Uint8Array(c.length*2);let e=0;for(let i=0;i<c.length;i++){const s=c.charCodeAt(i);if(s<128)t[e++]=s;else{const n=gn[s];t[e++]=n&255,t[e++]=n>>8}}return t.subarray(0,e)}new p.Vector2;class ys extends p.Shape{constructor(e,i){super();g(this,"width");g(this,"lastPoint");g(this,"polylines");g(this,"bounds");this.width=0,this.bounds=new p.Box2,this.lastPoint=e,this.polylines=i,this.width=this.calcWidth(i)}offset(e){const i=[];for(let s=0;s<this.polylines.length;s++){const n=this.polylines[s],r=[];for(let a=0;a<n.length;a++){const o=n[a];r.push(o.clone().add(e))}i.push(r)}return new ys(this.lastPoint,i)}transform(e){const i=[];for(let s=0;s<this.polylines.length;s++){const n=this.polylines[s],r=[];for(let a=0;a<n.length;a++){const o=n[a];r.push(o.clone().applyMatrix3(e))}i.push(r)}return new ys(this.lastPoint.clone().applyMatrix3(e),i)}calcWidth(e){const i=this.bounds;for(let r=0;r<e.length;r++){const a=e[r];for(let o=0;o<a.length;o++){const l=a[o];i.expandByPoint(l)}}const s=i.min.x||0;return(i.max.x||0)-s}toThreeGeometry(){const e=this.polylines,i=[],s=[];let n=0;const r=new p.BufferGeometry;for(let a=0;a<e.length;a++){const o=e[a];for(let l=0;l<o.length;l++){const h=o[l];i.push(h.x,h.y,0),l===o.length-1||s.push(n,n+1),n++}}return r.userData={advanceWidth:this.width},r.setAttribute("position",new p.Float32BufferAttribute(i,3)),r.setIndex(s),r}}const yt=class yt{static parserHeader(t,e){let i="",s=!1,n=0;const r=!0;for(;r;){const a=t.readInt8(),o=String.fromCharCode(a);if(s)o===e[n]?n++:(s=!1,n=0);else{if(o===e[n]){s=!0,n++;continue}i+=o}if(s&&n===e.length)break}return i}static getCode(t){const e=cu(t);return e.length<2?e[0]:e.length<4?Q.ToUInt16(e,0):Q.ToUInt32(e,0)}static parserCode(t,e,i){let s=new p.Vector2;const n=[];let r=[];const a=[];let o=!1;for(let l=0;l<e.length;l++){const h=e[l];switch(h){case 0:break;case 1:o=!0,r.push(s.clone());break;case 2:o=!1,r.length>1?(n.push(r.slice()),r=[]):s.set(0,0);break;case 3:l++,i/=e[l];break;case 4:l++,i*=e[l];break;case 5:if(a.length===4)throw"The position stack is only four locations deep";a.push(s.clone());break;case 6:if(a.length===0)break;s=a.pop(),r.length>1&&(n.push(r.slice()),r=[]),o&&r.push(s.clone());break;case 7:{let d=0,u,f=i*t.baseUp;const m=s.clone();switch(r.length>1&&(n.push(r.slice()),r=[]),t.fontType){case Ne.Shapes:l++,d=e[l];break;case Ne.Bigfont:l++,d=e[l],d==0&&(l++,d=Q.ToUInt16(new Uint8Array([e[l++],e[l++]]),0),m.x=e[l++]*i,m.y=e[l++]*i,f=e[l]*i);break;case Ne.Unifont:l+=2,d=Q.ToUInt16(new Uint8Array([e[l-1],e[l]]),0);break}d!==0&&(u=t.getGraphicDataByCodeWithOffset(d,f,m),u&&(n.push(...u.polylines.slice()),s=u.lastPoint.clone()))}break;case 8:{const d=new p.Vector2;d.x=Q.byteTosbyte(e[++l]),d.y=Q.byteTosbyte(e[++l]),s.add(d.multiplyScalar(i)),o&&r.push(s.clone())}break;case 9:for(;;){const u=new p.Vector2;if(u.x=Q.byteTosbyte(e[++l]),u.y=Q.byteTosbyte(e[++l]),!Number.isFinite(u.x)||!Number.isFinite(u.y)||u.x==0&&u.y==0)break;s.add(u.multiplyScalar(i)),o&&r.push(s.clone())}break;case 10:{const d=e[++l]*i,u=Q.byteTosbyte(e[++l]),f=(u&112)>>4;let m=u&7;m==0&&(m=8);const b=Math.PI/4;let y=b*m,S=yt.CIRCLE_SPAN;u<0&&(S=-S,y=-y);const w=b*f,x=w+y,E=s.clone().sub(new p.Vector2(Math.cos(w)*d,Math.sin(w)*d));if(s=E.clone().add(new p.Vector2(Math.cos(x)*d,Math.sin(x)*d)),o){let M=w;const O=!0;for(;O&&(M+=S,!!Number.isFinite(M));)if(u>=0&&M<x||u<0&&M>x)r.push(E.clone().add(new p.Vector2(d*Math.cos(M),d*Math.sin(M))));else break;r.push(s.clone())}}break;case 11:{const d=e[++l],u=e[++l],f=e[++l],m=e[++l],b=(f*255+m)*i,y=Q.byteTosbyte(e[++l]),S=(y&112)>>4;let w=y&7;w==0&&(w=8),u!=0&&w--;const x=Math.PI/4;let E=x*w,M=yt.CIRCLE_SPAN,O=1;y<0&&(M=-M,E=-E,O=-1);let T=x*S,v=T+E;T+=x*d/256*O,v+=x*u/256*O;const C=s.clone().sub(new p.Vector2(b*Math.cos(T),b*Math.sin(T)));if(s=C.clone().add(new p.Vector2(b*Math.cos(v),b*Math.sin(v))),o){let _=T;const A=!0;for(;A&&(_+=M,!!Number.isFinite(_));)if(y>0&&_<v||y<0&&_>v)r.push(C.clone().add(new p.Vector2(b*Math.cos(_),b*Math.sin(_))));else break;r.push(s.clone())}}break;case 12:{const d=new p.Vector2;d.x=Q.byteTosbyte(e[++l])*i,d.y=Q.byteTosbyte(e[++l])*i;let u=Q.byteTosbyte(e[++l]);u<-127&&(u=-127),o&&(u==0?r.push(s.clone().add(d)):r.push(yt.generateArcPoints(s,d,u/127))),s.add(d)}break;case 13:for(;;){const u=new p.Vector2;if(u.x=Q.byteTosbyte(e[++l])*i,u.y=Q.byteTosbyte(e[++l])*i,!Number.isFinite(u.x)||!Number.isFinite(u.y)||u.x==0&&u.y==0)break;let f=Q.byteTosbyte(e[++l]);f<-127&&(f=-127),o&&(f==0?r.push(s.clone().add(u)):r.push(yt.generateArcPoints(s.clone(),u,f/127))),s.add(u)}break;case 14:l=yt.skipCode(t,e,++l);break;default:if(h>15){const d=(h&240)>>4,u=h&15,f=new p.Vector2;switch(u){case 0:f.x=1;break;case 1:f.x=1,f.y=.5;break;case 2:f.x=1,f.y=1;break;case 3:f.x=.5,f.y=1;break;case 4:f.y=1;break;case 5:f.x=-.5,f.y=1;break;case 6:f.x=-1,f.y=1;break;case 7:f.x=-1,f.y=.5;break;case 8:f.x=-1;break;case 9:f.x=-1,f.y=-.5;break;case 10:f.x=-1,f.y=-1;break;case 11:f.x=-.5,f.y=-1;break;case 12:f.y=-1;break;case 13:f.x=.5,f.y=-1;break;case 14:f.x=1,f.y=-1;break;case 15:f.x=1,f.y=-.5;break}s.add(f.multiplyScalar(d*i)),o&&r.push(s.clone())}break}}return new ys(s,n)}static skipCode(t,e,i){switch(e[i]){case 0:break;case 1:break;case 2:break;case 3:case 4:i++;break;case 5:break;case 6:break;case 7:switch(t.fontType){case Ne.Shapes:i++;break;case Ne.Bigfont:i++,e[i]==0&&(i+=6);break;case Ne.Unifont:i+=2;break}break;case 8:i+=2;break;case 9:for(;;){const r=e[++i],a=e[++i];if(r===void 0||a===void 0||r==0&&a==0)break}break;case 10:i+=2;break;case 11:i+=5;break;case 12:i+=3;break;case 13:for(;;){const r=e[++i],a=e[++i];if(r===void 0||a===void 0||r==0&&a==0)break;e[++i]}break}return i}static generateArcPoints(t,e,i){const s=t.clone().add(e),n=i<0,r=!1;i=Math.abs(i);const a=e.length()/2,o=a*i,l=2*Math.atan(1/i),h=new p.Vector2(e.y,-e.x);h.normalize(),h.multiplyScalar(o);const d=Math.abs(a/Math.sin(l/2)),u=t.add(e.divideScalar(2));r!==n?u.add(h):u.sub(h);const f=t.sub(u),m=s.sub(u);let b=Math.atan2(f.y,f.x);const y=Math.atan2(m.y,m.x);let S=yt.CIRCLE_SPAN;n?(S=-S,b<y&&(b+=2*Math.PI)):b>y&&(b-=2*Math.PI);let w=b;const x=!0;for(;x;){if(w+=S,!n&&w<y||n&&w>y)return u.add(new p.Vector2(d*Math.cos(w),d*Math.sin(w)));break}return s}};g(yt,"FILE_STOP_FLAG",["\r",`
1532
1532
  `,""]),g(yt,"CIRCLE_SPAN",Math.PI/18);let Lt=yt;const sr={130:[[[5,0],[5,9.5]],[[4,7.1],[2.6,6.6],[2.1,6.2],[1.7,5.4],[1.6,4],[2.1,3],[2.6,2.6],[3.9,2.2],[6.1,2.2],[7.5,2.6],[8,3.1],[8.4,3.9],[8.4,5.2],[7.9,6.1],[7.5,6.6],[6.1,7.1],[4,7.1]]],131:[[[3,0],[7,0]],[[5,0],[5,9.5]],[[4,7.1],[2.6,6.6],[2.1,6.2],[1.7,5.4],[1.6,4],[2.1,3],[2.6,2.6],[3.9,2.2],[6.1,2.2],[7.5,2.6],[8,3.1],[8.4,3.9],[8.4,5.2],[7.9,6.1],[7.5,6.6],[6.1,7.1],[4,7.1]]],132:[[[3,0],[7,0]],[[4,0],[4,9.5]],[[6,0],[6,9.5]],[[4,7.1],[2.6,6.6],[2.1,6.2],[1.7,5.4],[1.6,4],[2.1,3],[2.6,2.6],[3.9,2.2],[6.1,2.2],[7.5,2.6],[8,3.1],[8.4,3.9],[8.4,5.2],[7.9,6.1],[7.5,6.6],[6.1,7.1],[4,7.1]]],133:[[[3,0],[7,0]],[[4,0],[4,9.5]],[[6,0],[6,9.5]],[[4,7.1],[2.6,6.6],[2.1,6.2],[1.7,5.4],[1.6,4],[2.1,3],[2.6,2.6],[3.9,2.2],[6.1,2.2],[7.5,2.6],[8,3.1],[8.4,3.9],[8.4,5.2],[7.9,6.1],[7.5,6.6],[6.1,7.1],[4,7.1]],[[3,9.5],[7,9.5]]],134:[[[3,0],[7,0]],[[5,0],[5,9.5]],[[4,7.1],[2.6,6.6],[2.1,6.2],[1.7,5.4],[1.6,4],[2.1,3],[2.6,2.6],[3.9,2.2],[6.1,2.2],[7.5,2.6],[8,3.1],[8.4,3.9],[8.4,5.2],[7.9,6.1],[7.5,6.6],[6.1,7.1],[4,7.1]],[[12,10],[9,10],[9,6]],[[9,8],[11,8]]],135:[[[3,0],[7,0]],[[4,0],[4,9.5]],[[6,0],[6,9.5]],[[4,7.1],[2.6,6.6],[2.1,6.2],[1.7,5.4],[1.6,4],[2.1,3],[2.6,2.6],[3.9,2.2],[6.1,2.2],[7.5,2.6],[8,3.1],[8.4,3.9],[8.4,5.2],[7.9,6.1],[7.5,6.6],[6.1,7.1],[4,7.1]],[[12,10],[9,10],[9,6]],[[9,8],[11,8]]],136:[[[3,0],[7,0]],[[4,0],[4,9.5]],[[6,0],[6,9.5]],[[4,7.1],[2.6,6.6],[2.1,6.2],[1.7,5.4],[1.6,4],[2.1,3],[2.6,2.6],[3.9,2.2],[6.1,2.2],[7.5,2.6],[8,3.1],[8.4,3.9],[8.4,5.2],[7.9,6.1],[7.5,6.6],[6.1,7.1],[4,7.1]],[[3,9.5],[7,9.5]],[[12,10],[9,10],[9,6]],[[9,8],[11,8]]],178:[[[1.142,9.285],[1.142,9.428],[1.285,9.714],[1.428,9.857],[1.714,10],[2.285,10],[2.571,9.857],[2.714,9.714],[2.857,9.428],[2.857,9.142],[2.714,8.857],[2.428,8.428],[1,7],[3,7]]],8960:[[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]],[[0,0],[8,8]]],20393:[[[0,0],[0,6.666]],[[0,4.761],[1.428,6.19],[2.38,6.666],[3.809,6.666],[4.761,6.19],[5.238,4.761],[5.238,0]],[[5.238,4.761],[6.666,6.19],[7.619,6.666],[9.047,6.666],[10,6.19],[10.476,4.761],[10.476,0]],[[11.142,9.285],[11.142,9.428],[11.285,9.714],[11.428,9.857],[11.714,10],[12.285,10],[12.571,9.857],[12.714,9.714],[12.857,9.428],[12.857,9.142],[12.714,8.857],[12.428,8.428],[11,7],[13,7]]],41123:[],55714:[[[2,5.9],[2.6,6.1],[3.4,7],[3.4,1]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],55970:[[[2.3,5.6],[2.3,5.9],[2.6,6.4],[2.9,6.7],[3.4,7],[4.6,7],[5.1,6.7],[5.4,6.4],[5.7,5.9],[5.7,5.3],[5.4,4.7],[4.9,3.9],[2,1],[6,1]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],56226:[[[2.6,7],[5.7,7],[4,4.7],[4.9,4.7],[5.4,4.4],[5.7,4.1],[6,3.3],[6,2.7],[5.7,1.9],[5.1,1.3],[4.3,1],[3.4,1],[2.6,1.3],[2.3,1.6],[2,2.1]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],56482:[[[4.9,7],[2,3],[6.3,3]],[[4.9,7],[4.9,1]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],56738:[[[5.4,7],[2.6,7],[2.3,4.4],[2.6,4.7],[3.4,5],[4.3,5],[5.1,4.7],[5.7,4.1],[6,3.3],[6,2.7],[5.7,1.9],[5.1,1.3],[4.3,1],[3.4,1],[2.6,1.3],[2.3,1.6],[2,2.1]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],56994:[[[5.4,6.1],[5.1,6.7],[4.3,7],[3.7,7],[2.9,6.7],[2.3,5.9],[2,4.4],[2,3],[2.3,1.9],[2.9,1.3],[3.7,1],[4,1],[4.9,1.3],[5.4,1.9],[5.7,2.7],[5.7,3],[5.4,3.9],[4.9,4.4],[4,4.7],[3.7,4.7],[2.9,4.4],[2.3,3.9],[2,3]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],57250:[[[2,7],[6,7],[3.1,1]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],57506:[[[3.4,7],[2.6,6.7],[2.3,6.1],[2.3,5.6],[2.6,5],[3.1,4.7],[4.3,4.4],[5.1,4.1],[5.7,3.6],[6,3],[6,2.1],[5.7,1.6],[5.4,1.3],[4.6,1],[3.4,1],[2.6,1.3],[2.3,1.6],[2,2.1],[2,3],[2.3,3.6],[2.9,4.1],[3.7,4.4],[4.9,4.7],[5.4,5],[5.7,5.6],[5.7,6.1],[5.4,6.7],[4.6,7],[3.4,7]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],57762:[[[5.7,5],[5.4,4.1],[4.9,3.6],[4,3.3],[3.7,3.3],[2.9,3.6],[2.3,4.1],[2,5],[2,5.3],[2.3,6.1],[2.9,6.7],[3.7,7],[4,7],[4.9,6.7],[5.4,6.1],[5.7,5],[5.7,3.6],[5.4,2.1],[4.9,1.3],[4,1],[3.4,1],[2.6,1.3],[2.3,1.9]],[[2.9,8],[1.7,7.4],[.6,6.3],[0,4.6],[0,3.4],[.6,1.7],[1.7,.6],[2.9,0],[4.6,0],[5.7,.6],[6.9,1.7],[7.4,3.4],[7.4,4.6],[6.9,6.3],[5.7,7.4],[4.6,8],[2.9,8]]],60070:[[[0,6],[10,6],[10,4]]],60326:[[[0,7],[0,5],[10,5]]]},ro=new p.Matrix3,us=class us extends al{constructor(e,i){super(e,i);g(this,"isExtend");g(this,"isUniCode");g(this,"isEmbedded");g(this,"fontType");g(this,"textShapesCache");g(this,"graphicData");if(this.isExtend=!1,this.isUniCode=!0,this.isEmbedded=!1,this.fontType=Ne.Unifont,this.textShapesCache=new Map,this.graphicData=new Map,i instanceof ArrayBuffer){const s=new vs(i),n=Lt.parserHeader(s,Lt.FILE_STOP_FLAG),r=n.split(" ");switch(r[1]){case"shapes":this.parseShapeFont(s),this.fontType=Ne.Shapes;break;case"bigfont":this.parseBigFont(s),this.fontType=Ne.Bigfont;break;case"unifont":this.parseUniFont(s),this.fontType=Ne.Unifont;break}this.fileHeader=r[0],this.fileVersion=r[2]}else this.setFontFile(i)}generateShapes(e,i){const s=[];let n=0;for(let r=0;r<e.length;r++){const a=e[r];if(a===" "){n+=i;continue}const o=this.getCharShape(a,i);if(!o){n+=i,this.addUnsupportedChar(a);continue}s.push(o.offset(new p.Vector2(n,0))),n+=o.width}return s}getCharShape(e,i){let s=Lt.getCode(e);s===0&&(s=e.charCodeAt(0));const n=this.getGraphicDataByCode(s,i);if(!n)return this.addUnsupportedChar?.(e),null;if(n.polylines&&n.polylines.length===0&&(n.width=i*.8),typeof n.width!="number"||n.width<=0){const r=n,a=r.xMin!=null?r.xMin:0,o=r.xMax!=null?r.xMax:0;n.width=Math.max(.1,o-a)}return n}getGraphicDataByCode(e,i){const s=e+"_"+i;if(this.textShapesCache.has(s))return this.textShapesCache.get(s);if(e===0)return;const n=this.data;let r;if(!this.graphicData.has(e)){if(n[e]){const a=n[e],o=us.DEFAULT_SIZE/this.baseUp;r=Lt.parserCode(this,a,o),this.graphicData.set(e,r)}else if(sr[e]){const a=[];for(let o=0;o<sr[e].length;o++)a.push(sr[e][o].map(l=>new p.Vector2(l[0],l[1])));r=new ys(new p.Vector2,a),this.graphicData.set(e,r)}}if(this.graphicData.has(e)){const a=i/us.DEFAULT_SIZE;ro.identity().scale(a,a),r=this.graphicData.get(e).transform(ro)}return r}getGraphicDataByCodeWithOffset(e,i,s){return this.getGraphicDataByCode(e,i)?.offset(s)}parseBigFont(e){Q.ToInt16(e.readBytes(2),0);const i=Q.ToInt16(e.readBytes(2),0),s=Q.ToInt16(e.readBytes(2),0);for(let l=0;l<s;l++)e.readBytes(2),e.readBytes(2);const n=[];for(let l=0;l<i;l++){const h=e.readBytes(8),d=Q.ToUInt16(new Uint8Array([h[1],h[0]]),0),u=Q.ToUInt16(h,2),f=Q.ToUInt32(h,4);d===0&&u===0&&f===0||n.push({code:d,length:u,offset:f})}const r={};for(const l of n)e.setPosition(l.offset),r[l.code]=e.readBytes(l.length);const a=r[0];this.info=hu(a);let o=this.info.indexOf("\0")+1;a.length-o===4?(this.baseUp=a[o++],this.baseDown=a[o++],this.orientation=a[o++]):(this.baseUp=a[o++],o++,this.orientation=a[o++],this.baseDown=a[o++],this.isExtend=!0),this.data=r}parseUniFont(e){const i=Q.ToInt32(e.readBytes(4),0),s=Q.ToInt16(e.readBytes(2),0),n=e.readBytes(s);this.info=new TextDecoder().decode(n);let r=this.info.indexOf("\0");this.baseUp=n[++r],this.baseDown=n[++r],this.orientation=n[++r],this.isUniCode=n[++r]==0,this.isEmbedded=n[++r]==0;const a={};for(let o=0;o<i-1;o++){const l=Q.ToUInt16(e.readBytes(2),0),h=Q.ToUInt16(e.readBytes(2),0);a[l]=e.readBytes(h)}this.data=a}parseShapeFont(e){e.readBytes(2),e.readBytes(2);const i=Q.ToInt16(e.readBytes(2),0),s=[];for(let o=0;o<i;o++){const l=Q.ToUInt16(e.readBytes(2),0),h=Q.ToUInt16(e.readBytes(2),0);s.push({code:l,length:h})}const n={};for(const o of s)n[o.code]=e.readBytes(o.length);const r=n[0];this.info=new TextDecoder().decode(r);let a=this.info.indexOf("\0");this.baseUp=r[++a],this.baseDown=r[++a],this.orientation=r[++a],this.data=n}getNotFoundTextShape(e){let i=0;return this.fontType===Ne.Bigfont&&(i=Lt.getCode("?")),this.fontType===Ne.Unifont&&(i=Lt.getCode("?")),this.getGraphicDataByCode(i,e)}getFontFile(){return{fontType:this.fontType,order:this.order,data:this.data,info:this.info,orientation:this.orientation,baseUp:this.baseUp,baseDown:this.baseDown,fileName:this.fileName,fileHeader:this.fileHeader,fileVersion:this.fileVersion}}setFontFile(e){this.fileName=e.fileName,this.fontType=e.fontType||Ne.Unifont,this.data=e.data,this.info=e.info,this.order=e.order,this.orientation=e.orientation,this.baseUp=e.baseUp,this.baseDown=e.baseDown,this.fileHeader=e.fileHeader,this.fileVersion=e.fileVersion}releaseFontData(){super.releaseFontData(),this.graphicData.clear(),this.textShapesCache.clear()}};g(us,"DEFAULT_SIZE",12);let gt=us;function hu(c){let t,e,i,s,n;t="";const r=c.length;for(e=0;e<r;)switch(i=c[e++],i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:t+=String.fromCharCode(i);break;case 12:case 13:s=c[e++],t+=String.fromCharCode((i&31)<<6|s&63);break;case 14:s=c[e++],n=c[e++],t+=String.fromCharCode((i&15)<<12|(s&63)<<6|(n&63)<<0);break}return t}class xt{constructor(){g(this,"loader");g(this,"fontMap");g(this,"fileNames");g(this,"unsupportedChars");g(this,"missingFonts");g(this,"enableFontCache");this.fontMap=new Map,this.unsupportedChars={},this.missingFonts={},this.enableFontCache=!0,this.loader=new p.FileLoader}async loadFonts(t){if(t=Array.isArray(t)?t:[t],this.fileNames=t.map(e=>typeof e=="object"?Object.keys(e)[0]:xt.getFileName(e.toLowerCase())),!await this.checkAllFontsLoaded(t)){for(let e=0;e<t.length;e++){const i=t[e];let s=null,n=[],r=[];typeof i=="object"?(n=Object.keys(i),r=Object.values(i),s=n[0]):s=xt.getFileName(i.toLowerCase());let a;if(n.length){const o=n[0];if(o.lastIndexOf(".json")>-1){this.loader.setResponseType("json");const l=await this.loader.loadAsync(r[0]);a=new ei(s,l)}else if(o.lastIndexOf(".shx")>-1){this.loader.setResponseType("arraybuffer");const l=await this.loader.loadAsync(r[0]);a=new gt(s,l)}else if(o.lastIndexOf(".ttf")>-1){this.loader.setResponseType("arraybuffer");const l=await this.loader.loadAsync(r[0]);a=new ei(s,l)}}else if(xt.isJsonFile(i)){this.loader.setResponseType("json");const o=await this.loader.loadAsync(i);a=new ei(s,o)}else if(xt.isShxFile(i)){this.loader.setResponseType("arraybuffer");const o=await this.loader.loadAsync(i);a=new gt(s,o)}else if(xt.isTtfFile(i)){this.loader.setResponseType("arraybuffer");const o=await this.loader.loadAsync(i);a=new ei(s,o)}a&&(a.order=e+1,this.fontMap.set(s,a))}this.enableFontCache&&Be.isBrowser&&(this.fontMap.forEach(async e=>{await e.setFontDataToIndexedDb()}),this.releaseFontData())}}getTextShape(t,e,i){if(this.fontMap.size===0){P.warn("[FontManager] no font loaded.");return}let s=this.fontMap.get(e.toLowerCase());return!s&&(s=this.fontMap.get(this.fontMap.keys().next().value),!this.missingFonts[e]&&(this.missingFonts[e]=0),this.missingFonts[e]++),s?.generateShapes(t,i)}getCharShape(t,e,i){if(this.fontMap.size===0){P.warn("[FontManager] no font loaded.");return}e==null&&(e="");const s=t.charCodeAt(0)>255,n=o=>{const l=o.getCharShape(t,i);if(l&&!(s&&o instanceof gt&&l.width<i*.5))return l};let r=this.fontMap.get(e.toLowerCase());if(!r){!this.missingFonts[e]&&(this.missingFonts[e]=0),this.missingFonts[e]++;for(const[,o]of this.fontMap)if(n(o)){r=o;break}}let a=r?.getCharShape(t,i);if(a&&s&&r instanceof gt&&a.width<i*.5&&(a=void 0),!a)for(const[,o]of this.fontMap){if(o===r)continue;const l=n(o);if(l){r=o,a=l;break}}if(a){if(r instanceof gt)return a.toThreeGeometry();if(r instanceof ei){const o=new Hl.TextGeometry(t,{font:r,depth:0,size:i||12,curveSegments:3,bevelSegments:3});o.computeBoundingBox();const l=o.boundingBox,h=l.min.x;return Number.isFinite(h)&&Math.abs(h)>1e-6&&o.translate(-h,0,0),o.userData.advanceWidth=Math.max(l.max.x-l.min.x,0),o}}}getNotFoundTextShape(t){let e,i;for(const[,s]of this.fontMap){const n=s.getNotFoundTextShape(t);if(n){e=n,i=s;break}}if(i instanceof gt)return e.toThreeGeometry();if(i instanceof ei)return new p.ExtrudeGeometry(e.toShapes(!1),{curveSegments:3,bevelSegments:3})}async checkAllFontsLoaded(t){if(!Be.isBrowser)return!1;let e=!1;for(let i=0;i<t.length;i++){const s=t[i];let n=null;typeof s=="object"?n=Object.keys(s)[0]:n=xt.getFileName(s.toLowerCase());const r=await Fi.instance().query(n);if(r)e=!0;else{e=!1;break}if(r.codes!==void 0){e=!1;break}}return e}async getFontFromIndexeddb(){if(this.fontMap.size!==0)return;const t=(await Fi.instance().queryAll()).sort((e,i)=>e.order-i.order);for(let e=0;e<t.length;e++){const i=t[e],{fileName:s,fontType:n}=i;if(this.fileNames&&!this.fileNames.includes(s))continue;let r;n?r=new gt(s,i):r=new ei(s,i),this.fontMap.set(s,r)}P.debug("[FontManager] Loaded font data from cache.")}isShxFont(t){if(this.fontMap.size===0){P.warn("[FontManager] no font loaded.");return}let e=this.fontMap.get(t);return!e&&(e=this.fontMap.get(this.fontMap.keys().next().value),!this.missingFonts[t]&&(this.missingFonts[t]=0),this.missingFonts[t]++),e instanceof gt}getUnsupportedChar(){return this.fontMap.forEach(t=>{Object.assign(this.unsupportedChars,t.unsupportedChars)}),this.unsupportedChars}releaseFontData(){this.fontMap.forEach(t=>{t.releaseFontData()}),this.fontMap.clear()}destroy(){this.releaseFontData(),this.fontMap.clear()}static isShxFile(t){return j.getExtension(t)==="shx"}static isTtfFile(t){return["WOFF","OTF","TTF"].includes(j.getExtension(t).toUpperCase())}static isJsonFile(t){return j.getExtension(t)==="json"}static getFileName(t){const e=t.lastIndexOf("/");return t.substring(e+1)}}class du{constructor(t){g(this,"object");this.object=t}instantiate(){const t=Date.now();this.instantiateInner(this.object),console.log("[Inst] instantiate() took "+(Date.now()-t)/1e3+"s")}instantiateInner(t){if(!t.children||t.children.length===0)return;const e=t.children.length,i={},s=[];for(let a=0;a<e;++a){const o=t.children[a];if(this.instantiateInner(o),o.children&&o.children.length>0||!o.geometry)continue;let l=!1;const h=Object.values(i);for(let d=h.length-1;d>=0;--d){const u=h[d].indexes[0],f=t.children[u];if(this.geometryEquals(o.geometry,f.geometry)&&be.materialsEquals(o.material,f.material)){!i[u]&&(i[u]={indexes:[u]},this.removeFromArray(s,u)),i[u].indexes.push(a),l=!0;break}}for(let d=s.length-1;!l&&d>=0;--d){const u=s[d],f=t.children[u];if(this.geometryEquals(o.geometry,f.geometry)&&be.materialsEquals(o.material,f.material)){!i[u]&&(i[u]={indexes:[u]},this.removeFromArray(s,u)),i[u].indexes.push(a),l=!0;break}}!l&&s.push(a)}if(Object.keys(i).length<=0)return;const n=[],r=[];Object.values(i).forEach(a=>{const o=a.indexes;r.push(...o);const l=t.children[o[0]];let h=l.material;if(h instanceof p.Material)h=h.clone();else if(Array.isArray(h)){const u=[];h.forEach(f=>u.push(f.clone())),h=u}const d=new p.InstancedMesh(l.geometry,h,o.length);d.name="[Instanced] "+l.name;for(let u=0;u<o.length;++u){const f=o[u],m=t.children[f];m.updateMatrix(),d.setMatrixAt(u,m.matrix)}d.matrixAutoUpdate=et,d.updateMatrix(),n.push(d)}),r.sort((a,o)=>o-a),r.forEach(a=>t.remove(t.children[a])),n.forEach(a=>{a.parent=t,t.children.push(a)}),t.updateMatrix(),console.log("[Inst] "+r.length+"(out of "+e+") objects instanced to "+n.length+" InstancedMesh")}removeFromArray(t,e){for(let i=t.length-1;i>=0;--i)if(t[i]===e){t.splice(i,1);return}}geometryEquals(t,e){return H.geometriesEqual(t,e)}}class ol{constructor(){g(this,"TIMEOUT","timeout");g(this,"INTERVAL","interval");g(this,"timeoutMap",{});g(this,"intervalMap",{})}run(t=this.INTERVAL,e,i=16.7){const s=Date.now;let n=s(),r=n;const a=Symbol(""),o=()=>{this.setIdMap(a,t,o),r=s(),r-n>=i&&(t===this.intervalMap&&(n=s(),r=n),e(),t===this.TIMEOUT&&this.clearTimeout(a))};return this.setIdMap(a,t,o),a}setIdMap(t,e,i){const s=requestAnimationFrame(i);e===this.INTERVAL?this.intervalMap[t]=s:e===this.TIMEOUT&&(this.timeoutMap[t]=s)}setTimeout(t,e){return this.run(this.TIMEOUT,t,e)}clearTimeout(t){cancelAnimationFrame(this.timeoutMap[t])}setInterval(t,e){return this.run(this.INTERVAL,t,e)}clearInterval(t){cancelAnimationFrame(this.intervalMap[t])}}class yn{constructor(t){g(this,"buffer");g(this,"u8");this.buffer=t,this.u8=new Uint8Array(t)}getBit(t){var e=this.u8[t>>3],i=t&7;return(e&128>>i)>>7-i}setBit(t,e){var i=t>>3,s=this.u8[i],n=t&7;e?this.u8[i]=s|128>>n:this.u8[i]=s&~(128>>n)}getInt12(t){var e=t/8|0,i=this.u8[e],s=this.u8[e+1],n=this.u8[e+2],r=t%8,a=8-r,o=Math.min(12-a,8),l=Math.max(12-a-o,0),h=~(255<<a),d=255<<8-o,u=255<<8-l;return i&=h,s&=d,n&=u,((i<<16)+(s<<8)+n>>12-r)-2048}setInt12(t,e){e+=2048;var i=t/8|0,s=t%8,n=e<<12-s,r=(n&16711680)>>16,a=(n&65280)>>8,o=n&255,l=8-s,h=Math.min(12-l,8),d=Math.max(12-l-h,0),u=255<<l;this.u8[i]=(this.u8[i]&u)+r;var f=~(255<<8-h);this.u8[i+1]=(this.u8[i+1]&f)+a;var m=~(255<<8-d);this.u8[i+2]=(this.u8[i+2]&m)+o}getInt6(t){var e=t/8|0,i=this.u8[e],s=this.u8[e+1],n=t%8,r=8-n,a=Math.max(6-r,0),o=~((255<<r)+(255>>8-(2-n))),l=255<<8-a;return i&=o,s&=l,((i<<8)+s>>10-n)-32}setInt6(t,e){e+=32;var i=t/8|0,s=t%8,n=e<<10-s,r=(n&65280)>>8,a=n&255,o=8-s,l=Math.max(6-o,0),h=(255<<o)+(255>>8-(2-s));this.u8[i]=(this.u8[i]&h)+r;var d=~(255<<8-l);this.u8[i+1]=(this.u8[i+1]&d)+a}test(){var t=new ArrayBuffer(3),e=new yn(t),i,s;for(i=0;i<12;i++)for(s=-2048;s<2048;s++)if(e.setInt12(i,s),e.getInt12(i)!=s){console.log("12-bit prob at",i,s),console.log("expected",s,"got",e.getInt12(i));break}for(i=0;i<18;i++)for(s=-32;s<32;s++)if(e.setInt6(i,s),e.getInt6(i)!=s){console.log("6-bit prob at",i,s),console.log("expected",s,"got",e.getInt6(i));break}return e}}var ns=(c=>(c[c.NULL=0]="NULL",c[c.POINT=1]="POINT",c[c.POLYLINE=3]="POLYLINE",c[c.POLYGON=5]="POLYGON",c))(ns||{});class uu{parse(t){var e={},i=new DataView(t),s=0;if(e.fileCode=i.getInt32(s,!1),e.fileCode!=9994)throw new Error("Unknown file code: "+e.fileCode);for(s+=24,e.wordLength=i.getInt32(s,!1),e.byteLength=e.wordLength*2,s+=4,e.version=i.getInt32(s,!0),s+=4,e.shapeType=i.getInt32(s,!0),s+=4,e.minX=i.getFloat64(s,!0),e.minY=i.getFloat64(s+8,!0),e.maxX=i.getFloat64(s+16,!0),e.maxY=i.getFloat64(s+24,!0),e.minZ=i.getFloat64(s+32,!0),e.maxZ=i.getFloat64(s+40,!0),e.minM=i.getFloat64(s+48,!0),e.maxM=i.getFloat64(s+56,!0),s+=64,e.records=[];s<e.byteLength;){var n={};n.number=i.getInt32(s,!1),s+=4,n.length=i.getInt32(s,!1),s+=4;try{n.shape=this.parseShape(i,s,n.length)}catch(r){console.log(r,n)}s+=n.length*2,e.records.push(n)}return e}parseShape(t,e,i){var s=0,n=null,r={};switch(r.type=t.getInt32(e,!0),e+=4,r.type){case 0:break;case 1:r.content={x:t.getFloat64(e,!0),y:t.getFloat64(e+8,!0)};break;case 3:case 5:for(n=r.content={minX:t.getFloat64(e,!0),minY:t.getFloat64(e+8,!0),maxX:t.getFloat64(e+16,!0),maxY:t.getFloat64(e+24,!0),parts:new Int32Array(t.getInt32(e+32,!0)),points:new Float64Array(t.getInt32(e+36,!0)*2)},e+=40,s=0;s<n.parts.length;s++)n.parts[s]=t.getInt32(e,!0),e+=4;for(s=0;s<n.points.length;s++)n.points[s]=t.getFloat64(e,!0),e+=8;break;case 8:case 11:case 13:case 15:case 18:case 21:case 23:case 25:case 28:case 31:throw new Error("Shape type not supported: "+r.type+":"+ +r.type);default:throw new Error("Unknown shape type at "+(e-4)+": "+r.type)}return r}}class fu{constructor(){g(this,"LINE_MATERIAL");g(this,"MESH_MATERIAL");this.LINE_MATERIAL=new p.LineBasicMaterial({color:0,linewidth:2,opacity:.8,transparent:!0}),this.MESH_MATERIAL=new p.MeshBasicMaterial({color:1926655,opacity:.8,transparent:!0})}createModel(t){for(var e=[],i=[],s=0;s<t.records.length;s++){var n=t.records[s].shape;if(n.type===ns.POLYLINE||n.type===ns.POLYGON)for(var r=n.content.points,a=n.content.parts,o=0;o<a.length;o++){const m=[];for(var l=a[o],h=a[o+1]||r.length/2;l<h;l++){var d=r[l*2],u=r[l*2+1];m.push(new p.Vector3(d,u,0))}if(n.type===ns.POLYGON){const b=p.ShapeUtils.triangulateShape(m,[]),y=[];b.forEach(x=>y.push(...x));const S=new p.BufferGeometry;S.setFromPoints(m),S.setIndex(y),e.push(S);const w=new p.BufferGeometry;m.length>2&&!m[0].equals(m[m.length-1])&&m.push(m[0]),w.setFromPoints(m),i.push(w)}else{const b=new p.BufferGeometry;b.setFromPoints(m),i.push(b)}}}for(var f=new p.Object3D,s=0;s<i.length;s++)f.add(new p.Line(i[s],this.LINE_MATERIAL));for(var s=0;s<e.length;s++)f.add(new p.Mesh(e[s],this.MESH_MATERIAL));return console.log("parsed",e.length,i.length),f}loadCompressed(t){for(var e=this.deltaDecode6(t),i=[],s=[],n=0;n<e.length;n++){let d=[];if(e[n]===-32768){for(var r=[],a=1;a<d.length;a++)!(d[a-1].x==d[a].x&&d[a-1].y==d[a].y)&&r.push(d[a]);const u=new p.BufferGeometry;u.setFromPoints(r),i.push(u),d=[];continue}var o=e[n]*180/32767,l=e[n+1]*180/32767;n++,d.push(new p.Vector3(o,l,0))}for(var h=new p.Object3D,n=0;n<s.length;n++)h.add(new p.Line(s[n],this.LINE_MATERIAL));for(var n=0;n<i.length;n++)h.add(new p.Mesh(i[n],this.MESH_MATERIAL));return console.log("parsed compressed",i.length,s.length),h}compress(t){for(var e=[],i=0;i<t.records.length;i++){var s=t.records[i].shape;if(s.type===ns.POLYGON)for(var n=s.content.points,r=s.content.parts,a=0;a<r.length;a++){for(var o=r[a],l=r[a+1]||n.length/2;o<l;o++){var h=n[o*2],d=n[o*2+1];e.push(h/180*32767,d/180*32767)}e.push(-32768)}}var u=new Int16Array(e);console.log("16-bit quantized byteLength",u.buffer.byteLength);var f=this.deltaEncode6(u);return console.log("delta-encoded byteLength",f.byteLength),f}deltaEncode(t){for(var e=[],i=[],s=[],n=0,r=0,a=0,o=0;o<t.length;o++){if(t[o]==-32768){i.push(s),e.push(i),i=[],s=[],a+=3;continue}s.length==0?(n=t[o],r=t[o+1],s.push(n,r),a+=4,o++):Math.abs(n-t[o])>1023||Math.abs(r-t[o+1])>1023?(i.push(s),a+=1,s=[],n=t[o],r=t[o+1],s.push(n,r),a+=4,o++):(s.push((t[o]-n)/8,(t[o+1]-r)/8),n+=((t[o]-n)/8|0)*8,r+=((t[o+1]-r)/8|0)*8,a+=2,o++)}return this.storeDeltas(a,e)}deltaEncode6(t){var e=[],i=[],s=[],n=0,r=0,a=0,o=0;for(a=0;a<t.length;a++)t[a]=0|t[a]/16;for(a=0;a<t.length;a++){if(t[a]===-2048){i.push(s),e.push(i),i=[],s=[],o+=3;continue}s.length==0?(n=t[a],r=t[a+1],s.push(n,r),o+=4,a++):Math.abs(n-t[a])>31||Math.abs(r-t[a+1])>31?(i.push(s),o+=1,s=[],n=t[a],r=t[a+1],s.push(n,r),o+=4,a++):(s.push(t[a]-n,t[a+1]-r),n+=t[a]-n,r+=t[a+1]-r,o+=2,a++)}return this.storeDeltas6(o,e)}storeDeltas(t,e){for(var i=new ArrayBuffer(t),s=new DataView(i),n=0,r=0;r<e.length;r++){for(var a=e[r],o=0;o<a.length;o++){var l=a[o];s.setInt16(n,l[0]),n+=2,s.setInt16(n,l[1]),n+=2;for(var h=2;h<l.length;h++)s.setInt8(n++,l[h]);s.setInt8(n,-128),n+=1}s.setInt16(n,-32768),n+=2}return i}deltaDecode(t){for(var e=new DataView(t),i=0,s=[];i<t.byteLength;){var n=e.getInt16(i);if(i+=2,n===-32768){s.push(-32768);continue}var r=e.getInt16(i);for(i+=2,s.push(n,r);i<t.byteLength;){var a=e.getInt8(i);if(i++,a==-128)break;var o=e.getInt8(i);i++,n+=a*8,r+=o*8,s.push(n,r)}}return s}storeDeltas6(t,e){for(var i=new ArrayBuffer(Math.ceil(t*.75)+4),s=new yn(i),n=32,r=0;r<e.length;r++){for(var a=e[r],o=0;o<a.length;o++){var l=a[o];s.setInt12(n,l[0]),n+=12,s.setInt12(n,l[1]),n+=12;for(var h=2;h<l.length;h++)s.setInt6(n,l[h]),n+=6;s.setInt6(n,-32),n+=6}s.setInt12(n,-2048),n+=12}return new DataView(i).setUint32(0,n),i}deltaDecode6(t){for(var e=new DataView(t).getUint32(0),i=new yn(t),s=32,n=[];s<e;){var r=i.getInt12(s);if(s+=12,r===-2048){n.push(-2048);continue}var a=i.getInt12(s);for(s+=12,n.push(r,a);s<e;){var o=i.getInt6(s);if(s+=6,o===-32)break;var l=i.getInt6(s);s+=6,r+=o,a+=l,n.push(r,a)}}for(var h=0;h<n.length;h++)n[h]*=16;return n}}class pu{async load(t,e,i,s){this.updateProgress(i,0);const n=new XMLHttpRequest;n.responseType="arraybuffer",n.onload=()=>{this.updateProgress(i,50);const r=new uu,a=r.parse(n.response),o=new fu().createModel(a);this.updateProgress(i,100),e(o)},n.onerror=s,n.open("GET",t),n.send(null)}updateProgress(t,e){if(t){const i={lengthComputable:!0,loaded:e,total:100};t(new ProgressEvent("progress",i))}}}const fs=class fs{constructor(t){g(this,"gltfLoader");g(this,"font");g(this,"manager");g(this,"currentDxfLoader");this.manager=t}setLoadManager(t){this.manager=t}async loadLocalModel(t,e,i){const s=e.toLowerCase();return s.endsWith("fbx")?this.loadFbx(t,i):s.endsWith("obj")?this.loadObj(t,i):s.endsWith("stl")?this.loadStl(t,i):s.endsWith("ifc")?(P.warn("[LoadingHelper] IFC is not supported directly since three.js r150!"),Promise.reject("Not supported!")):s.endsWith("shp")?this.loadShp(t,i):s.endsWith("dae")?this.loadDae(t,i):s.endsWith("dxf")?this.loadDxf(t,i):s.endsWith("jpg")||s.endsWith("jpeg")||s.endsWith("png")?this.loadImage(t,i):this.loadGltf(t,i)}async loadModel(t,e,i){const s=t;if(!s)return Promise.resolve();let n=e?.toLowerCase()||"";if(!n){const r=s.split("?")[0].toLowerCase();if(r){const a=r.lastIndexOf(".");a!==-1&&(n=r.slice(a+1))}}if(n.endsWith("fbx"))return this.loadFbx(s,i);if(n.endsWith("obj"))return this.loadObj(s,i);if(n.endsWith("stl"))return this.loadStl(s,i);if(n.endsWith("ifc"))P.warn("[LoadingHelper] IFC is not supported directly since three.js r150!");else return n.endsWith("shp")?this.loadShp(s,i):n.endsWith("dae")?this.loadDae(s,i):n.endsWith("dxf")?this.loadDxf(s,i):n.endsWith("jpg")||n.endsWith("jpeg")||n.endsWith("png")?this.loadImage(s,i):this.loadGltf(s,i)}async loadGltf(t,e){const i=this.getGltfLoader();t.indexOf("#")!==-1&&console.warn("[LoadingHelper] '#' is not allowed in filename "+t),t=t.replace(/#/g,encodeURIComponent("#"));const s=r=>{r.total===0&&r.loaded>0||e&&e(r)},n=await i.loadAsync(t,s);return Promise.resolve(n.scene)}parseGltf(t,e,i,s){return this.getGltfLoader().parse(t,e,r=>i(r.scene),s)}async loadFbx(t,e){const i=new Xl.FBXLoader(this.manager),s=await i.loadAsync(t,e);return Promise.resolve(s)}async loadObj(t,e){const i=new $l.OBJLoader(this.manager),s=new Kl.MTLLoader(this.manager),n=t.replace(".obj",".mtl"),r=await s.loadAsync(n,e);r.preload(),i.setMaterials(r);const a=await i.loadAsync(t,e);return Promise.resolve(a)}async loadStl(t,e){const i=new Ql.STLLoader(this.manager),s=await i.loadAsync(t,e),n=new p.MeshStandardMaterial({color:11184810,metalness:.1,roughness:.8}),r=new p.Mesh(s,n);return Promise.resolve(r)}async loadShp(t,e){const i=new pu;return new Promise((s,n)=>{i.load(t,r=>{s(r)},e,r=>{n(r)})})}async loadDae(t,e){const i=new Wl.ColladaLoader(this.manager),s=await i.loadAsync(t,e);return Promise.resolve(s.scene)}async load3dm(t,e){return Promise.reject("3dm format is not supported since three.js r159 (Rhino3dmLoader removed)")}async loadDxf(t,e){this.font||console.warn("[LoadingHelper] Should set font first!");const i={ignorePaperSpace:!0,enableLocalCache:!1,overrideHatchPatternLineThickness:2},s=new X(this.manager,i);s.setFont(this.font),await this.font?.getFontFromIndexeddb();try{const n=await s.loadAsync(t,e);return Promise.resolve(n.threejsObject)}catch{const r=new ErrorEvent("");return Promise.reject(r)}}async loadPly(t,e){const i=new Jl.PLYLoader(this.manager),s=await i.loadAsync(t,e);return Promise.resolve(new p.Mesh(s))}async loadImage(t,e){const i=new p.TextureLoader(this.manager),s=await i.loadAsync(t,e);if(!s)return Promise.reject("Failed to load image!");const n=10,r=s.image;let a=r&&r.height||n,o=r&&r.width||n;a=n/o*a,o=n;const l=new p.MeshBasicMaterial({map:s,side:p.DoubleSide,transparent:!0}),h=new p.PlaneGeometry(o,a),d=new p.Mesh(h,l);return Promise.resolve(d)}async loadDxfData(t,e,i,s,n){this.font||console.warn("[LoadingHelper] Should set font first!");const r=new X(this.manager,n);return this.currentDxfLoader=r,r.setFont(this.font),await this.font?.getFontFromIndexeddb(),r.manager.onLoad=()=>{s&&s()},r.loadEx(t,e,i)}abortDxfLoading(){this.currentDxfLoader?.abort(),this.currentDxfLoader=void 0}setFont(t){this.font=t}static setDracoDecoderPath(t){this.DecoderPath=t}static setRhino3dmLibraryPath(t){this.Rhino3dmLibraryPath=t}getGltfLoader(){if(!this.gltfLoader){this.gltfLoader=new Zl.GLTFLoader(this.manager);const t=new Yl.DRACOLoader(this.manager);t.setDecoderPath(fs.DecoderPath),this.gltfLoader.setDRACOLoader(t)}return this.gltfLoader}};g(fs,"DecoderPath","libs/draco/gltf/"),g(fs,"Rhino3dmLibraryPath","https://unpkg.com/rhino3dm@8.0.0-beta2/");let Vt=fs;const ll=`(function(){"use strict";function Ks(f){for(let t=f.length-1;t>=0;--t)if(f[t]>=65535)return!0;return!1}function ms(f){return document.createElementNS("http://www.w3.org/1999/xhtml",f)}const ps={};function xs(f){const t=f[0];if(typeof t=="string"&&t.startsWith("TSL:")){const e=f[1];e&&e.isStackTrace?f[0]+=" "+e.getLocation():f[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return f}function yt(...f){f=xs(f);const t="THREE."+f.shift();{const e=f[0];e&&e.isStackTrace?console.warn(e.getError(t)):console.warn(t,...f)}}function Ut(...f){f=xs(f);const t="THREE."+f.shift();{const e=f[0];e&&e.isStackTrace?console.error(e.getError(t)):console.error(t,...f)}}function yi(...f){const t=f.join(" ");t in ps||(ps[t]=!0,yt(...f))}class Ve{addEventListener(t,e){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[t]===void 0&&(i[t]=[]),i[t].indexOf(e)===-1&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return i===void 0?!1:i[t]!==void 0&&i[t].indexOf(e)!==-1}removeEventListener(t,e){const i=this._listeners;if(i===void 0)return;const s=i[t];if(s!==void 0){const n=s.indexOf(e);n!==-1&&s.splice(n,1)}}dispatchEvent(t){const e=this._listeners;if(e===void 0)return;const i=e[t.type];if(i!==void 0){t.target=this;const s=i.slice(0);for(let n=0,r=s.length;n<r;n++)s[n].call(this,t);t.target=null}}}const $=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"];function Re(){const f=Math.random()*4294967295|0,t=Math.random()*4294967295|0,e=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return($[f&255]+$[f>>8&255]+$[f>>16&255]+$[f>>24&255]+"-"+$[t&255]+$[t>>8&255]+"-"+$[t>>16&15|64]+$[t>>24&255]+"-"+$[e&63|128]+$[e>>8&255]+"-"+$[e>>16&255]+$[e>>24&255]+$[i&255]+$[i>>8&255]+$[i>>16&255]+$[i>>24&255]).toLowerCase()}function V(f,t,e){return Math.max(t,Math.min(e,f))}function me(f,t){switch(t.constructor){case Float32Array:return f;case Uint32Array:return f/4294967295;case Uint16Array:return f/65535;case Uint8Array:case Uint8ClampedArray:return f/255;case Int32Array:return Math.max(f/2147483647,-1);case Int16Array:return Math.max(f/32767,-1);case Int8Array:return Math.max(f/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function K(f,t){switch(t.constructor){case Float32Array:return f;case Uint32Array:return Math.round(f*4294967295);case Uint16Array:return Math.round(f*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(f*255);case Int32Array:return Math.round(f*2147483647);case Int16Array:return Math.round(f*32767);case Int8Array:return Math.round(f*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const hs=class hs{constructor(t=0,e=0){this.x=t,this.y=e}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,e){return this.x=t,this.y=e,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;default:throw new Error("THREE.Vector2: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){const e=this.x,i=this.y,s=t.elements;return this.x=s[0]*e+s[3]*i+s[6],this.y=s[1]*e+s[4]*i+s[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,e){return this.x=V(this.x,t.x,e.x),this.y=V(this.y,t.y,e.y),this}clampScalar(t,e){return this.x=V(this.x,t,e),this.y=V(this.y,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(V(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(V(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y;return e*e+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this}rotateAround(t,e){const i=Math.cos(e),s=Math.sin(e),n=this.x-t.x,r=this.y-t.y;return this.x=n*i-r*s+t.x,this.y=n*s+r*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};hs.prototype.isVector2=!0;let Y=hs;class pe{constructor(t=0,e=0,i=0,s=1){this.isQuaternion=!0,this._x=t,this._y=e,this._z=i,this._w=s}static slerpFlat(t,e,i,s,n,r,a){let o=i[s+0],c=i[s+1],h=i[s+2],u=i[s+3],l=n[r+0],d=n[r+1],y=n[r+2],m=n[r+3];if(u!==m||o!==l||c!==d||h!==y){let z=o*l+c*d+h*y+u*m;z<0&&(l=-l,d=-d,y=-y,m=-m,z=-z);let b=1-a;if(z<.9995){const p=Math.acos(z),x=Math.sin(p);b=Math.sin(b*p)/x,a=Math.sin(a*p)/x,o=o*b+l*a,c=c*b+d*a,h=h*b+y*a,u=u*b+m*a}else{o=o*b+l*a,c=c*b+d*a,h=h*b+y*a,u=u*b+m*a;const p=1/Math.sqrt(o*o+c*c+h*h+u*u);o*=p,c*=p,h*=p,u*=p}}t[e]=o,t[e+1]=c,t[e+2]=h,t[e+3]=u}static multiplyQuaternionsFlat(t,e,i,s,n,r){const a=i[s],o=i[s+1],c=i[s+2],h=i[s+3],u=n[r],l=n[r+1],d=n[r+2],y=n[r+3];return t[e]=a*y+h*u+o*d-c*l,t[e+1]=o*y+h*l+c*u-a*d,t[e+2]=c*y+h*d+a*l-o*u,t[e+3]=h*y-a*u-o*l-c*d,t}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get w(){return this._w}set w(t){this._w=t,this._onChangeCallback()}set(t,e,i,s){return this._x=t,this._y=e,this._z=i,this._w=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(t){return this._x=t.x,this._y=t.y,this._z=t.z,this._w=t.w,this._onChangeCallback(),this}setFromEuler(t,e=!0){const i=t._x,s=t._y,n=t._z,r=t._order,a=Math.cos,o=Math.sin,c=a(i/2),h=a(s/2),u=a(n/2),l=o(i/2),d=o(s/2),y=o(n/2);switch(r){case"XYZ":this._x=l*h*u+c*d*y,this._y=c*d*u-l*h*y,this._z=c*h*y+l*d*u,this._w=c*h*u-l*d*y;break;case"YXZ":this._x=l*h*u+c*d*y,this._y=c*d*u-l*h*y,this._z=c*h*y-l*d*u,this._w=c*h*u+l*d*y;break;case"ZXY":this._x=l*h*u-c*d*y,this._y=c*d*u+l*h*y,this._z=c*h*y+l*d*u,this._w=c*h*u-l*d*y;break;case"ZYX":this._x=l*h*u-c*d*y,this._y=c*d*u+l*h*y,this._z=c*h*y-l*d*u,this._w=c*h*u+l*d*y;break;case"YZX":this._x=l*h*u+c*d*y,this._y=c*d*u+l*h*y,this._z=c*h*y-l*d*u,this._w=c*h*u-l*d*y;break;case"XZY":this._x=l*h*u-c*d*y,this._y=c*d*u-l*h*y,this._z=c*h*y+l*d*u,this._w=c*h*u+l*d*y;break;default:yt("Quaternion: .setFromEuler() encountered an unknown order: "+r)}return e===!0&&this._onChangeCallback(),this}setFromAxisAngle(t,e){const i=e/2,s=Math.sin(i);return this._x=t.x*s,this._y=t.y*s,this._z=t.z*s,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(t){const e=t.elements,i=e[0],s=e[4],n=e[8],r=e[1],a=e[5],o=e[9],c=e[2],h=e[6],u=e[10],l=i+a+u;if(l>0){const d=.5/Math.sqrt(l+1);this._w=.25/d,this._x=(h-o)*d,this._y=(n-c)*d,this._z=(r-s)*d}else if(i>a&&i>u){const d=2*Math.sqrt(1+i-a-u);this._w=(h-o)/d,this._x=.25*d,this._y=(s+r)/d,this._z=(n+c)/d}else if(a>u){const d=2*Math.sqrt(1+a-i-u);this._w=(n-c)/d,this._x=(s+r)/d,this._y=.25*d,this._z=(o+h)/d}else{const d=2*Math.sqrt(1+u-i-a);this._w=(r-s)/d,this._x=(n+c)/d,this._y=(o+h)/d,this._z=.25*d}return this._onChangeCallback(),this}setFromUnitVectors(t,e){let i=t.dot(e)+1;return i<1e-8?(i=0,Math.abs(t.x)>Math.abs(t.z)?(this._x=-t.y,this._y=t.x,this._z=0,this._w=i):(this._x=0,this._y=-t.z,this._z=t.y,this._w=i)):(this._x=t.y*e.z-t.z*e.y,this._y=t.z*e.x-t.x*e.z,this._z=t.x*e.y-t.y*e.x,this._w=i),this.normalize()}angleTo(t){return 2*Math.acos(Math.abs(V(this.dot(t),-1,1)))}rotateTowards(t,e){const i=this.angleTo(t);if(i===0)return this;const s=Math.min(1,e/i);return this.slerp(t,s),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(t){return this._x*t._x+this._y*t._y+this._z*t._z+this._w*t._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let t=this.length();return t===0?(this._x=0,this._y=0,this._z=0,this._w=1):(t=1/t,this._x=this._x*t,this._y=this._y*t,this._z=this._z*t,this._w=this._w*t),this._onChangeCallback(),this}multiply(t){return this.multiplyQuaternions(this,t)}premultiply(t){return this.multiplyQuaternions(t,this)}multiplyQuaternions(t,e){const i=t._x,s=t._y,n=t._z,r=t._w,a=e._x,o=e._y,c=e._z,h=e._w;return this._x=i*h+r*a+s*c-n*o,this._y=s*h+r*o+n*a-i*c,this._z=n*h+r*c+i*o-s*a,this._w=r*h-i*a-s*o-n*c,this._onChangeCallback(),this}slerp(t,e){let i=t._x,s=t._y,n=t._z,r=t._w,a=this.dot(t);a<0&&(i=-i,s=-s,n=-n,r=-r,a=-a);let o=1-e;if(a<.9995){const c=Math.acos(a),h=Math.sin(c);o=Math.sin(o*c)/h,e=Math.sin(e*c)/h,this._x=this._x*o+i*e,this._y=this._y*o+s*e,this._z=this._z*o+n*e,this._w=this._w*o+r*e,this._onChangeCallback()}else this._x=this._x*o+i*e,this._y=this._y*o+s*e,this._z=this._z*o+n*e,this._w=this._w*o+r*e,this.normalize();return this}slerpQuaternions(t,e,i){return this.copy(t).slerp(e,i)}random(){const t=2*Math.PI*Math.random(),e=2*Math.PI*Math.random(),i=Math.random(),s=Math.sqrt(1-i),n=Math.sqrt(i);return this.set(s*Math.sin(t),s*Math.cos(t),n*Math.sin(e),n*Math.cos(e))}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._w===this._w}fromArray(t,e=0){return this._x=t[e],this._y=t[e+1],this._z=t[e+2],this._w=t[e+3],this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._w,t}fromBufferAttribute(t,e){return this._x=t.getX(e),this._y=t.getY(e),this._z=t.getZ(e),this._w=t.getW(e),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}const ls=class ls{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.z=i}set(t,e,i){return i===void 0&&(i=this.z),this.x=t,this.y=e,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;default:throw new Error("THREE.Vector3: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,e){return this.x=t.x*e.x,this.y=t.y*e.y,this.z=t.z*e.z,this}applyEuler(t){return this.applyQuaternion(gs.setFromEuler(t))}applyAxisAngle(t,e){return this.applyQuaternion(gs.setFromAxisAngle(t,e))}applyMatrix3(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[3]*i+n[6]*s,this.y=n[1]*e+n[4]*i+n[7]*s,this.z=n[2]*e+n[5]*i+n[8]*s,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=t.elements,r=1/(n[3]*e+n[7]*i+n[11]*s+n[15]);return this.x=(n[0]*e+n[4]*i+n[8]*s+n[12])*r,this.y=(n[1]*e+n[5]*i+n[9]*s+n[13])*r,this.z=(n[2]*e+n[6]*i+n[10]*s+n[14])*r,this}applyQuaternion(t){const e=this.x,i=this.y,s=this.z,n=t.x,r=t.y,a=t.z,o=t.w,c=2*(r*s-a*i),h=2*(a*e-n*s),u=2*(n*i-r*e);return this.x=e+o*c+r*u-a*h,this.y=i+o*h+a*c-n*u,this.z=s+o*u+n*h-r*c,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){const e=this.x,i=this.y,s=this.z,n=t.elements;return this.x=n[0]*e+n[4]*i+n[8]*s,this.y=n[1]*e+n[5]*i+n[9]*s,this.z=n[2]*e+n[6]*i+n[10]*s,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,e){return this.x=V(this.x,t.x,e.x),this.y=V(this.y,t.y,e.y),this.z=V(this.z,t.z,e.z),this}clampScalar(t,e){return this.x=V(this.x,t,e),this.y=V(this.y,t,e),this.z=V(this.z,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(V(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,e){const i=t.x,s=t.y,n=t.z,r=e.x,a=e.y,o=e.z;return this.x=s*o-n*a,this.y=n*r-i*o,this.z=i*a-s*r,this}projectOnVector(t){const e=t.lengthSq();if(e===0)return this.set(0,0,0);const i=t.dot(this)/e;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return mi.copy(this).projectOnVector(t),this.sub(mi)}reflect(t){return this.sub(mi.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){const e=Math.sqrt(this.lengthSq()*t.lengthSq());if(e===0)return Math.PI/2;const i=this.dot(t)/e;return Math.acos(V(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){const e=this.x-t.x,i=this.y-t.y,s=this.z-t.z;return e*e+i*i+s*s}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,e,i){const s=Math.sin(e)*t;return this.x=s*Math.sin(i),this.y=Math.cos(e)*t,this.z=s*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,e,i){return this.x=t*Math.sin(e),this.y=i,this.z=t*Math.cos(e),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this}setFromMatrixScale(t){const e=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),s=this.setFromMatrixColumn(t,2).length();return this.x=e,this.y=i,this.z=s,this}setFromMatrixColumn(t,e){return this.fromArray(t.elements,e*4)}setFromMatrix3Column(t,e){return this.fromArray(t.elements,e*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const t=Math.random()*Math.PI*2,e=Math.random()*2-1,i=Math.sqrt(1-e*e);return this.x=i*Math.cos(t),this.y=e,this.z=i*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};ls.prototype.isVector3=!0;let S=ls;const mi=new S,gs=new pe,us=class us{constructor(t,e,i,s,n,r,a,o,c){this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,e,i,s,n,r,a,o,c)}set(t,e,i,s,n,r,a,o,c){const h=this.elements;return h[0]=t,h[1]=s,h[2]=a,h[3]=e,h[4]=n,h[5]=o,h[6]=i,h[7]=r,h[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],this}extractBasis(t,e,i){return t.setFromMatrix3Column(this,0),e.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){const e=t.elements;return this.set(e[0],e[4],e[8],e[1],e[5],e[9],e[2],e[6],e[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],a=i[3],o=i[6],c=i[1],h=i[4],u=i[7],l=i[2],d=i[5],y=i[8],m=s[0],z=s[3],b=s[6],p=s[1],x=s[4],g=s[7],w=s[2],B=s[5],_=s[8];return n[0]=r*m+a*p+o*w,n[3]=r*z+a*x+o*B,n[6]=r*b+a*g+o*_,n[1]=c*m+h*p+u*w,n[4]=c*z+h*x+u*B,n[7]=c*b+h*g+u*_,n[2]=l*m+d*p+y*w,n[5]=l*z+d*x+y*B,n[8]=l*b+d*g+y*_,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[3]*=t,e[6]*=t,e[1]*=t,e[4]*=t,e[7]*=t,e[2]*=t,e[5]*=t,e[8]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],c=t[7],h=t[8];return e*r*h-e*a*c-i*n*h+i*a*o+s*n*c-s*r*o}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],c=t[7],h=t[8],u=h*r-a*c,l=a*o-h*n,d=c*n-r*o,y=e*u+i*l+s*d;if(y===0)return this.set(0,0,0,0,0,0,0,0,0);const m=1/y;return t[0]=u*m,t[1]=(s*c-h*i)*m,t[2]=(a*i-s*r)*m,t[3]=l*m,t[4]=(h*e-s*o)*m,t[5]=(s*n-a*e)*m,t[6]=d*m,t[7]=(i*o-c*e)*m,t[8]=(r*e-i*n)*m,this}transpose(){let t;const e=this.elements;return t=e[1],e[1]=e[3],e[3]=t,t=e[2],e[2]=e[6],e[6]=t,t=e[5],e[5]=e[7],e[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){const e=this.elements;return t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8],this}setUvTransform(t,e,i,s,n,r,a){const o=Math.cos(n),c=Math.sin(n);return this.set(i*o,i*c,-i*(o*r+c*a)+r+t,-s*c,s*o,-s*(-c*r+o*a)+a+e,0,0,1),this}scale(t,e){return yi("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(pi.makeScale(t,e)),this}rotate(t){return yi("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(pi.makeRotation(-t)),this}translate(t,e){return yi("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(pi.makeTranslation(t,e)),this}makeTranslation(t,e){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,e,0,0,1),this}makeRotation(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,i,e,0,0,0,1),this}makeScale(t,e){return this.set(t,0,0,0,e,0,0,0,1),this}equals(t){const e=this.elements,i=t.elements;for(let s=0;s<9;s++)if(e[s]!==i[s])return!1;return!0}fromArray(t,e=0){for(let i=0;i<9;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t}clone(){return new this.constructor().fromArray(this.elements)}};us.prototype.isMatrix3=!0;let xt=us;const pi=new xt;function xi(f){return f<.04045?f*.0773993808:Math.pow(f*.9478672986+.0521327014,2.4)}let Zt;class tn{static getDataURL(t,e="image/png"){if(/^data:/i.test(t.src)||typeof HTMLCanvasElement>"u")return t.src;let i;if(t instanceof HTMLCanvasElement)i=t;else{Zt===void 0&&(Zt=ms("canvas")),Zt.width=t.width,Zt.height=t.height;const s=Zt.getContext("2d");t instanceof ImageData?s.putImageData(t,0,0):s.drawImage(t,0,0,t.width,t.height),i=Zt}return i.toDataURL(e)}static sRGBToLinear(t){if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap){const e=ms("canvas");e.width=t.width,e.height=t.height;const i=e.getContext("2d");i.drawImage(t,0,0,t.width,t.height);const s=i.getImageData(0,0,t.width,t.height),n=s.data;for(let r=0;r<n.length;r++)n[r]=xi(n[r]/255)*255;return i.putImageData(s,0,0),e}else if(t.data){const e=t.data.slice(0);for(let i=0;i<e.length;i++)e instanceof Uint8Array||e instanceof Uint8ClampedArray?e[i]=Math.floor(xi(e[i]/255)*255):e[i]=xi(e[i]);return{data:e,width:t.width,height:t.height}}else return yt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),t}}let en=0;class sn{constructor(t=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:en++}),this.uuid=Re(),this.data=t,this.dataReady=!0,this.version=0}getSize(t){const e=this.data;return typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement?t.set(e.videoWidth,e.videoHeight,0):typeof VideoFrame<"u"&&e instanceof VideoFrame?t.set(e.displayWidth,e.displayHeight,0):e!==null?t.set(e.width,e.height,e.depth||0):t.set(0,0,0),t}set needsUpdate(t){t===!0&&this.version++}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.images[this.uuid]!==void 0)return t.images[this.uuid];const i={uuid:this.uuid,url:""},s=this.data;if(s!==null){let n;if(Array.isArray(s)){n=[];for(let r=0,a=s.length;r<a;r++)s[r].isDataTexture?n.push(gi(s[r].image)):n.push(gi(s[r]))}else n=gi(s);i.url=n}return e||(t.images[this.uuid]=i),i}}function gi(f){return typeof HTMLImageElement<"u"&&f instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&f instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&f instanceof ImageBitmap?tn.getDataURL(f):f.data?{data:Array.from(f.data),width:f.width,height:f.height,type:f.data.constructor.name}:(yt("Texture: Unable to serialize Texture."),{})}let nn=0;const wi=new S;class Nt extends Ve{constructor(t=Nt.DEFAULT_IMAGE,e=Nt.DEFAULT_MAPPING,i=1001,s=1001,n=1006,r=1008,a=1023,o=1009,c=Nt.DEFAULT_ANISOTROPY,h=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:nn++}),this.uuid=Re(),this.name="",this.source=new sn(t),this.mipmaps=[],this.mapping=e,this.channel=0,this.wrapS=i,this.wrapT=s,this.magFilter=n,this.minFilter=r,this.anisotropy=c,this.format=a,this.internalFormat=null,this.type=o,this.offset=new Y(0,0),this.repeat=new Y(1,1),this.center=new Y(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new xt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(t&&t.depth&&t.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(wi).x}get height(){return this.source.getSize(wi).y}get depth(){return this.source.getSize(wi).z}get image(){return this.source.data}set image(t){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.normalized=t.normalized,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.renderTarget=t.renderTarget,this.isRenderTargetTexture=t.isRenderTargetTexture,this.isArrayTexture=t.isArrayTexture,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}setValues(t){for(const e in t){const i=t[e];if(i===void 0){yt(\`Texture.setValues(): parameter '\${e}' has value of undefined.\`);continue}const s=this[e];if(s===void 0){yt(\`Texture.setValues(): property '\${e}' does not exist.\`);continue}s&&i&&s.isVector2&&i.isVector2||s&&i&&s.isVector3&&i.isVector3||s&&i&&s.isMatrix3&&i.isMatrix3?s.copy(i):this[e]=i}}toJSON(t){const e=t===void 0||typeof t=="string";if(!e&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,normalized:this.normalized,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),e||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==300)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case 1e3:t.x=t.x-Math.floor(t.x);break;case 1001:t.x=t.x<0?0:1;break;case 1002:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case 1e3:t.y=t.y-Math.floor(t.y);break;case 1001:t.y=t.y<0?0:1;break;case 1002:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}}Nt.DEFAULT_IMAGE=null,Nt.DEFAULT_MAPPING=300,Nt.DEFAULT_ANISOTROPY=1;const fs=class fs{constructor(t=0,e=0,i=0,s=1){this.x=t,this.y=e,this.z=i,this.w=s}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,e,i,s){return this.x=t,this.y=e,this.z=i,this.w=s,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,e){switch(t){case 0:this.x=e;break;case 1:this.y=e;break;case 2:this.z=e;break;case 3:this.w=e;break;default:throw new Error("THREE.Vector4: index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,e){return this.x=t.x+e.x,this.y=t.y+e.y,this.z=t.z+e.z,this.w=t.w+e.w,this}addScaledVector(t,e){return this.x+=t.x*e,this.y+=t.y*e,this.z+=t.z*e,this.w+=t.w*e,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,e){return this.x=t.x-e.x,this.y=t.y-e.y,this.z=t.z-e.z,this.w=t.w-e.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){const e=this.x,i=this.y,s=this.z,n=this.w,r=t.elements;return this.x=r[0]*e+r[4]*i+r[8]*s+r[12]*n,this.y=r[1]*e+r[5]*i+r[9]*s+r[13]*n,this.z=r[2]*e+r[6]*i+r[10]*s+r[14]*n,this.w=r[3]*e+r[7]*i+r[11]*s+r[15]*n,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);const e=Math.sqrt(1-t.w*t.w);return e<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/e,this.y=t.y/e,this.z=t.z/e),this}setAxisAngleFromRotationMatrix(t){let e,i,s,n;const o=t.elements,c=o[0],h=o[4],u=o[8],l=o[1],d=o[5],y=o[9],m=o[2],z=o[6],b=o[10];if(Math.abs(h-l)<.01&&Math.abs(u-m)<.01&&Math.abs(y-z)<.01){if(Math.abs(h+l)<.1&&Math.abs(u+m)<.1&&Math.abs(y+z)<.1&&Math.abs(c+d+b-3)<.1)return this.set(1,0,0,0),this;e=Math.PI;const x=(c+1)/2,g=(d+1)/2,w=(b+1)/2,B=(h+l)/4,_=(u+m)/4,M=(y+z)/4;return x>g&&x>w?x<.01?(i=0,s=.707106781,n=.707106781):(i=Math.sqrt(x),s=B/i,n=_/i):g>w?g<.01?(i=.707106781,s=0,n=.707106781):(s=Math.sqrt(g),i=B/s,n=M/s):w<.01?(i=.707106781,s=.707106781,n=0):(n=Math.sqrt(w),i=_/n,s=M/n),this.set(i,s,n,e),this}let p=Math.sqrt((z-y)*(z-y)+(u-m)*(u-m)+(l-h)*(l-h));return Math.abs(p)<.001&&(p=1),this.x=(z-y)/p,this.y=(u-m)/p,this.z=(l-h)/p,this.w=Math.acos((c+d+b-1)/2),this}setFromMatrixPosition(t){const e=t.elements;return this.x=e[12],this.y=e[13],this.z=e[14],this.w=e[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,e){return this.x=V(this.x,t.x,e.x),this.y=V(this.y,t.y,e.y),this.z=V(this.z,t.z,e.z),this.w=V(this.w,t.w,e.w),this}clampScalar(t,e){return this.x=V(this.x,t,e),this.y=V(this.y,t,e),this.z=V(this.z,t,e),this.w=V(this.w,t,e),this}clampLength(t,e){const i=this.length();return this.divideScalar(i||1).multiplyScalar(V(i,t,e))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,e){return this.x+=(t.x-this.x)*e,this.y+=(t.y-this.y)*e,this.z+=(t.z-this.z)*e,this.w+=(t.w-this.w)*e,this}lerpVectors(t,e,i){return this.x=t.x+(e.x-t.x)*i,this.y=t.y+(e.y-t.y)*i,this.z=t.z+(e.z-t.z)*i,this.w=t.w+(e.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,e=0){return this.x=t[e],this.y=t[e+1],this.z=t[e+2],this.w=t[e+3],this}toArray(t=[],e=0){return t[e]=this.x,t[e+1]=this.y,t[e+2]=this.z,t[e+3]=this.w,t}fromBufferAttribute(t,e){return this.x=t.getX(e),this.y=t.getY(e),this.z=t.getZ(e),this.w=t.getW(e),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}};fs.prototype.isVector4=!0;let xe=fs;const ui=class ui{constructor(t,e,i,s,n,r,a,o,c,h,u,l,d,y,m,z){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,e,i,s,n,r,a,o,c,h,u,l,d,y,m,z)}set(t,e,i,s,n,r,a,o,c,h,u,l,d,y,m,z){const b=this.elements;return b[0]=t,b[4]=e,b[8]=i,b[12]=s,b[1]=n,b[5]=r,b[9]=a,b[13]=o,b[2]=c,b[6]=h,b[10]=u,b[14]=l,b[3]=d,b[7]=y,b[11]=m,b[15]=z,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new ui().fromArray(this.elements)}copy(t){const e=this.elements,i=t.elements;return e[0]=i[0],e[1]=i[1],e[2]=i[2],e[3]=i[3],e[4]=i[4],e[5]=i[5],e[6]=i[6],e[7]=i[7],e[8]=i[8],e[9]=i[9],e[10]=i[10],e[11]=i[11],e[12]=i[12],e[13]=i[13],e[14]=i[14],e[15]=i[15],this}copyPosition(t){const e=this.elements,i=t.elements;return e[12]=i[12],e[13]=i[13],e[14]=i[14],this}setFromMatrix3(t){const e=t.elements;return this.set(e[0],e[3],e[6],0,e[1],e[4],e[7],0,e[2],e[5],e[8],0,0,0,0,1),this}extractBasis(t,e,i){return this.determinantAffine()===0?(t.set(1,0,0),e.set(0,1,0),i.set(0,0,1),this):(t.setFromMatrixColumn(this,0),e.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(t,e,i){return this.set(t.x,e.x,i.x,0,t.y,e.y,i.y,0,t.z,e.z,i.z,0,0,0,0,1),this}extractRotation(t){if(t.determinantAffine()===0)return this.identity();const e=this.elements,i=t.elements,s=1/$t.setFromMatrixColumn(t,0).length(),n=1/$t.setFromMatrixColumn(t,1).length(),r=1/$t.setFromMatrixColumn(t,2).length();return e[0]=i[0]*s,e[1]=i[1]*s,e[2]=i[2]*s,e[3]=0,e[4]=i[4]*n,e[5]=i[5]*n,e[6]=i[6]*n,e[7]=0,e[8]=i[8]*r,e[9]=i[9]*r,e[10]=i[10]*r,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromEuler(t){const e=this.elements,i=t.x,s=t.y,n=t.z,r=Math.cos(i),a=Math.sin(i),o=Math.cos(s),c=Math.sin(s),h=Math.cos(n),u=Math.sin(n);if(t.order==="XYZ"){const l=r*h,d=r*u,y=a*h,m=a*u;e[0]=o*h,e[4]=-o*u,e[8]=c,e[1]=d+y*c,e[5]=l-m*c,e[9]=-a*o,e[2]=m-l*c,e[6]=y+d*c,e[10]=r*o}else if(t.order==="YXZ"){const l=o*h,d=o*u,y=c*h,m=c*u;e[0]=l+m*a,e[4]=y*a-d,e[8]=r*c,e[1]=r*u,e[5]=r*h,e[9]=-a,e[2]=d*a-y,e[6]=m+l*a,e[10]=r*o}else if(t.order==="ZXY"){const l=o*h,d=o*u,y=c*h,m=c*u;e[0]=l-m*a,e[4]=-r*u,e[8]=y+d*a,e[1]=d+y*a,e[5]=r*h,e[9]=m-l*a,e[2]=-r*c,e[6]=a,e[10]=r*o}else if(t.order==="ZYX"){const l=r*h,d=r*u,y=a*h,m=a*u;e[0]=o*h,e[4]=y*c-d,e[8]=l*c+m,e[1]=o*u,e[5]=m*c+l,e[9]=d*c-y,e[2]=-c,e[6]=a*o,e[10]=r*o}else if(t.order==="YZX"){const l=r*o,d=r*c,y=a*o,m=a*c;e[0]=o*h,e[4]=m-l*u,e[8]=y*u+d,e[1]=u,e[5]=r*h,e[9]=-a*h,e[2]=-c*h,e[6]=d*u+y,e[10]=l-m*u}else if(t.order==="XZY"){const l=r*o,d=r*c,y=a*o,m=a*c;e[0]=o*h,e[4]=-u,e[8]=c*h,e[1]=l*u+m,e[5]=r*h,e[9]=d*u-y,e[2]=y*u-d,e[6]=a*h,e[10]=m*u+l}return e[3]=0,e[7]=0,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,this}makeRotationFromQuaternion(t){return this.compose(rn,t,on)}lookAt(t,e,i){const s=this.elements;return et.subVectors(t,e),et.lengthSq()===0&&(et.z=1),et.normalize(),Pt.crossVectors(i,et),Pt.lengthSq()===0&&(Math.abs(i.z)===1?et.x+=1e-4:et.z+=1e-4,et.normalize(),Pt.crossVectors(i,et)),Pt.normalize(),ke.crossVectors(et,Pt),s[0]=Pt.x,s[4]=ke.x,s[8]=et.x,s[1]=Pt.y,s[5]=ke.y,s[9]=et.y,s[2]=Pt.z,s[6]=ke.z,s[10]=et.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,e){const i=t.elements,s=e.elements,n=this.elements,r=i[0],a=i[4],o=i[8],c=i[12],h=i[1],u=i[5],l=i[9],d=i[13],y=i[2],m=i[6],z=i[10],b=i[14],p=i[3],x=i[7],g=i[11],w=i[15],B=s[0],_=s[4],M=s[8],P=s[12],A=s[1],C=s[5],T=s[9],E=s[13],I=s[2],F=s[6],R=s[10],Z=s[14],tt=s[3],dt=s[7],at=s[11],pt=s[15];return n[0]=r*B+a*A+o*I+c*tt,n[4]=r*_+a*C+o*F+c*dt,n[8]=r*M+a*T+o*R+c*at,n[12]=r*P+a*E+o*Z+c*pt,n[1]=h*B+u*A+l*I+d*tt,n[5]=h*_+u*C+l*F+d*dt,n[9]=h*M+u*T+l*R+d*at,n[13]=h*P+u*E+l*Z+d*pt,n[2]=y*B+m*A+z*I+b*tt,n[6]=y*_+m*C+z*F+b*dt,n[10]=y*M+m*T+z*R+b*at,n[14]=y*P+m*E+z*Z+b*pt,n[3]=p*B+x*A+g*I+w*tt,n[7]=p*_+x*C+g*F+w*dt,n[11]=p*M+x*T+g*R+w*at,n[15]=p*P+x*E+g*Z+w*pt,this}multiplyScalar(t){const e=this.elements;return e[0]*=t,e[4]*=t,e[8]*=t,e[12]*=t,e[1]*=t,e[5]*=t,e[9]*=t,e[13]*=t,e[2]*=t,e[6]*=t,e[10]*=t,e[14]*=t,e[3]*=t,e[7]*=t,e[11]*=t,e[15]*=t,this}determinant(){const t=this.elements,e=t[0],i=t[4],s=t[8],n=t[12],r=t[1],a=t[5],o=t[9],c=t[13],h=t[2],u=t[6],l=t[10],d=t[14],y=t[3],m=t[7],z=t[11],b=t[15],p=o*d-c*l,x=a*d-c*u,g=a*l-o*u,w=r*d-c*h,B=r*l-o*h,_=r*u-a*h;return e*(m*p-z*x+b*g)-i*(y*p-z*w+b*B)+s*(y*x-m*w+b*_)-n*(y*g-m*B+z*_)}determinantAffine(){const t=this.elements,e=t[0],i=t[4],s=t[8],n=t[1],r=t[5],a=t[9],o=t[2],c=t[6],h=t[10];return e*(r*h-a*c)-i*(n*h-a*o)+s*(n*c-r*o)}transpose(){const t=this.elements;let e;return e=t[1],t[1]=t[4],t[4]=e,e=t[2],t[2]=t[8],t[8]=e,e=t[6],t[6]=t[9],t[9]=e,e=t[3],t[3]=t[12],t[12]=e,e=t[7],t[7]=t[13],t[13]=e,e=t[11],t[11]=t[14],t[14]=e,this}setPosition(t,e,i){const s=this.elements;return t.isVector3?(s[12]=t.x,s[13]=t.y,s[14]=t.z):(s[12]=t,s[13]=e,s[14]=i),this}invert(){const t=this.elements,e=t[0],i=t[1],s=t[2],n=t[3],r=t[4],a=t[5],o=t[6],c=t[7],h=t[8],u=t[9],l=t[10],d=t[11],y=t[12],m=t[13],z=t[14],b=t[15],p=e*a-i*r,x=e*o-s*r,g=e*c-n*r,w=i*o-s*a,B=i*c-n*a,_=s*c-n*o,M=h*m-u*y,P=h*z-l*y,A=h*b-d*y,C=u*z-l*m,T=u*b-d*m,E=l*b-d*z,I=p*E-x*T+g*C+w*A-B*P+_*M;if(I===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const F=1/I;return t[0]=(a*E-o*T+c*C)*F,t[1]=(s*T-i*E-n*C)*F,t[2]=(m*_-z*B+b*w)*F,t[3]=(l*B-u*_-d*w)*F,t[4]=(o*A-r*E-c*P)*F,t[5]=(e*E-s*A+n*P)*F,t[6]=(z*g-y*_-b*x)*F,t[7]=(h*_-l*g+d*x)*F,t[8]=(r*T-a*A+c*M)*F,t[9]=(i*A-e*T-n*M)*F,t[10]=(y*B-m*g+b*p)*F,t[11]=(u*g-h*B-d*p)*F,t[12]=(a*P-r*C-o*M)*F,t[13]=(e*C-i*P+s*M)*F,t[14]=(m*x-y*w-z*p)*F,t[15]=(h*w-u*x+l*p)*F,this}scale(t){const e=this.elements,i=t.x,s=t.y,n=t.z;return e[0]*=i,e[4]*=s,e[8]*=n,e[1]*=i,e[5]*=s,e[9]*=n,e[2]*=i,e[6]*=s,e[10]*=n,e[3]*=i,e[7]*=s,e[11]*=n,this}getMaxScaleOnAxis(){const t=this.elements,e=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],s=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(e,i,s))}makeTranslation(t,e,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,e,0,0,1,i,0,0,0,1),this}makeRotationX(t){const e=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,e,-i,0,0,i,e,0,0,0,0,1),this}makeRotationY(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,0,i,0,0,1,0,0,-i,0,e,0,0,0,0,1),this}makeRotationZ(t){const e=Math.cos(t),i=Math.sin(t);return this.set(e,-i,0,0,i,e,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,e){const i=Math.cos(e),s=Math.sin(e),n=1-i,r=t.x,a=t.y,o=t.z,c=n*r,h=n*a;return this.set(c*r+i,c*a-s*o,c*o+s*a,0,c*a+s*o,h*a+i,h*o-s*r,0,c*o-s*a,h*o+s*r,n*o*o+i,0,0,0,0,1),this}makeScale(t,e,i){return this.set(t,0,0,0,0,e,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,e,i,s,n,r){return this.set(1,i,n,0,t,1,r,0,e,s,1,0,0,0,0,1),this}compose(t,e,i){const s=this.elements,n=e._x,r=e._y,a=e._z,o=e._w,c=n+n,h=r+r,u=a+a,l=n*c,d=n*h,y=n*u,m=r*h,z=r*u,b=a*u,p=o*c,x=o*h,g=o*u,w=i.x,B=i.y,_=i.z;return s[0]=(1-(m+b))*w,s[1]=(d+g)*w,s[2]=(y-x)*w,s[3]=0,s[4]=(d-g)*B,s[5]=(1-(l+b))*B,s[6]=(z+p)*B,s[7]=0,s[8]=(y+x)*_,s[9]=(z-p)*_,s[10]=(1-(l+m))*_,s[11]=0,s[12]=t.x,s[13]=t.y,s[14]=t.z,s[15]=1,this}decompose(t,e,i){const s=this.elements;t.x=s[12],t.y=s[13],t.z=s[14];const n=this.determinantAffine();if(n===0)return i.set(1,1,1),e.identity(),this;let r=$t.set(s[0],s[1],s[2]).length();const a=$t.set(s[4],s[5],s[6]).length(),o=$t.set(s[8],s[9],s[10]).length();n<0&&(r=-r),ct.copy(this);const c=1/r,h=1/a,u=1/o;return ct.elements[0]*=c,ct.elements[1]*=c,ct.elements[2]*=c,ct.elements[4]*=h,ct.elements[5]*=h,ct.elements[6]*=h,ct.elements[8]*=u,ct.elements[9]*=u,ct.elements[10]*=u,e.setFromRotationMatrix(ct),i.x=r,i.y=a,i.z=o,this}makePerspective(t,e,i,s,n,r,a=2e3,o=!1){const c=this.elements,h=2*n/(e-t),u=2*n/(i-s),l=(e+t)/(e-t),d=(i+s)/(i-s);let y,m;if(o)y=n/(r-n),m=r*n/(r-n);else if(a===2e3)y=-(r+n)/(r-n),m=-2*r*n/(r-n);else if(a===2001)y=-r/(r-n),m=-r*n/(r-n);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+a);return c[0]=h,c[4]=0,c[8]=l,c[12]=0,c[1]=0,c[5]=u,c[9]=d,c[13]=0,c[2]=0,c[6]=0,c[10]=y,c[14]=m,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(t,e,i,s,n,r,a=2e3,o=!1){const c=this.elements,h=2/(e-t),u=2/(i-s),l=-(e+t)/(e-t),d=-(i+s)/(i-s);let y,m;if(o)y=1/(r-n),m=r/(r-n);else if(a===2e3)y=-2/(r-n),m=-(r+n)/(r-n);else if(a===2001)y=-1/(r-n),m=-n/(r-n);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+a);return c[0]=h,c[4]=0,c[8]=0,c[12]=l,c[1]=0,c[5]=u,c[9]=0,c[13]=d,c[2]=0,c[6]=0,c[10]=y,c[14]=m,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(t){const e=this.elements,i=t.elements;for(let s=0;s<16;s++)if(e[s]!==i[s])return!1;return!0}fromArray(t,e=0){for(let i=0;i<16;i++)this.elements[i]=t[i+e];return this}toArray(t=[],e=0){const i=this.elements;return t[e]=i[0],t[e+1]=i[1],t[e+2]=i[2],t[e+3]=i[3],t[e+4]=i[4],t[e+5]=i[5],t[e+6]=i[6],t[e+7]=i[7],t[e+8]=i[8],t[e+9]=i[9],t[e+10]=i[10],t[e+11]=i[11],t[e+12]=i[12],t[e+13]=i[13],t[e+14]=i[14],t[e+15]=i[15],t}};ui.prototype.isMatrix4=!0;let H=ui;const $t=new S,ct=new H,rn=new S(0,0,0),on=new S(1,1,1),Pt=new S,ke=new S,et=new S,ws=new H,bs=new pe;class Ue{constructor(t=0,e=0,i=0,s=Ue.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=e,this._z=i,this._order=s}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,e,i,s=this._order){return this._x=t,this._y=e,this._z=i,this._order=s,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,e=this._order,i=!0){const s=t.elements,n=s[0],r=s[4],a=s[8],o=s[1],c=s[5],h=s[9],u=s[2],l=s[6],d=s[10];switch(e){case"XYZ":this._y=Math.asin(V(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,d),this._z=Math.atan2(-r,n)):(this._x=Math.atan2(l,c),this._z=0);break;case"YXZ":this._x=Math.asin(-V(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(a,d),this._z=Math.atan2(o,c)):(this._y=Math.atan2(-u,n),this._z=0);break;case"ZXY":this._x=Math.asin(V(l,-1,1)),Math.abs(l)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-r,c)):(this._y=0,this._z=Math.atan2(o,n));break;case"ZYX":this._y=Math.asin(-V(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(l,d),this._z=Math.atan2(o,n)):(this._x=0,this._z=Math.atan2(-r,c));break;case"YZX":this._z=Math.asin(V(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,c),this._y=Math.atan2(-u,n)):(this._x=0,this._y=Math.atan2(a,d));break;case"XZY":this._z=Math.asin(-V(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(l,c),this._y=Math.atan2(a,n)):(this._x=Math.atan2(-h,d),this._y=0);break;default:yt("Euler: .setFromRotationMatrix() encountered an unknown order: "+e)}return this._order=e,i===!0&&this._onChangeCallback(),this}setFromQuaternion(t,e,i){return ws.makeRotationFromQuaternion(t),this.setFromRotationMatrix(ws,e,i)}setFromVector3(t,e=this._order){return this.set(t.x,t.y,t.z,e)}reorder(t){return bs.setFromEuler(this),this.setFromQuaternion(bs,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],e=0){return t[e]=this._x,t[e+1]=this._y,t[e+2]=this._z,t[e+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ue.DEFAULT_ORDER="XYZ";class an{constructor(){this.mask=1}set(t){this.mask=(1<<t|0)>>>0}enable(t){this.mask|=1<<t|0}enableAll(){this.mask=-1}toggle(t){this.mask^=1<<t|0}disable(t){this.mask&=~(1<<t|0)}disableAll(){this.mask=0}test(t){return(this.mask&t.mask)!==0}isEnabled(t){return(this.mask&(1<<t|0))!==0}}let cn=0;const zs=new S,Jt=new pe,gt=new H,Ne=new S,ge=new S,hn=new S,ln=new pe,_s=new S(1,0,0),Ms=new S(0,1,0),As=new S(0,0,1),Ss={type:"added"},un={type:"removed"},Gt={type:"childadded",child:null},bi={type:"childremoved",child:null};class Ct extends Ve{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:cn++}),this.uuid=Re(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Ct.DEFAULT_UP.clone();const t=new S,e=new Ue,i=new pe,s=new S(1,1,1);function n(){i.setFromEuler(e,!1)}function r(){e.setFromQuaternion(i,void 0,!1)}e._onChange(n),i._onChange(r),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:e},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:s},modelViewMatrix:{value:new H},normalMatrix:{value:new xt}}),this.matrix=new H,this.matrixWorld=new H,this.matrixAutoUpdate=Ct.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Ct.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new an,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,e){this.quaternion.setFromAxisAngle(t,e)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,e){return Jt.setFromAxisAngle(t,e),this.quaternion.multiply(Jt),this}rotateOnWorldAxis(t,e){return Jt.setFromAxisAngle(t,e),this.quaternion.premultiply(Jt),this}rotateX(t){return this.rotateOnAxis(_s,t)}rotateY(t){return this.rotateOnAxis(Ms,t)}rotateZ(t){return this.rotateOnAxis(As,t)}translateOnAxis(t,e){return zs.copy(t).applyQuaternion(this.quaternion),this.position.add(zs.multiplyScalar(e)),this}translateX(t){return this.translateOnAxis(_s,t)}translateY(t){return this.translateOnAxis(Ms,t)}translateZ(t){return this.translateOnAxis(As,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(gt.copy(this.matrixWorld).invert())}lookAt(t,e,i){t.isVector3?Ne.copy(t):Ne.set(t,e,i);const s=this.parent;this.updateWorldMatrix(!0,!1),ge.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?gt.lookAt(ge,Ne,this.up):gt.lookAt(Ne,ge,this.up),this.quaternion.setFromRotationMatrix(gt),s&&(gt.extractRotation(s.matrixWorld),Jt.setFromRotationMatrix(gt),this.quaternion.premultiply(Jt.invert()))}add(t){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return t===this?(Ut("Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(t.removeFromParent(),t.parent=this,this.children.push(t),t.dispatchEvent(Ss),Gt.child=t,this.dispatchEvent(Gt),Gt.child=null):Ut("Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const e=this.children.indexOf(t);return e!==-1&&(t.parent=null,this.children.splice(e,1),t.dispatchEvent(un),bi.child=t,this.dispatchEvent(bi),bi.child=null),this}removeFromParent(){const t=this.parent;return t!==null&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),gt.copy(this.matrixWorld).invert(),t.parent!==null&&(t.parent.updateWorldMatrix(!0,!1),gt.multiply(t.parent.matrixWorld)),t.applyMatrix4(gt),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(Ss),Gt.child=t,this.dispatchEvent(Gt),Gt.child=null,this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,e){if(this[t]===e)return this;for(let i=0,s=this.children.length;i<s;i++){const r=this.children[i].getObjectByProperty(t,e);if(r!==void 0)return r}}getObjectsByProperty(t,e,i=[]){this[t]===e&&i.push(this);const s=this.children;for(let n=0,r=s.length;n<r;n++)s[n].getObjectsByProperty(t,e,i);return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ge,t,hn),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(ge,ln,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);const e=this.matrixWorld.elements;return t.set(e[8],e[9],e[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(t){t(this);const e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].traverse(t)}traverseVisible(t){if(this.visible===!1)return;t(this);const e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].traverseVisible(t)}traverseAncestors(t){const e=this.parent;e!==null&&(t(e),e.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const t=this.pivot;if(t!==null){const e=t.x,i=t.y,s=t.z,n=this.matrix.elements;n[12]+=e-n[0]*e-n[4]*i-n[8]*s,n[13]+=i-n[1]*e-n[5]*i-n[9]*s,n[14]+=s-n[2]*e-n[6]*i-n[10]*s}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,t=!0);const e=this.children;for(let i=0,s=e.length;i<s;i++)e[i].updateMatrixWorld(t)}updateWorldMatrix(t,e,i=!1){const s=this.parent;if(t===!0&&s!==null&&s.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),e===!0){const n=this.children;for(let r=0,a=n.length;r<a;r++)n[r].updateWorldMatrix(!1,!0,i)}}toJSON(t){const e=t===void 0||typeof t=="string",i={};e&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const s={};s.uuid=this.uuid,s.type=this.type,s.name=this.name,s.castShadow=this.castShadow,s.receiveShadow=this.receiveShadow,s.visible=this.visible,s.frustumCulled=this.frustumCulled,s.renderOrder=this.renderOrder,s.static=this.static,s.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(s.userData=this.userData),s.layers=this.layers.mask,s.matrix=this.matrix.toArray(),s.up=this.up.toArray(),this.pivot!==null&&(s.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(s.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(s.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(s.type="InstancedMesh",s.count=this.count,s.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(s.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(s.type="BatchedMesh",s.perObjectFrustumCulled=this.perObjectFrustumCulled,s.sortObjects=this.sortObjects,s.drawRanges=this._drawRanges,s.reservedRanges=this._reservedRanges,s.geometryInfo=this._geometryInfo.map(a=>({...a,boundingBox:a.boundingBox?a.boundingBox.toJSON():void 0,boundingSphere:a.boundingSphere?a.boundingSphere.toJSON():void 0})),s.instanceInfo=this._instanceInfo.map(a=>({...a})),s.availableInstanceIds=this._availableInstanceIds.slice(),s.availableGeometryIds=this._availableGeometryIds.slice(),s.nextIndexStart=this._nextIndexStart,s.nextVertexStart=this._nextVertexStart,s.geometryCount=this._geometryCount,s.maxInstanceCount=this._maxInstanceCount,s.maxVertexCount=this._maxVertexCount,s.maxIndexCount=this._maxIndexCount,s.geometryInitialized=this._geometryInitialized,s.matricesTexture=this._matricesTexture.toJSON(t),s.indirectTexture=this._indirectTexture.toJSON(t),this._colorsTexture!==null&&(s.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(s.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(s.boundingBox=this.boundingBox.toJSON()));function n(a,o){return a[o.uuid]===void 0&&(a[o.uuid]=o.toJSON(t)),o.uuid}if(this.isScene)this.background&&(this.background.isColor?s.background=this.background.toJSON():this.background.isTexture&&(s.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(s.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){s.geometry=n(t.geometries,this.geometry);const a=this.geometry.parameters;if(a!==void 0&&a.shapes!==void 0){const o=a.shapes;if(Array.isArray(o))for(let c=0,h=o.length;c<h;c++){const u=o[c];n(t.shapes,u)}else n(t.shapes,o)}}if(this.isSkinnedMesh&&(s.bindMode=this.bindMode,s.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(n(t.skeletons,this.skeleton),s.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const a=[];for(let o=0,c=this.material.length;o<c;o++)a.push(n(t.materials,this.material[o]));s.material=a}else s.material=n(t.materials,this.material);if(this.children.length>0){s.children=[];for(let a=0;a<this.children.length;a++)s.children.push(this.children[a].toJSON(t).object)}if(this.animations.length>0){s.animations=[];for(let a=0;a<this.animations.length;a++){const o=this.animations[a];s.animations.push(n(t.animations,o))}}if(e){const a=r(t.geometries),o=r(t.materials),c=r(t.textures),h=r(t.images),u=r(t.shapes),l=r(t.skeletons),d=r(t.animations),y=r(t.nodes);a.length>0&&(i.geometries=a),o.length>0&&(i.materials=o),c.length>0&&(i.textures=c),h.length>0&&(i.images=h),u.length>0&&(i.shapes=u),l.length>0&&(i.skeletons=l),d.length>0&&(i.animations=d),y.length>0&&(i.nodes=y)}return i.object=s,i;function r(a){const o=[];for(const c in a){const h=a[c];delete h.metadata,o.push(h)}return o}}clone(t){return new this.constructor().copy(this,t)}copy(t,e=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.pivot=t.pivot!==null?t.pivot.clone():null,this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.static=t.static,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),e===!0)for(let i=0;i<t.children.length;i++){const s=t.children[i];this.add(s.clone())}return this}dispose(){this.dispatchEvent({type:"dispose"})}}Ct.DEFAULT_UP=new S(0,1,0),Ct.DEFAULT_MATRIX_AUTO_UPDATE=!0,Ct.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const ht=new S,wt=new S,zi=new S,bt=new S,Qt=new S,jt=new S,Bs=new S,_i=new S,Mi=new S,Ai=new S,Si=new xe,Bi=new xe,Ti=new xe;class st{constructor(t=new S,e=new S,i=new S){this.a=t,this.b=e,this.c=i}static getNormal(t,e,i,s){s.subVectors(i,e),ht.subVectors(t,e),s.cross(ht);const n=s.lengthSq();return n>0?s.multiplyScalar(1/Math.sqrt(n)):s.set(0,0,0)}static getBarycoord(t,e,i,s,n){ht.subVectors(s,e),wt.subVectors(i,e),zi.subVectors(t,e);const r=ht.dot(ht),a=ht.dot(wt),o=ht.dot(zi),c=wt.dot(wt),h=wt.dot(zi),u=r*c-a*a;if(u===0)return n.set(0,0,0),null;const l=1/u,d=(c*o-a*h)*l,y=(r*h-a*o)*l;return n.set(1-d-y,y,d)}static containsPoint(t,e,i,s){return this.getBarycoord(t,e,i,s,bt)===null?!1:bt.x>=0&&bt.y>=0&&bt.x+bt.y<=1}static getInterpolation(t,e,i,s,n,r,a,o){return this.getBarycoord(t,e,i,s,bt)===null?(o.x=0,o.y=0,"z"in o&&(o.z=0),"w"in o&&(o.w=0),null):(o.setScalar(0),o.addScaledVector(n,bt.x),o.addScaledVector(r,bt.y),o.addScaledVector(a,bt.z),o)}static getInterpolatedAttribute(t,e,i,s,n,r){return Si.setScalar(0),Bi.setScalar(0),Ti.setScalar(0),Si.fromBufferAttribute(t,e),Bi.fromBufferAttribute(t,i),Ti.fromBufferAttribute(t,s),r.setScalar(0),r.addScaledVector(Si,n.x),r.addScaledVector(Bi,n.y),r.addScaledVector(Ti,n.z),r}static isFrontFacing(t,e,i,s){return ht.subVectors(i,e),wt.subVectors(t,e),ht.cross(wt).dot(s)<0}set(t,e,i){return this.a.copy(t),this.b.copy(e),this.c.copy(i),this}setFromPointsAndIndices(t,e,i,s){return this.a.copy(t[e]),this.b.copy(t[i]),this.c.copy(t[s]),this}setFromAttributeAndIndices(t,e,i,s){return this.a.fromBufferAttribute(t,e),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,s),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return ht.subVectors(this.c,this.b),wt.subVectors(this.a,this.b),ht.cross(wt).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return st.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,e){return st.getBarycoord(t,this.a,this.b,this.c,e)}getInterpolation(t,e,i,s,n){return st.getInterpolation(t,this.a,this.b,this.c,e,i,s,n)}containsPoint(t){return st.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return st.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,e){const i=this.a,s=this.b,n=this.c;let r,a;Qt.subVectors(s,i),jt.subVectors(n,i),_i.subVectors(t,i);const o=Qt.dot(_i),c=jt.dot(_i);if(o<=0&&c<=0)return e.copy(i);Mi.subVectors(t,s);const h=Qt.dot(Mi),u=jt.dot(Mi);if(h>=0&&u<=h)return e.copy(s);const l=o*u-h*c;if(l<=0&&o>=0&&h<=0)return r=o/(o-h),e.copy(i).addScaledVector(Qt,r);Ai.subVectors(t,n);const d=Qt.dot(Ai),y=jt.dot(Ai);if(y>=0&&d<=y)return e.copy(n);const m=d*c-o*y;if(m<=0&&c>=0&&y<=0)return a=c/(c-y),e.copy(i).addScaledVector(jt,a);const z=h*y-d*u;if(z<=0&&u-h>=0&&d-y>=0)return Bs.subVectors(n,s),a=(u-h)/(u-h+(d-y)),e.copy(s).addScaledVector(Bs,a);const b=1/(z+m+l);return r=m*b,a=l*b,e.copy(i).addScaledVector(Qt,r).addScaledVector(jt,a)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}}class Q{constructor(t=new S(1/0,1/0,1/0),e=new S(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=t,this.max=e}set(t,e){return this.min.copy(t),this.max.copy(e),this}setFromArray(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e+=3)this.expandByPoint(lt.fromArray(t,e));return this}setFromBufferAttribute(t){this.makeEmpty();for(let e=0,i=t.count;e<i;e++)this.expandByPoint(lt.fromBufferAttribute(t,e));return this}setFromPoints(t){this.makeEmpty();for(let e=0,i=t.length;e<i;e++)this.expandByPoint(t[e]);return this}setFromCenterAndSize(t,e){const i=lt.copy(e).multiplyScalar(.5);return this.min.copy(t).sub(i),this.max.copy(t).add(i),this}setFromObject(t,e=!1){return this.makeEmpty(),this.expandByObject(t,e)}clone(){return new this.constructor().copy(this)}copy(t){return this.min.copy(t.min),this.max.copy(t.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(t){return this.isEmpty()?t.set(0,0,0):t.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(t){return this.isEmpty()?t.set(0,0,0):t.subVectors(this.max,this.min)}expandByPoint(t){return this.min.min(t),this.max.max(t),this}expandByVector(t){return this.min.sub(t),this.max.add(t),this}expandByScalar(t){return this.min.addScalar(-t),this.max.addScalar(t),this}expandByObject(t,e=!1){t.updateWorldMatrix(!1,!1);const i=t.geometry;if(i!==void 0){const n=i.getAttribute("position");if(e===!0&&n!==void 0&&t.isInstancedMesh!==!0)for(let r=0,a=n.count;r<a;r++)t.isMesh===!0?t.getVertexPosition(r,lt):lt.fromBufferAttribute(n,r),lt.applyMatrix4(t.matrixWorld),this.expandByPoint(lt);else t.boundingBox!==void 0?(t.boundingBox===null&&t.computeBoundingBox(),Le.copy(t.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),Le.copy(i.boundingBox)),Le.applyMatrix4(t.matrixWorld),this.union(Le)}const s=t.children;for(let n=0,r=s.length;n<r;n++)this.expandByObject(s[n],e);return this}containsPoint(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y&&t.z>=this.min.z&&t.z<=this.max.z}containsBox(t){return this.min.x<=t.min.x&&t.max.x<=this.max.x&&this.min.y<=t.min.y&&t.max.y<=this.max.y&&this.min.z<=t.min.z&&t.max.z<=this.max.z}getParameter(t,e){return e.set((t.x-this.min.x)/(this.max.x-this.min.x),(t.y-this.min.y)/(this.max.y-this.min.y),(t.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(t){return t.max.x>=this.min.x&&t.min.x<=this.max.x&&t.max.y>=this.min.y&&t.min.y<=this.max.y&&t.max.z>=this.min.z&&t.min.z<=this.max.z}intersectsSphere(t){return this.clampPoint(t.center,lt),lt.distanceToSquared(t.center)<=t.radius*t.radius}intersectsPlane(t){let e,i;return t.normal.x>0?(e=t.normal.x*this.min.x,i=t.normal.x*this.max.x):(e=t.normal.x*this.max.x,i=t.normal.x*this.min.x),t.normal.y>0?(e+=t.normal.y*this.min.y,i+=t.normal.y*this.max.y):(e+=t.normal.y*this.max.y,i+=t.normal.y*this.min.y),t.normal.z>0?(e+=t.normal.z*this.min.z,i+=t.normal.z*this.max.z):(e+=t.normal.z*this.max.z,i+=t.normal.z*this.min.z),e<=-t.constant&&i>=-t.constant}intersectsTriangle(t){if(this.isEmpty())return!1;this.getCenter(we),De.subVectors(this.max,we),Kt.subVectors(t.a,we),te.subVectors(t.b,we),ee.subVectors(t.c,we),Et.subVectors(te,Kt),It.subVectors(ee,te),Lt.subVectors(Kt,ee);let e=[0,-Et.z,Et.y,0,-It.z,It.y,0,-Lt.z,Lt.y,Et.z,0,-Et.x,It.z,0,-It.x,Lt.z,0,-Lt.x,-Et.y,Et.x,0,-It.y,It.x,0,-Lt.y,Lt.x,0];return!Pi(e,Kt,te,ee,De)||(e=[1,0,0,0,1,0,0,0,1],!Pi(e,Kt,te,ee,De))?!1:(qe.crossVectors(Et,It),e=[qe.x,qe.y,qe.z],Pi(e,Kt,te,ee,De))}clampPoint(t,e){return e.copy(t).clamp(this.min,this.max)}distanceToPoint(t){return this.clampPoint(t,lt).distanceTo(t)}getBoundingSphere(t){return this.isEmpty()?t.makeEmpty():(this.getCenter(t.center),t.radius=this.getSize(lt).length()*.5),t}intersect(t){return this.min.max(t.min),this.max.min(t.max),this.isEmpty()&&this.makeEmpty(),this}union(t){return this.min.min(t.min),this.max.max(t.max),this}applyMatrix4(t){return this.isEmpty()?this:(zt[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(t),zt[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(t),zt[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(t),zt[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(t),zt[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(t),zt[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(t),zt[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(t),zt[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(t),this.setFromPoints(zt),this)}translate(t){return this.min.add(t),this.max.add(t),this}equals(t){return t.min.equals(this.min)&&t.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(t){return this.min.fromArray(t.min),this.max.fromArray(t.max),this}}const zt=[new S,new S,new S,new S,new S,new S,new S,new S],lt=new S,Le=new Q,Kt=new S,te=new S,ee=new S,Et=new S,It=new S,Lt=new S,we=new S,De=new S,qe=new S,Dt=new S;function Pi(f,t,e,i,s){for(let n=0,r=f.length-3;n<=r;n+=3){Dt.fromArray(f,n);const a=s.x*Math.abs(Dt.x)+s.y*Math.abs(Dt.y)+s.z*Math.abs(Dt.z),o=t.dot(Dt),c=e.dot(Dt),h=i.dot(Dt);if(Math.max(-Math.max(o,c,h),Math.min(o,c,h))>a)return!1}return!0}const L=new S,ve=new Y;let fn=0;class mt extends Ve{constructor(t,e,i=!1){if(super(),Array.isArray(t))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:fn++}),this.name="",this.array=t,this.itemSize=e,this.count=t!==void 0?t.length/e:0,this.normalized=i,this.usage=35044,this.updateRanges=[],this.gpuType=1015,this.version=0}onUploadCallback(){}set needsUpdate(t){t===!0&&this.version++}setUsage(t){return this.usage=t,this}addUpdateRange(t,e){this.updateRanges.push({start:t,count:e})}clearUpdateRanges(){this.updateRanges.length=0}copy(t){return this.name=t.name,this.array=new t.array.constructor(t.array),this.itemSize=t.itemSize,this.count=t.count,this.normalized=t.normalized,this.usage=t.usage,this.gpuType=t.gpuType,this}copyAt(t,e,i){t*=this.itemSize,i*=e.itemSize;for(let s=0,n=this.itemSize;s<n;s++)this.array[t+s]=e.array[i+s];return this}copyArray(t){return this.array.set(t),this}applyMatrix3(t){if(this.itemSize===2)for(let e=0,i=this.count;e<i;e++)ve.fromBufferAttribute(this,e),ve.applyMatrix3(t),this.setXY(e,ve.x,ve.y);else if(this.itemSize===3)for(let e=0,i=this.count;e<i;e++)L.fromBufferAttribute(this,e),L.applyMatrix3(t),this.setXYZ(e,L.x,L.y,L.z);return this}applyMatrix4(t){for(let e=0,i=this.count;e<i;e++)L.fromBufferAttribute(this,e),L.applyMatrix4(t),this.setXYZ(e,L.x,L.y,L.z);return this}applyNormalMatrix(t){for(let e=0,i=this.count;e<i;e++)L.fromBufferAttribute(this,e),L.applyNormalMatrix(t),this.setXYZ(e,L.x,L.y,L.z);return this}transformDirection(t){for(let e=0,i=this.count;e<i;e++)L.fromBufferAttribute(this,e),L.transformDirection(t),this.setXYZ(e,L.x,L.y,L.z);return this}set(t,e=0){return this.array.set(t,e),this}getComponent(t,e){let i=this.array[t*this.itemSize+e];return this.normalized&&(i=me(i,this.array)),i}setComponent(t,e,i){return this.normalized&&(i=K(i,this.array)),this.array[t*this.itemSize+e]=i,this}getX(t){let e=this.array[t*this.itemSize];return this.normalized&&(e=me(e,this.array)),e}setX(t,e){return this.normalized&&(e=K(e,this.array)),this.array[t*this.itemSize]=e,this}getY(t){let e=this.array[t*this.itemSize+1];return this.normalized&&(e=me(e,this.array)),e}setY(t,e){return this.normalized&&(e=K(e,this.array)),this.array[t*this.itemSize+1]=e,this}getZ(t){let e=this.array[t*this.itemSize+2];return this.normalized&&(e=me(e,this.array)),e}setZ(t,e){return this.normalized&&(e=K(e,this.array)),this.array[t*this.itemSize+2]=e,this}getW(t){let e=this.array[t*this.itemSize+3];return this.normalized&&(e=me(e,this.array)),e}setW(t,e){return this.normalized&&(e=K(e,this.array)),this.array[t*this.itemSize+3]=e,this}setXY(t,e,i){return t*=this.itemSize,this.normalized&&(e=K(e,this.array),i=K(i,this.array)),this.array[t+0]=e,this.array[t+1]=i,this}setXYZ(t,e,i,s){return t*=this.itemSize,this.normalized&&(e=K(e,this.array),i=K(i,this.array),s=K(s,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=s,this}setXYZW(t,e,i,s,n){return t*=this.itemSize,this.normalized&&(e=K(e,this.array),i=K(i,this.array),s=K(s,this.array),n=K(n,this.array)),this.array[t+0]=e,this.array[t+1]=i,this.array[t+2]=s,this.array[t+3]=n,this}onUpload(t){return this.onUploadCallback=t,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const t={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return t.name=this.name,t.usage=this.usage,t.gpuType=this.gpuType,t}dispose(){this.dispatchEvent({type:"dispose"})}}class dn extends mt{constructor(t,e,i){super(new Uint16Array(t),e,i)}}class yn extends mt{constructor(t,e,i){super(new Uint32Array(t),e,i)}}class mn extends mt{constructor(t,e,i){super(new Float32Array(t),e,i)}}const pn=new Q,be=new S,Ci=new S;class xn{constructor(t=new S,e=-1){this.isSphere=!0,this.center=t,this.radius=e}set(t,e){return this.center.copy(t),this.radius=e,this}setFromPoints(t,e){const i=this.center;e!==void 0?i.copy(e):pn.setFromPoints(t).getCenter(i);let s=0;for(let n=0,r=t.length;n<r;n++)s=Math.max(s,i.distanceToSquared(t[n]));return this.radius=Math.sqrt(s),this}copy(t){return this.center.copy(t.center),this.radius=t.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(t){return t.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(t){return t.distanceTo(this.center)-this.radius}intersectsSphere(t){const e=this.radius+t.radius;return t.center.distanceToSquared(this.center)<=e*e}intersectsBox(t){return t.intersectsSphere(this)}intersectsPlane(t){return Math.abs(t.distanceToPoint(this.center))<=this.radius}clampPoint(t,e){const i=this.center.distanceToSquared(t);return e.copy(t),i>this.radius*this.radius&&(e.sub(this.center).normalize(),e.multiplyScalar(this.radius).add(this.center)),e}getBoundingBox(t){return this.isEmpty()?(t.makeEmpty(),t):(t.set(this.center,this.center),t.expandByScalar(this.radius),t)}applyMatrix4(t){return this.center.applyMatrix4(t),this.radius=this.radius*t.getMaxScaleOnAxis(),this}translate(t){return this.center.add(t),this}expandByPoint(t){if(this.isEmpty())return this.center.copy(t),this.radius=0,this;be.subVectors(t,this.center);const e=be.lengthSq();if(e>this.radius*this.radius){const i=Math.sqrt(e),s=(i-this.radius)*.5;this.center.addScaledVector(be,s/i),this.radius+=s}return this}union(t){return t.isEmpty()?this:this.isEmpty()?(this.copy(t),this):(this.center.equals(t.center)===!0?this.radius=Math.max(this.radius,t.radius):(Ci.subVectors(t.center,this.center).setLength(t.radius),this.expandByPoint(be.copy(t.center).add(Ci)),this.expandByPoint(be.copy(t.center).sub(Ci))),this)}equals(t){return t.center.equals(this.center)&&t.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(t){return this.radius=t.radius,this.center.fromArray(t.center),this}}let gn=0;const nt=new H,Ei=new Ct,ie=new S,it=new Q,ze=new Q,W=new S;class Ii extends Ve{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:gn++}),this.uuid=Re(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(Ks(t)?yn:dn)(t,1):this.index=t,this}setIndirect(t,e=0){return this.indirect=t,this.indirectOffset=e,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,e){return this.attributes[t]=e,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,e,i=0){this.groups.push({start:t,count:e,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,e){this.drawRange.start=t,this.drawRange.count=e}applyMatrix4(t){const e=this.attributes.position;e!==void 0&&(e.applyMatrix4(t),e.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const n=new xt().getNormalMatrix(t);i.applyNormalMatrix(n),i.needsUpdate=!0}const s=this.attributes.tangent;return s!==void 0&&(s.transformDirection(t),s.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(t){return nt.makeRotationFromQuaternion(t),this.applyMatrix4(nt),this}rotateX(t){return nt.makeRotationX(t),this.applyMatrix4(nt),this}rotateY(t){return nt.makeRotationY(t),this.applyMatrix4(nt),this}rotateZ(t){return nt.makeRotationZ(t),this.applyMatrix4(nt),this}translate(t,e,i){return nt.makeTranslation(t,e,i),this.applyMatrix4(nt),this}scale(t,e,i){return nt.makeScale(t,e,i),this.applyMatrix4(nt),this}lookAt(t){return Ei.lookAt(t),Ei.updateMatrix(),this.applyMatrix4(Ei.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ie).negate(),this.translate(ie.x,ie.y,ie.z),this}setFromPoints(t){const e=this.getAttribute("position");if(e===void 0){const i=[];for(let s=0,n=t.length;s<n;s++){const r=t[s];i.push(r.x,r.y,r.z||0)}this.setAttribute("position",new mn(i,3))}else{const i=Math.min(t.length,e.count);for(let s=0;s<i;s++){const n=t[s];e.setXYZ(s,n.x,n.y,n.z||0)}t.length>e.count&&yt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),e.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Q);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){Ut("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new S(-1/0,-1/0,-1/0),new S(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),e)for(let i=0,s=e.length;i<s;i++){const n=e[i];it.setFromBufferAttribute(n),this.morphTargetsRelative?(W.addVectors(this.boundingBox.min,it.min),this.boundingBox.expandByPoint(W),W.addVectors(this.boundingBox.max,it.max),this.boundingBox.expandByPoint(W)):(this.boundingBox.expandByPoint(it.min),this.boundingBox.expandByPoint(it.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Ut('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new xn);const t=this.attributes.position,e=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){Ut("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new S,1/0);return}if(t){const i=this.boundingSphere.center;if(it.setFromBufferAttribute(t),e)for(let n=0,r=e.length;n<r;n++){const a=e[n];ze.setFromBufferAttribute(a),this.morphTargetsRelative?(W.addVectors(it.min,ze.min),it.expandByPoint(W),W.addVectors(it.max,ze.max),it.expandByPoint(W)):(it.expandByPoint(ze.min),it.expandByPoint(ze.max))}it.getCenter(i);let s=0;for(let n=0,r=t.count;n<r;n++)W.fromBufferAttribute(t,n),s=Math.max(s,i.distanceToSquared(W));if(e)for(let n=0,r=e.length;n<r;n++){const a=e[n],o=this.morphTargetsRelative;for(let c=0,h=a.count;c<h;c++)W.fromBufferAttribute(a,c),o&&(ie.fromBufferAttribute(t,c),W.add(ie)),s=Math.max(s,i.distanceToSquared(W))}this.boundingSphere.radius=Math.sqrt(s),isNaN(this.boundingSphere.radius)&&Ut('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const t=this.index,e=this.attributes;if(t===null||e.position===void 0||e.normal===void 0||e.uv===void 0){Ut("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=e.position,s=e.normal,n=e.uv;let r=this.getAttribute("tangent");(r===void 0||r.count!==i.count)&&(r=new mt(new Float32Array(4*i.count),4),this.setAttribute("tangent",r));const a=[],o=[];for(let M=0;M<i.count;M++)a[M]=new S,o[M]=new S;const c=new S,h=new S,u=new S,l=new Y,d=new Y,y=new Y,m=new S,z=new S;function b(M,P,A){c.fromBufferAttribute(i,M),h.fromBufferAttribute(i,P),u.fromBufferAttribute(i,A),l.fromBufferAttribute(n,M),d.fromBufferAttribute(n,P),y.fromBufferAttribute(n,A),h.sub(c),u.sub(c),d.sub(l),y.sub(l);const C=1/(d.x*y.y-y.x*d.y);isFinite(C)&&(m.copy(h).multiplyScalar(y.y).addScaledVector(u,-d.y).multiplyScalar(C),z.copy(u).multiplyScalar(d.x).addScaledVector(h,-y.x).multiplyScalar(C),a[M].add(m),a[P].add(m),a[A].add(m),o[M].add(z),o[P].add(z),o[A].add(z))}let p=this.groups;p.length===0&&(p=[{start:0,count:t.count}]);for(let M=0,P=p.length;M<P;++M){const A=p[M],C=A.start,T=A.count;for(let E=C,I=C+T;E<I;E+=3)b(t.getX(E+0),t.getX(E+1),t.getX(E+2))}const x=new S,g=new S,w=new S,B=new S;function _(M){w.fromBufferAttribute(s,M),B.copy(w);const P=a[M];x.copy(P),x.sub(w.multiplyScalar(w.dot(P))).normalize(),g.crossVectors(B,P);const C=g.dot(o[M])<0?-1:1;r.setXYZW(M,x.x,x.y,x.z,C)}for(let M=0,P=p.length;M<P;++M){const A=p[M],C=A.start,T=A.count;for(let E=C,I=C+T;E<I;E+=3)_(t.getX(E+0)),_(t.getX(E+1)),_(t.getX(E+2))}this._transformed=!0}computeVertexNormals(){const t=this.index,e=this.getAttribute("position");if(e!==void 0){let i=this.getAttribute("normal");if(i===void 0||i.count!==e.count)i=new mt(new Float32Array(e.count*3),3),this.setAttribute("normal",i);else for(let l=0,d=i.count;l<d;l++)i.setXYZ(l,0,0,0);const s=new S,n=new S,r=new S,a=new S,o=new S,c=new S,h=new S,u=new S;if(t)for(let l=0,d=t.count;l<d;l+=3){const y=t.getX(l+0),m=t.getX(l+1),z=t.getX(l+2);s.fromBufferAttribute(e,y),n.fromBufferAttribute(e,m),r.fromBufferAttribute(e,z),h.subVectors(r,n),u.subVectors(s,n),h.cross(u),a.fromBufferAttribute(i,y),o.fromBufferAttribute(i,m),c.fromBufferAttribute(i,z),a.add(h),o.add(h),c.add(h),i.setXYZ(y,a.x,a.y,a.z),i.setXYZ(m,o.x,o.y,o.z),i.setXYZ(z,c.x,c.y,c.z)}else for(let l=0,d=e.count;l<d;l+=3)s.fromBufferAttribute(e,l+0),n.fromBufferAttribute(e,l+1),r.fromBufferAttribute(e,l+2),h.subVectors(r,n),u.subVectors(s,n),h.cross(u),i.setXYZ(l+0,h.x,h.y,h.z),i.setXYZ(l+1,h.x,h.y,h.z),i.setXYZ(l+2,h.x,h.y,h.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const t=this.attributes.normal;for(let e=0,i=t.count;e<i;e++)W.fromBufferAttribute(t,e),W.normalize(),t.setXYZ(e,W.x,W.y,W.z)}toNonIndexed(){function t(a,o){const c=a.array,h=a.itemSize,u=a.normalized,l=new c.constructor(o.length*h);let d=0,y=0;for(let m=0,z=o.length;m<z;m++){a.isInterleavedBufferAttribute?d=o[m]*a.data.stride+a.offset:d=o[m]*h;for(let b=0;b<h;b++)l[y++]=c[d++]}return new mt(l,h,u)}if(this.index===null)return yt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const e=new Ii,i=this.index.array,s=this.attributes;for(const a in s){const o=s[a],c=t(o,i);e.setAttribute(a,c)}const n=this.morphAttributes;for(const a in n){const o=[],c=n[a];for(let h=0,u=c.length;h<u;h++){const l=c[h],d=t(l,i);o.push(d)}e.morphAttributes[a]=o}e.morphTargetsRelative=this.morphTargetsRelative;const r=this.groups;for(let a=0,o=r.length;a<o;a++){const c=r[a];e.addGroup(c.start,c.count,c.materialIndex)}return e}toJSON(){const t={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,t.name=this.name,Object.keys(this.userData).length>0&&(t.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const o=this.parameters;for(const c in o)o[c]!==void 0&&(t[c]=o[c]);return t}t.data={attributes:{}};const e=this.index;e!==null&&(t.data.index={type:e.array.constructor.name,array:Array.prototype.slice.call(e.array)});const i=this.attributes;for(const o in i){const c=i[o];t.data.attributes[o]=c.toJSON(t.data)}const s={};let n=!1;for(const o in this.morphAttributes){const c=this.morphAttributes[o],h=[];for(let u=0,l=c.length;u<l;u++){const d=c[u];h.push(d.toJSON(t.data))}h.length>0&&(s[o]=h,n=!0)}n&&(t.data.morphAttributes=s,t.data.morphTargetsRelative=this.morphTargetsRelative);const r=this.groups;r.length>0&&(t.data.groups=JSON.parse(JSON.stringify(r)));const a=this.boundingSphere;return a!==null&&(t.data.boundingSphere=a.toJSON()),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const e={};this.name=t.name;const i=t.index;i!==null&&this.setIndex(i.clone());const s=t.attributes;for(const c in s){const h=s[c];this.setAttribute(c,h.clone(e))}const n=t.morphAttributes;for(const c in n){const h=[],u=n[c];for(let l=0,d=u.length;l<d;l++)h.push(u[l].clone(e));this.morphAttributes[c]=h}this.morphTargetsRelative=t.morphTargetsRelative;const r=t.groups;for(let c=0,h=r.length;c<h;c++){const u=r[c];this.addGroup(u.start,u.count,u.materialIndex)}const a=t.boundingBox;a!==null&&(this.boundingBox=a.clone());const o=t.boundingSphere;return o!==null&&(this.boundingSphere=o.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this._transformed=t._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Fi=new S,wn=new S,bn=new xt;class Ts{constructor(t=new S(1,0,0),e=0){this.isPlane=!0,this.normal=t,this.constant=e}set(t,e){return this.normal.copy(t),this.constant=e,this}setComponents(t,e,i,s){return this.normal.set(t,e,i),this.constant=s,this}setFromNormalAndCoplanarPoint(t,e){return this.normal.copy(t),this.constant=-e.dot(this.normal),this}setFromCoplanarPoints(t,e,i){const s=Fi.subVectors(i,e).cross(wn.subVectors(t,e)).normalize();return this.setFromNormalAndCoplanarPoint(s,t),this}copy(t){return this.normal.copy(t.normal),this.constant=t.constant,this}normalize(){const t=1/this.normal.length();return this.normal.multiplyScalar(t),this.constant*=t,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(t){return this.normal.dot(t)+this.constant}distanceToSphere(t){return this.distanceToPoint(t.center)-t.radius}projectPoint(t,e){return e.copy(t).addScaledVector(this.normal,-this.distanceToPoint(t))}intersectLine(t,e,i=!0){const s=t.delta(Fi),n=this.normal.dot(s);if(n===0)return this.distanceToPoint(t.start)===0?e.copy(t.start):null;const r=-(t.start.dot(this.normal)+this.constant)/n;return i===!0&&(r<0||r>1)?null:e.copy(t.start).addScaledVector(s,r)}intersectsLine(t){const e=this.distanceToPoint(t.start),i=this.distanceToPoint(t.end);return e<0&&i>0||i<0&&e>0}intersectsBox(t){return t.intersectsPlane(this)}intersectsSphere(t){return t.intersectsPlane(this)}coplanarPoint(t){return t.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(t,e){const i=e||bn.getNormalMatrix(t),s=this.coplanarPoint(Fi).applyMatrix4(t),n=this.normal.applyMatrix3(i).normalize();return this.constant=-s.dot(n),this}translate(t){return this.constant-=t.dot(this.normal),this}equals(t){return t.normal.equals(this.normal)&&t.constant===this.constant}clone(){return new this.constructor().copy(this)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(t){return this.normal.fromArray(t.normal),this.constant=t.constant,this}}const _t=new S,Vi=new S,Oe=new S,We=new S;class zn{constructor(t=new S,e=new S(0,0,-1)){this.origin=t,this.direction=e}set(t,e){return this.origin.copy(t),this.direction.copy(e),this}copy(t){return this.origin.copy(t.origin),this.direction.copy(t.direction),this}at(t,e){return e.copy(this.origin).addScaledVector(this.direction,t)}lookAt(t){return this.direction.copy(t).sub(this.origin).normalize(),this}recast(t){return this.origin.copy(this.at(t,_t)),this}closestPointToPoint(t,e){e.subVectors(t,this.origin);const i=e.dot(this.direction);return i<0?e.copy(this.origin):e.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(t){return Math.sqrt(this.distanceSqToPoint(t))}distanceSqToPoint(t){const e=_t.subVectors(t,this.origin).dot(this.direction);return e<0?this.origin.distanceToSquared(t):(_t.copy(this.origin).addScaledVector(this.direction,e),_t.distanceToSquared(t))}distanceSqToSegment(t,e,i,s){Vi.copy(t).add(e).multiplyScalar(.5),Oe.copy(e).sub(t).normalize(),We.copy(this.origin).sub(Vi);const n=t.distanceTo(e)*.5,r=-this.direction.dot(Oe),a=We.dot(this.direction),o=-We.dot(Oe),c=We.lengthSq(),h=Math.abs(1-r*r);let u,l,d,y;if(h>0)if(u=r*o-a,l=r*a-o,y=n*h,u>=0)if(l>=-y)if(l<=y){const m=1/h;u*=m,l*=m,d=u*(u+r*l+2*a)+l*(r*u+l+2*o)+c}else l=n,u=Math.max(0,-(r*l+a)),d=-u*u+l*(l+2*o)+c;else l=-n,u=Math.max(0,-(r*l+a)),d=-u*u+l*(l+2*o)+c;else l<=-y?(u=Math.max(0,-(-r*n+a)),l=u>0?-n:Math.min(Math.max(-n,-o),n),d=-u*u+l*(l+2*o)+c):l<=y?(u=0,l=Math.min(Math.max(-n,-o),n),d=l*(l+2*o)+c):(u=Math.max(0,-(r*n+a)),l=u>0?n:Math.min(Math.max(-n,-o),n),d=-u*u+l*(l+2*o)+c);else l=r>0?-n:n,u=Math.max(0,-(r*l+a)),d=-u*u+l*(l+2*o)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,u),s&&s.copy(Vi).addScaledVector(Oe,l),d}intersectSphere(t,e){if(t.radius<0)return null;_t.subVectors(t.center,this.origin);const i=_t.dot(this.direction),s=_t.dot(_t)-i*i,n=t.radius*t.radius;if(s>n)return null;const r=Math.sqrt(n-s),a=i-r,o=i+r;return o<0?null:a<0?this.at(o,e):this.at(a,e)}intersectsSphere(t){return t.radius<0?!1:this.distanceSqToPoint(t.center)<=t.radius*t.radius}distanceToPlane(t){const e=t.normal.dot(this.direction);if(e===0)return t.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(t.normal)+t.constant)/e;return i>=0?i:null}intersectPlane(t,e){const i=this.distanceToPlane(t);return i===null?null:this.at(i,e)}intersectsPlane(t){const e=t.distanceToPoint(this.origin);return e===0||t.normal.dot(this.direction)*e<0}intersectBox(t,e){let i,s,n,r,a,o;const c=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,l=this.origin;return c>=0?(i=(t.min.x-l.x)*c,s=(t.max.x-l.x)*c):(i=(t.max.x-l.x)*c,s=(t.min.x-l.x)*c),h>=0?(n=(t.min.y-l.y)*h,r=(t.max.y-l.y)*h):(n=(t.max.y-l.y)*h,r=(t.min.y-l.y)*h),i>r||n>s||((n>i||isNaN(i))&&(i=n),(r<s||isNaN(s))&&(s=r),u>=0?(a=(t.min.z-l.z)*u,o=(t.max.z-l.z)*u):(a=(t.max.z-l.z)*u,o=(t.min.z-l.z)*u),i>o||a>s)||((a>i||i!==i)&&(i=a),(o<s||s!==s)&&(s=o),s<0)?null:this.at(i>=0?i:s,e)}intersectsBox(t){return this.intersectBox(t,_t)!==null}intersectTriangle(t,e,i,s,n){const r=this.origin,a=this.direction,o=a.x,c=a.y,h=a.z,u=t.x-r.x,l=t.y-r.y,d=t.z-r.z,y=e.x-r.x,m=e.y-r.y,z=e.z-r.z,b=i.x-r.x,p=i.y-r.y,x=i.z-r.z,g=Math.abs(o),w=Math.abs(c),B=Math.abs(h);let _,M,P,A,C,T,E,I,F,R,Z,tt;if(g>=w&&g>=B?(P=o,T=u,F=y,tt=b,o>=0?(_=c,M=h,A=l,C=d,E=m,I=z,R=p,Z=x):(_=h,M=c,A=d,C=l,E=z,I=m,R=x,Z=p)):w>=B?(P=c,T=l,F=m,tt=p,c>=0?(_=h,M=o,A=d,C=u,E=z,I=y,R=x,Z=b):(_=o,M=h,A=u,C=d,E=y,I=z,R=b,Z=x)):(P=h,T=d,F=z,tt=x,h>=0?(_=o,M=c,A=u,C=l,E=y,I=m,R=b,Z=p):(_=c,M=o,A=l,C=u,E=m,I=y,R=p,Z=b)),P===0)return null;const dt=_/P,at=M/P,pt=1/P,ye=A-dt*T,Ie=C-at*T,ys=E-dt*F,Tt=I-at*F,fi=R-dt*tt,di=Z-at*tt,Wt=fi*Tt-di*ys,Xt=ye*di-Ie*fi,Yt=ys*Ie-Tt*ye;if(s){if(Wt<0||Xt<0||Yt<0)return null}else if((Wt<0||Xt<0||Yt<0)&&(Wt>0||Xt>0||Yt>0))return null;const Fe=Wt+Xt+Yt;if(Fe===0)return null;const Ht=pt*(Wt*T+Xt*F+Yt*tt);return(Fe>0?Ht<0:Ht>0)?null:this.at(Ht/Fe,n)}applyMatrix4(t){return this.origin.applyMatrix4(t),this.direction.transformDirection(t),this}equals(t){return t.origin.equals(this.origin)&&t.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}}const ds=class ds{constructor(t,e,i,s){this.elements=[1,0,0,1],t!==void 0&&this.set(t,e,i,s)}identity(){return this.set(1,0,0,1),this}fromArray(t,e=0){for(let i=0;i<4;i++)this.elements[i]=t[i+e];return this}set(t,e,i,s){const n=this.elements;return n[0]=t,n[2]=e,n[1]=i,n[3]=s,this}};ds.prototype.isMatrix2=!0;let Ps=ds;const Cs=new S,Xe=new S,se=new S,ne=new S,Ri=new S,_n=new S,Mn=new S;class Mt{constructor(t=new S,e=new S){this.start=t,this.end=e}set(t,e){return this.start.copy(t),this.end.copy(e),this}copy(t){return this.start.copy(t.start),this.end.copy(t.end),this}getCenter(t){return t.addVectors(this.start,this.end).multiplyScalar(.5)}delta(t){return t.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(t,e){return this.delta(e).multiplyScalar(t).add(this.start)}closestPointToPointParameter(t,e){Cs.subVectors(t,this.start),Xe.subVectors(this.end,this.start);const i=Xe.dot(Xe);if(i===0)return 0;let n=Xe.dot(Cs)/i;return e&&(n=V(n,0,1)),n}closestPointToPoint(t,e,i){const s=this.closestPointToPointParameter(t,e);return this.delta(i).multiplyScalar(s).add(this.start)}distanceSqToLine3(t,e=_n,i=Mn){const s=10000000000000001e-32;let n,r;const a=this.start,o=t.start,c=this.end,h=t.end;se.subVectors(c,a),ne.subVectors(h,o),Ri.subVectors(a,o);const u=se.dot(se),l=ne.dot(ne),d=ne.dot(Ri);if(u<=s&&l<=s)return e.copy(a),i.copy(o),e.sub(i),e.dot(e);if(u<=s)n=0,r=d/l,r=V(r,0,1);else{const y=se.dot(Ri);if(l<=s)r=0,n=V(-y/u,0,1);else{const m=se.dot(ne),z=u*l-m*m;z!==0?n=V((m*d-y*l)/z,0,1):n=0,r=(m*n+d)/l,r<0?(r=0,n=V(-y/u,0,1)):r>1&&(r=1,n=V((m-y)/u,0,1))}}return e.copy(a).addScaledVector(se,n),i.copy(o).addScaledVector(ne,r),e.distanceToSquared(i)}applyMatrix4(t){return this.start.applyMatrix4(t),this.end.applyMatrix4(t),this}equals(t){return t.start.equals(this.start)&&t.end.equals(this.end)}clone(){return new this.constructor().copy(this)}}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"186"}})),typeof window<"u"&&(window.__THREE__?yt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="186");new xt().set(-1,0,0,0,1,0,0,0,1),new xt().set(-1,0,0,0,1,0,0,0,1);const Es=0,An=1,Sn=2,Is=2,ki=1.25,Fs=1,J=32,q=J/4,Vs=65535,Ye=Math.pow(2,-24),Ui=Symbol("SKIP_GENERATION"),Rs={strategy:Es,maxDepth:40,targetLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Ui]:!1};function U(f,t,e){return e.min.x=t[f],e.min.y=t[f+1],e.min.z=t[f+2],e.max.x=t[f+3],e.max.y=t[f+4],e.max.z=t[f+5],e}function Ni(f){let t=-1,e=-1/0;for(let i=0;i<3;i++){const s=f[i+3]-f[i];s>e&&(e=s,t=i)}return t}function ks(f,t){t.set(f)}function Us(f,t,e){let i,s;for(let n=0;n<3;n++){const r=n+3;i=f[n],s=t[n],e[n]=i<s?i:s,i=f[r],s=t[r],e[r]=i>s?i:s}}function He(f,t,e){for(let i=0;i<3;i++){const s=t[f+2*i],n=t[f+2*i+1],r=s-n,a=s+n;r<e[i]&&(e[i]=r),a>e[i+3]&&(e[i+3]=a)}}function _e(f){const t=f[3]-f[0],e=f[4]-f[1],i=f[5]-f[2];return 2*(t*e+e*i+i*t)}function N(f,t){return t[f+15]===Vs}function X(f,t){return t[f+6]}function G(f,t){return t[f+14]}function v(f){return f+q}function O(f,t){const e=t[f+6];return f+e*q}function Li(f,t){return t[f+7]}function Wr(f){return f}function Di(f,t,e,i,s){let n=1/0,r=1/0,a=1/0,o=-1/0,c=-1/0,h=-1/0,u=1/0,l=1/0,d=1/0,y=-1/0,m=-1/0,z=-1/0;const b=f.offset||0;for(let p=(t-b)*6,x=(t+e-b)*6;p<x;p+=6){const g=f[p+0],w=f[p+1],B=g-w,_=g+w;B<n&&(n=B),_>o&&(o=_),g<u&&(u=g),g>y&&(y=g);const M=f[p+2],P=f[p+3],A=M-P,C=M+P;A<r&&(r=A),C>c&&(c=C),M<l&&(l=M),M>m&&(m=M);const T=f[p+4],E=f[p+5],I=T-E,F=T+E;I<a&&(a=I),F>h&&(h=F),T<d&&(d=T),T>z&&(z=T)}i[0]=n,i[1]=r,i[2]=a,i[3]=o,i[4]=c,i[5]=h,s[0]=u,s[1]=l,s[2]=d,s[3]=y,s[4]=m,s[5]=z}const At=32,Bn=(f,t)=>f.candidate-t.candidate,Ft=new Array(At).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Ze=new Float32Array(6);function Tn(f,t,e,i,s,n){let r=-1,a=0;if(n===Es)r=Ni(t),r!==-1&&(a=(t[r]+t[r+3])/2);else if(n===An)r=Ni(f),r!==-1&&(a=Pn(e,i,s,r));else if(n===Sn){const o=_e(f);let c=ki*s;const h=e.offset||0,u=(i-h)*6,l=(i+s-h)*6;for(let d=0;d<3;d++){const y=t[d],b=(t[d+3]-y)/At;if(s<At/4){const p=[...Ft];p.length=s;let x=0;for(let w=u;w<l;w+=6,x++){const B=p[x];B.candidate=e[w+2*d],B.count=0;const{bounds:_,leftCacheBounds:M,rightCacheBounds:P}=B;for(let A=0;A<3;A++)P[A]=1/0,P[A+3]=-1/0,M[A]=1/0,M[A+3]=-1/0,_[A]=1/0,_[A+3]=-1/0;He(w,e,_)}p.sort(Bn);let g=s;for(let w=0;w<g;w++){const B=p[w];for(;w+1<g&&p[w+1].candidate===B.candidate;)p.splice(w+1,1),g--}for(let w=u;w<l;w+=6){const B=e[w+2*d];for(let _=0;_<g;_++){const M=p[_];B>=M.candidate?He(w,e,M.rightCacheBounds):(He(w,e,M.leftCacheBounds),M.count++)}}for(let w=0;w<g;w++){const B=p[w],_=B.count,M=s-B.count,P=B.leftCacheBounds,A=B.rightCacheBounds;let C=0;_!==0&&(C=_e(P)/o);let T=0;M!==0&&(T=_e(A)/o);const E=Fs+ki*(C*_+T*M);E<c&&(r=d,c=E,a=B.candidate)}}else{for(let g=0;g<At;g++){const w=Ft[g];w.count=0,w.candidate=y+b+g*b;const B=w.bounds;for(let _=0;_<3;_++)B[_]=1/0,B[_+3]=-1/0}for(let g=u;g<l;g+=6){let _=~~((e[g+2*d]-y)/b);_>=At&&(_=At-1);const M=Ft[_];M.count++,He(g,e,M.bounds)}const p=Ft[At-1];ks(p.bounds,p.rightCacheBounds);for(let g=At-2;g>=0;g--){const w=Ft[g],B=Ft[g+1];Us(w.bounds,B.rightCacheBounds,w.rightCacheBounds)}let x=0;for(let g=0;g<At-1;g++){const w=Ft[g],B=w.count,_=w.bounds,P=Ft[g+1].rightCacheBounds;B!==0&&(x===0?ks(_,Ze):Us(_,Ze,Ze)),x+=B;let A=0,C=0;x!==0&&(A=_e(Ze)/o);const T=s-x;T!==0&&(C=_e(P)/o);const E=Fs+ki*(A*x+C*T);E<c&&(r=d,c=E,a=w.candidate)}}}}else console.warn(\`BVH: Invalid build strategy value \${n} used.\`);return{axis:r,pos:a}}function Pn(f,t,e,i){let s=0;const n=f.offset;for(let r=t,a=t+e;r<a;r++)s+=f[(r-n)*6+i*2];return s/e}class qi{constructor(){this.boundingData=new Float32Array(6)}}function Cn(f,t,e,i,s,n){let r=i,a=i+s-1;const o=n.pos,c=n.axis*2,h=e.offset||0;for(;;){for(;r<=a&&e[(r-h)*6+c]<o;)r++;for(;r<=a&&e[(a-h)*6+c]>=o;)a--;if(r<a){for(let u=0;u<t;u++){let l=f[r*t+u];f[r*t+u]=f[a*t+u],f[a*t+u]=l}for(let u=0;u<6;u++){const l=r-h,d=a-h,y=e[l*6+u];e[l*6+u]=e[d*6+u],e[d*6+u]=y}r++,a--}else return r}}let Ns,$e,vi,Ls;const En=Math.pow(2,32);function Oi(f){return"count"in f?1:1+Oi(f.left)+Oi(f.right)}function In(f,t,e){return Ns=new Float32Array(e),$e=new Uint32Array(e),vi=new Uint16Array(e),Ls=new Uint8Array(e),Wi(f,t)}function Wi(f,t){const e=f/4,i=f/2,s="count"in t,n=t.boundingData;for(let r=0;r<6;r++)Ns[e+r]=n[r];if(s)return t.buffer?(Ls.set(new Uint8Array(t.buffer),f),f+t.buffer.byteLength):($e[e+6]=t.offset,vi[i+14]=t.count,vi[i+15]=Vs,f+J);{const{left:r,right:a,splitAxis:o}=t,c=f+J;let h=Wi(c,r);const u=f/J,d=h/J-u;if(d>En)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return $e[e+6]=d,$e[e+7]=o,Wi(h,a)}}function Fn(f,t,e,i,s,n){const{maxDepth:r,verbose:a,targetLeafSize:o,_strictLeafSize:c=1/0,strategy:h,onProgress:u}=s,l=f.primitiveBuffer,d=f.primitiveBufferStride,y=new Float32Array(6);let m=!1;const z=new qi;return Di(t,e,i,z.boundingData,y),p(z,e,i,y),z;function b(x){u&&u((x-n.offset)/n.count)}function p(x,g,w,B=null,_=0){!m&&_>=r&&(m=!0,a&&console.warn(\`BVH: Max depth of \${r} reached when generating BVH. Consider increasing maxDepth.\`));const M=w>c;if(w<=o&&!M||_>=r)return b(g+w),x.offset=g,x.count=w,x;const P=Tn(x.boundingData,B,t,g,w,h);let A=P.axis===-1?-1:Cn(l,d,t,g,w,P);if(P.axis===-1||A===g||A===g+w){if(!M)return b(g+w),x.offset=g,x.count=w,x;P.axis=Math.max(0,Ni(x.boundingData)),A=g+Math.max(1,Math.floor(w/2))}x.splitAxis=P.axis;const C=new qi,T=g,E=A-g;x.left=C,Di(t,T,E,C.boundingData,y),p(C,T,E,y,_+1);const I=new qi,F=A,R=w-E;return x.right=I,Di(t,F,R,I.boundingData,y),p(I,F,R,y,_+1),x}}function Vn(f,t){const e=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=f.getRootRanges(t.range),s=i[0],n=i[i.length-1],r={offset:s.offset,count:n.offset+n.count-s.offset},a=new Float32Array(6*r.count);a.offset=r.offset,f.computePrimitiveBounds(r.offset,r.count,a),f._roots=i.map(o=>{const c=Fn(f,a,o.offset,o.count,t,r),h=Oi(c),u=new e(J*h);return In(0,c,u),u})}class Xi{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return t.length===0?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class Rn{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,t.length!==0&&this.setBuffer(t.pop())}}}const k=new Rn;let Vt,re;const oe=[],Je=new Xi(()=>new Q);function kn(f,t,e,i,s,n){Vt=Je.getPrimitive(),re=Je.getPrimitive(),oe.push(Vt,re),k.setBuffer(f._roots[t]);const r=Yi(0,f.geometry,e,i,s,n);k.clearBuffer(),Je.releasePrimitive(Vt),Je.releasePrimitive(re),oe.pop(),oe.pop();const a=oe.length;return a>0&&(re=oe[a-1],Vt=oe[a-2]),r}function Yi(f,t,e,i,s=null,n=0,r=0){const{float32Array:a,uint16Array:o,uint32Array:c}=k;let h=f*2;if(N(h,o)){const l=X(f,c),d=G(h,o);return U(f,a,Vt),i(l,d,!1,r,n+f/q,Vt)}else{let A=function(T){const{uint16Array:E,uint32Array:I}=k;let F=T*2;for(;!N(F,E);)T=v(T),F=T*2;return X(T,I)},C=function(T){const{uint16Array:E,uint32Array:I}=k;let F=T*2;for(;!N(F,E);)T=O(T,I),F=T*2;return X(T,I)+G(F,E)};const l=v(f),d=O(f,c);let y=l,m=d,z,b,p,x;if(s&&(p=Vt,x=re,U(y,a,p),U(m,a,x),z=s(p),b=s(x),b<z)){y=d,m=l;const T=z;z=b,b=T,p=x}p||(p=Vt,U(y,a,p));const g=N(y*2,o),w=e(p,g,z,r+1,n+y/q);let B;if(w===Is){const T=A(y),I=C(y)-T;B=i(T,I,!0,r+1,n+y/q,p)}else B=w&&Yi(y,t,e,i,s,n,r+1);if(B)return!0;x=re,U(m,a,x);const _=N(m*2,o),M=e(x,_,b,r+1,n+m/q);let P;if(M===Is){const T=A(m),I=C(m)-T;P=i(T,I,!0,r+1,n+m/q,x)}else P=M&&Yi(m,t,e,i,s,n,r+1);return!!P}}const Me=new k.constructor,Ge=new k.constructor,Rt=new Xi(()=>new Q),ae=new Q,ce=new Q,Hi=new Q,Zi=new Q;let $i=!1;function Un(f,t,e,i){if($i)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");$i=!0;const s=f._roots,n=t._roots;let r,a=0,o=0;const c=new H().copy(e).invert();for(let h=0,u=s.length;h<u;h++){Me.setBuffer(s[h]),o=0;const l=Rt.getPrimitive();U(0,Me.float32Array,l),l.applyMatrix4(c);for(let d=0,y=n.length;d<y&&(Ge.setBuffer(n[d]),r=ut(0,0,e,c,i,a,o,0,0,l),Ge.clearBuffer(),o+=n[d].byteLength/J,!r);d++);if(Rt.releasePrimitive(l),Me.clearBuffer(),a+=s[h].byteLength/J,r)break}return $i=!1,r}function ut(f,t,e,i,s,n=0,r=0,a=0,o=0,c=null,h=!1){let u,l;h?(u=Ge,l=Me):(u=Me,l=Ge);const d=u.float32Array,y=u.uint32Array,m=u.uint16Array,z=l.float32Array,b=l.uint32Array,p=l.uint16Array,x=f*2,g=t*2,w=N(x,m),B=N(g,p);let _=!1;if(B&&w)h?_=s(X(t,b),G(t*2,p),X(f,y),G(f*2,m),o,r+t/q,a,n+f/q):_=s(X(f,y),G(f*2,m),X(t,b),G(t*2,p),a,n+f/q,o,r+t/q);else if(B){const M=Rt.getPrimitive();U(t,z,M),M.applyMatrix4(e);const P=v(f),A=O(f,y);U(P,d,ae),U(A,d,ce);const C=M.intersectsBox(ae),T=M.intersectsBox(ce);_=C&&ut(t,P,i,e,s,r,n,o,a+1,M,!h)||T&&ut(t,A,i,e,s,r,n,o,a+1,M,!h),Rt.releasePrimitive(M)}else{const M=v(t),P=O(t,b);U(M,z,Hi),U(P,z,Zi);const A=c.intersectsBox(Hi),C=c.intersectsBox(Zi);if(A&&C)_=ut(f,M,e,i,s,n,r,a,o+1,c,h)||ut(f,P,e,i,s,n,r,a,o+1,c,h);else if(A)if(w)_=ut(f,M,e,i,s,n,r,a,o+1,c,h);else{const T=Rt.getPrimitive();T.copy(Hi).applyMatrix4(e);const E=v(f),I=O(f,y);U(E,d,ae),U(I,d,ce);const F=T.intersectsBox(ae),R=T.intersectsBox(ce);_=F&&ut(M,E,i,e,s,r,n,o,a+1,T,!h)||R&&ut(M,I,i,e,s,r,n,o,a+1,T,!h),Rt.releasePrimitive(T)}else if(C)if(w)_=ut(f,P,e,i,s,n,r,a,o+1,c,h);else{const T=Rt.getPrimitive();T.copy(Zi).applyMatrix4(e);const E=v(f),I=O(f,y);U(E,d,ae),U(I,d,ce);const F=T.intersectsBox(ae),R=T.intersectsBox(ce);_=F&&ut(P,E,i,e,s,r,n,o,a+1,T,!h)||R&&ut(P,I,i,e,s,r,n,o,a+1,T,!h),Rt.releasePrimitive(T)}}return _}const Ji=new class{constructor(){let f=null,t=null,e=null,i=!1;this.root=null,this.buffer=null,this.uint32Array=null,this.uint16Array=null,this.setBVH=(n,r)=>{if(i)throw new Error("BVHTraversalHelper: cannot call setBVH during an active traversal.");this.root=r,this.buffer=f=n._roots[r],this.uint16Array=e=new Uint16Array(f),this.uint32Array=t=new Uint32Array(f)},this.reset=()=>{this.root=null,this.buffer=f=null,this.uint16Array=e=null,this.uint32Array=t=null},this.getRangeStart=n=>{let r=n*2;for(;!N(r,e);)n=v(n),r=n*2;return X(n,t)},this.getRangeEnd=n=>{let r=n*2;for(;!N(r,e);)n=O(n,t),r=n*2;return X(n,t)+G(r,e)};const s=(n,r,a)=>{const o=r*2,c=N(o,e);if(!n(a,c,r)&&!c){const u=v(r),l=O(r,t);s(n,u,a+1),s(n,l,a+1)}};this.traverseBuffer=n=>{if(i)throw new Error("BVHTraversalHelper: cannot start a traversal during an active traversal.");i=!0;try{s(n,0,0)}finally{i=!1}},this.traverse=n=>{this.traverseBuffer((r,a,o)=>{if(a){const c=o*2,h=t[o+6],u=e[c+14];return n(r,a,new Float32Array(f,o*4,6),h,u)}else{const c=Li(o,t);return n(r,a,new Float32Array(f,o*4,6),c)}})}}},Ds=new Q,he=new Float32Array(6);class Nn{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){t={...Rs,...t},"maxLeafSize"in t&&(console.warn('BVH: "maxLeafSize" option has been deprecated. Use "targetLeafSize", instead.'),t={...t,targetLeafSize:t.maxLeafSize}),Vn(this,t)}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,s){let n=1/0,r=1/0,a=1/0,o=-1/0,c=-1/0,h=-1/0;for(let u=t,l=t+e;u<l;u++){this.writePrimitiveBounds(u,he,0);const[d,y,m,z,b,p]=he;d<n&&(n=d),z>o&&(o=z),y<r&&(r=y),b>c&&(c=b),m<a&&(a=m),p>h&&(h=p)}return i[s+0]=n,i[s+1]=r,i[s+2]=a,i[s+3]=o,i[s+4]=c,i[s+5]=h,i}computePrimitiveBounds(t,e,i){const s=i.offset||0;for(let n=t,r=t+e;n<r;n++){this.writePrimitiveBounds(n,he,0);const[a,o,c,h,u,l]=he,d=(a+h)/2,y=(o+u)/2,m=(c+l)/2,z=(h-a)/2,b=(u-o)/2,p=(l-c)/2,x=(n-s)*6;i[x+0]=d,i[x+1]=z+(Math.abs(d)+z)*Ye,i[x+2]=y,i[x+3]=b+(Math.abs(y)+b)*Ye,i[x+4]=m,i[x+5]=p+(Math.abs(m)+p)*Ye}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,s=e.length;i<s;i++)e[i]+=t;else{const i=this._roots;for(let s=0;s<i.length;s++){const n=i[s],r=new Uint32Array(n),a=new Uint16Array(n),o=n.byteLength/J;for(let c=0;c<o;c++){const h=q*c,u=2*h;N(u,a)&&(r[h+6]+=t)}}}}traverse(t,e=0){Ji.setBVH(this,e),Ji.traverse(t),Ji.reset()}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const s=t[e],n=new Uint32Array(s),r=new Uint16Array(s),a=new Float32Array(s),o=s.byteLength/J;for(let c=o-1;c>=0;c--){const h=c*q,u=h*2;if(N(u,r)){const d=X(h,n),y=G(u,r);this.writePrimitiveRangeBounds(d,y,he,0),a.set(he,h)}else{const d=v(h),y=O(h,n);for(let m=0;m<3;m++){const z=a[d+m],b=a[d+m+3],p=a[y+m],x=a[y+m+3];a[h+m]=z<p?z:p,a[h+m+3]=b>x?b:x}}}}}getBoundingBox(t){return t.makeEmpty(),this._roots.forEach(i=>{U(0,new Float32Array(i),Ds),t.union(Ds)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:s,intersectsPrimitive:n,scratchPrimitive:r,iterate:a}=t;if(s&&n){const u=s;s=(l,d,y,m,z)=>u(l,d,y,m,z)?!0:a(l,d,this,n,y,m,r)}else s||(n?s=(u,l,d,y)=>a(u,l,this,n,d,y,r):s=(u,l,d)=>d);let o=!1,c=0;const h=this._roots;for(let u=0,l=h.length;u<l;u++){const d=h[u];if(o=kn(this,u,i,s,e,c),o)break;c+=d.byteLength/J}return o}bvhcast(t,e,i){let{intersectsRanges:s}=i;return Un(this,t,e,s)}}function Ln(){return typeof SharedArrayBuffer<"u"}function Gi(f){return f.index?f.index.count:f.attributes.position.count}function Qe(f){return Gi(f)/3}function Dn(f,t=ArrayBuffer){return f>65535?new Uint32Array(new t(4*f)):new Uint16Array(new t(2*f))}function qn(f,t){if(!f.index){const e=f.attributes.position.count,i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=Dn(e,i);f.setIndex(new mt(s,1));for(let n=0;n<e;n++)s[n]=n}}function vn(f,t,e){const i=Gi(f)/e,s=t||f.drawRange,n=s.start/e,r=(s.start+s.count)/e,a=Math.max(0,n),o=Math.min(i,r)-a;return{offset:Math.floor(a),count:Math.floor(o)}}function On(f,t){return f.groups.map(e=>({offset:e.start/t,count:e.count/t}))}function qs(f,t,e){const i=vn(f,t,e),s=On(f,e);if(!s.length)return[i];const n=[],r=i.offset,a=i.offset+i.count,o=Gi(f)/e,c=[];for(const l of s){const{offset:d,count:y}=l,m=d,z=isFinite(y)?y:o-d,b=d+z;m<a&&b>r&&(c.push({pos:Math.max(r,m),isStart:!0}),c.push({pos:Math.min(a,b),isStart:!1}))}c.sort((l,d)=>l.pos!==d.pos?l.pos-d.pos:l.type==="end"?-1:1);let h=0,u=null;for(const l of c){const d=l.pos;h!==0&&d!==u&&n.push({offset:u,count:d-u}),h+=l.isStart?1:-1,u=d}return n}function Wn(f,t){const e=f[f.length-1],i=e.offset+e.count>2**16,s=f.reduce((c,h)=>c+h.count,0),n=i?4:2,r=t?new SharedArrayBuffer(s*n):new ArrayBuffer(s*n),a=i?new Uint32Array(r):new Uint16Array(r);let o=0;for(let c=0;c<f.length;c++){const{offset:h,count:u}=f[c];for(let l=0;l<u;l++)a[o+l]=h+l;o+=u}return a}class Xn extends Nn{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(t.isBufferGeometry){if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("BVH: Only BufferGeometries are supported.");if(e.useSharedArrayBuffer&&!Ln())throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?i=>this._indirectBuffer[i]:i=>i,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,e={...Rs,...e},e[Ui]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const s=qs(e,t.range,i),n=Wn(s,t.useSharedArrayBuffer);this._indirectBuffer=n}else qn(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new Q))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:qs(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class St{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,s=-1/0;for(let n=0,r=t.length;n<r;n++){const o=t[n][e];i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}setFromPoints(t,e){let i=1/0,s=-1/0;for(let n=0,r=e.length;n<r;n++){const a=e[n],o=t.dot(a);i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}isSeparated(t){return this.min>t.max||t.min>this.max}}St.prototype.setFromBox=(function(){const f=new S;return function(e,i){const s=i.min,n=i.max;let r=1/0,a=-1/0;for(let o=0;o<=1;o++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){f.x=s.x*o+n.x*(1-o),f.y=s.y*c+n.y*(1-c),f.z=s.z*h+n.z*(1-h);const u=e.dot(f);r=Math.min(u,r),a=Math.max(u,a)}this.min=r,this.max=a}})();const Yn=(function(){const f=new S,t=new S,e=new S;return function(s,n,r){const a=s.start,o=f,c=n.start,h=t;e.subVectors(a,c),f.subVectors(s.end,s.start),t.subVectors(n.end,n.start);const u=e.dot(h),l=h.dot(o),d=h.dot(h),y=e.dot(o),z=o.dot(o)*d-l*l;let b,p;z!==0?b=(u*l-y*d)/z:b=0,p=(u+b*l)/d,r.x=b,r.y=p}})(),Qi=(function(){const f=new Y,t=new S,e=new S;return function(s,n,r,a){Yn(s,n,f);let o=f.x,c=f.y;if(o>=0&&o<=1&&c>=0&&c<=1){s.at(o,r),n.at(c,a);return}else if(o>=0&&o<=1){c<0?n.at(0,a):n.at(1,a),s.closestPointToPoint(a,!0,r);return}else if(c>=0&&c<=1){o<0?s.at(0,r):s.at(1,r),n.closestPointToPoint(r,!0,a);return}else{let h;o<0?h=s.start:h=s.end;let u;c<0?u=n.start:u=n.end;const l=t,d=e;if(s.closestPointToPoint(u,!0,t),n.closestPointToPoint(h,!0,e),l.distanceToSquared(u)<=d.distanceToSquared(h)){r.copy(l),a.copy(u);return}else{r.copy(h),a.copy(d);return}}}})(),Hn=(function(){const f=new S,t=new S,e=new Ts,i=new Mt;return function(n,r){const{radius:a,center:o}=n,{a:c,b:h,c:u}=r;if(i.start=c,i.end=h,i.closestPointToPoint(o,!0,f).distanceTo(o)<=a||(i.start=c,i.end=u,i.closestPointToPoint(o,!0,f).distanceTo(o)<=a)||(i.start=h,i.end=u,i.closestPointToPoint(o,!0,f).distanceTo(o)<=a))return!0;const m=r.getPlane(e);if(Math.abs(m.distanceToPoint(o))<=a){const b=m.projectPoint(o,t);if(r.containsPoint(b))return!0}return!1}})(),Zn=["x","y","z"],Bt=1e-15,vs=Bt*Bt;function rt(f){return Math.abs(f)<Bt}class ft extends st{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new S),this.satBounds=new Array(4).fill().map(()=>new St),this.points=[this.a,this.b,this.c],this.plane=new Ts,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new Mt,this.needsUpdate=!0}intersectsSphere(t){return Hn(t,this)}update(){const t=this.a,e=this.b,i=this.c,s=this.points,n=this.satAxes,r=this.satBounds,a=n[0],o=r[0];this.getNormal(a),o.setFromPoints(a,s);const c=n[1],h=r[1];c.subVectors(t,e),h.setFromPoints(c,s);const u=n[2],l=r[2];u.subVectors(e,i),l.setFromPoints(u,s);const d=n[3],y=r[3];d.subVectors(i,t),y.setFromPoints(d,s);const m=c.length(),z=u.length(),b=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<Bt?z<Bt||b<Bt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):z<Bt?b<Bt?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):b<Bt&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(a,t),this.needsUpdate=!1}}ft.prototype.closestPointToSegment=(function(){const f=new S,t=new S,e=new Mt;return function(s,n=null,r=null){const{start:a,end:o}=s,c=this.points;let h,u=1/0;for(let l=0;l<3;l++){const d=(l+1)%3;e.start.copy(c[l]),e.end.copy(c[d]),Qi(e,s,f,t),h=f.distanceToSquared(t),h<u&&(u=h,n&&n.copy(f),r&&r.copy(t))}return this.closestPointToPoint(a,f),h=a.distanceToSquared(f),h<u&&(u=h,n&&n.copy(f),r&&r.copy(a)),this.closestPointToPoint(o,f),h=o.distanceToSquared(f),h<u&&(u=h,n&&n.copy(f),r&&r.copy(o)),Math.sqrt(u)}})(),ft.prototype.intersectsTriangle=(function(){const f=new ft,t=new St,e=new St,i=new S,s=new S,n=new S,r=new S,a=new Mt,o=new Mt,c=new S,h=new Y,u=new Y;function l(x,g,w,B){const _=i;!x.isDegenerateIntoPoint&&!x.isDegenerateIntoSegment?_.copy(x.plane.normal):_.copy(g.plane.normal);const M=x.satBounds,P=x.satAxes;for(let T=1;T<4;T++){const E=M[T],I=P[T];if(t.setFromPoints(I,g.points),E.isSeparated(t)||(r.copy(_).cross(I),t.setFromPoints(r,x.points),e.setFromPoints(r,g.points),t.isSeparated(e)))return!1}const A=g.satBounds,C=g.satAxes;for(let T=1;T<4;T++){const E=A[T],I=C[T];if(t.setFromPoints(I,x.points),E.isSeparated(t)||(r.crossVectors(_,I),t.setFromPoints(r,x.points),e.setFromPoints(r,g.points),t.isSeparated(e)))return!1}return w&&(B||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),w.start.set(0,0,0),w.end.set(0,0,0)),!0}function d(x,g,w,B,_,M,P,A,C,T,E){let I=P/(P-A);T.x=B+(_-B)*I,E.start.subVectors(g,x).multiplyScalar(I).add(x),I=P/(P-C),T.y=B+(M-B)*I,E.end.subVectors(w,x).multiplyScalar(I).add(x)}function y(x,g,w,B,_,M,P,A,C,T,E){if(_>0)d(x.c,x.a,x.b,B,g,w,C,P,A,T,E);else if(M>0)d(x.b,x.a,x.c,w,g,B,A,P,C,T,E);else if(A*C>0||P!=0)d(x.a,x.b,x.c,g,w,B,P,A,C,T,E);else if(A!=0)d(x.b,x.a,x.c,w,g,B,A,P,C,T,E);else if(C!=0)d(x.c,x.a,x.b,B,g,w,C,P,A,T,E);else return!0;return!1}function m(x,g,w,B){const _=g.degenerateSegment,M=x.plane.distanceToPoint(_.start),P=x.plane.distanceToPoint(_.end);return rt(M)?rt(P)?l(x,g,w,B):(w&&(w.start.copy(_.start),w.end.copy(_.start)),x.containsPoint(_.start)):rt(P)?(w&&(w.start.copy(_.end),w.end.copy(_.end)),x.containsPoint(_.end)):x.plane.intersectLine(_,i)!=null?(w&&(w.start.copy(i),w.end.copy(i)),x.containsPoint(i)):!1}function z(x,g,w){const B=g.a;return rt(x.plane.distanceToPoint(B))&&x.containsPoint(B)?(w&&(w.start.copy(B),w.end.copy(B)),!0):!1}function b(x,g,w){const B=x.degenerateSegment,_=g.a;return B.closestPointToPoint(_,!0,i),_.distanceToSquared(i)<vs?(w&&(w.start.copy(_),w.end.copy(_)),!0):!1}function p(x,g,w,B){if(x.isDegenerateIntoSegment)if(g.isDegenerateIntoSegment){const _=x.degenerateSegment,M=g.degenerateSegment,P=s,A=n;_.delta(P),M.delta(A);const C=i.subVectors(M.start,_.start),T=P.x*A.y-P.y*A.x;if(rt(T))return!1;const E=(C.x*A.y-C.y*A.x)/T,I=-(P.x*C.y-P.y*C.x)/T;if(E<0||E>1||I<0||I>1)return!1;const F=_.start.z+P.z*E,R=M.start.z+A.z*I;return rt(F-R)?(w&&(w.start.copy(_.start).addScaledVector(P,E),w.end.copy(_.start).addScaledVector(P,E)),!0):!1}else return g.isDegenerateIntoPoint?b(x,g,w):m(g,x,w,B);else{if(x.isDegenerateIntoPoint)return g.isDegenerateIntoPoint?g.a.distanceToSquared(x.a)<vs?(w&&(w.start.copy(x.a),w.end.copy(x.a)),!0):!1:g.isDegenerateIntoSegment?b(g,x,w):z(g,x,w);if(g.isDegenerateIntoPoint)return z(x,g,w);if(g.isDegenerateIntoSegment)return m(x,g,w,B)}}return function(g,w=null,B=!1){this.needsUpdate&&this.update(),g.isExtendedTriangle?g.needsUpdate&&g.update():(f.copy(g),f.update(),g=f);const _=p(this,g,w,B);if(_!==void 0)return _;const M=this.plane,P=g.plane;let A=P.distanceToPoint(this.a),C=P.distanceToPoint(this.b),T=P.distanceToPoint(this.c);rt(A)&&(A=0),rt(C)&&(C=0),rt(T)&&(T=0);const E=A*C,I=A*T;if(E>0&&I>0)return!1;let F=M.distanceToPoint(g.a),R=M.distanceToPoint(g.b),Z=M.distanceToPoint(g.c);rt(F)&&(F=0),rt(R)&&(R=0),rt(Z)&&(Z=0);const tt=F*R,dt=F*Z;if(tt>0&&dt>0)return!1;s.copy(M.normal),n.copy(P.normal);const at=s.cross(n);let pt=0,ye=Math.abs(at.x);const Ie=Math.abs(at.y);Ie>ye&&(ye=Ie,pt=1),Math.abs(at.z)>ye&&(pt=2);const Tt=Zn[pt],fi=this.a[Tt],di=this.b[Tt],Wt=this.c[Tt],Xt=g.a[Tt],Yt=g.b[Tt],Fe=g.c[Tt];if(y(this,fi,di,Wt,E,I,A,C,T,h,a))return l(this,g,w,B);if(y(g,Xt,Yt,Fe,tt,dt,F,R,Z,u,o))return l(this,g,w,B);if(h.y<h.x){const Ht=h.y;h.y=h.x,h.x=Ht,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(u.y<u.x){const Ht=u.y;u.y=u.x,u.x=Ht,c.copy(o.start),o.start.copy(o.end),o.end.copy(c)}return h.y<u.x||u.y<h.x?!1:(w&&(u.x>h.x?w.start.copy(o.start):w.start.copy(a.start),u.y<h.y?w.end.copy(o.end):w.end.copy(a.end)),!0)}})(),ft.prototype.distanceToPoint=(function(){const f=new S;return function(e){return this.closestPointToPoint(e,f),e.distanceTo(f)}})(),ft.prototype.distanceToTriangle=(function(){const f=new S,t=new S,e=["a","b","c"],i=new Mt,s=new Mt;return function(r,a=null,o=null){const c=a||o?i:null;if(this.intersectsTriangle(r,c,!0))return(a||o)&&(a&&c.getCenter(a),o&&c.getCenter(o)),0;let h=1/0;for(let u=0;u<3;u++){let l;const d=e[u],y=r[d];this.closestPointToPoint(y,f),l=y.distanceToSquared(f),l<h&&(h=l,a&&a.copy(f),o&&o.copy(y));const m=this[d];r.closestPointToPoint(m,f),l=m.distanceToSquared(f),l<h&&(h=l,a&&a.copy(m),o&&o.copy(f))}for(let u=0;u<3;u++){const l=e[u],d=e[(u+1)%3];i.set(this[l],this[d]);for(let y=0;y<3;y++){const m=e[y],z=e[(y+1)%3];s.set(r[m],r[z]),Qi(i,s,f,t);const b=f.distanceToSquared(t);b<h&&(h=b,a&&a.copy(f),o&&o.copy(t))}}return Math.sqrt(h)}})();class j{constructor(t,e,i){this.isOrientedBox=!0,this.min=new S,this.max=new S,this.matrix=new H,this.invMatrix=new H,this.points=new Array(8).fill().map(()=>new S),this.satAxes=new Array(3).fill().map(()=>new S),this.satBounds=new Array(3).fill().map(()=>new St),this.alignedSatBounds=new Array(3).fill().map(()=>new St),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}j.prototype.update=(function(){return function(){const t=this.matrix,e=this.min,i=this.max,s=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const l=1*c|2*h|4*u,d=s[l];d.x=c?i.x:e.x,d.y=h?i.y:e.y,d.z=u?i.z:e.z,d.applyMatrix4(t)}const n=this.satBounds,r=this.satAxes,a=s[0];for(let c=0;c<3;c++){const h=r[c],u=n[c],l=1<<c,d=s[l];h.subVectors(a,d),u.setFromPoints(h,s)}const o=this.alignedSatBounds;o[0].setFromPointsField(s,"x"),o[1].setFromPointsField(s,"y"),o[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})(),j.prototype.intersectsBox=(function(){const f=new St;return function(e){this.needsUpdate&&this.update();const i=e.min,s=e.max,n=this.satBounds,r=this.satAxes,a=this.alignedSatBounds;if(f.min=i.x,f.max=s.x,a[0].isSeparated(f)||(f.min=i.y,f.max=s.y,a[1].isSeparated(f))||(f.min=i.z,f.max=s.z,a[2].isSeparated(f)))return!1;for(let o=0;o<3;o++){const c=r[o],h=n[o];if(f.setFromBox(c,e),h.isSeparated(f))return!1}return!0}})(),j.prototype.intersectsTriangle=(function(){const f=new ft,t=new Array(3),e=new St,i=new St,s=new S;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(f.copy(r),f.update(),r=f);const a=this.satBounds,o=this.satAxes;t[0]=r.a,t[1]=r.b,t[2]=r.c;for(let l=0;l<3;l++){const d=a[l],y=o[l];if(e.setFromPoints(y,t),d.isSeparated(e))return!1}const c=r.satBounds,h=r.satAxes,u=this.points;for(let l=0;l<3;l++){const d=c[l],y=h[l];if(e.setFromPoints(y,u),d.isSeparated(e))return!1}for(let l=0;l<3;l++){const d=o[l];for(let y=0;y<4;y++){const m=h[y];if(s.crossVectors(d,m),e.setFromPoints(s,t),i.setFromPoints(s,u),e.isSeparated(i))return!1}}return!0}})(),j.prototype.closestPointToPoint=(function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}})(),j.prototype.distanceToPoint=(function(){const f=new S;return function(e){return this.closestPointToPoint(e,f),e.distanceTo(f)}})(),j.prototype.distanceToBox=(function(){const f=["x","y","z"],t=new Array(12).fill().map(()=>new Mt),e=new Array(12).fill().map(()=>new Mt),i=new S,s=new S;return function(r,a=0,o=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(o||c)&&(r.getCenter(s),this.closestPointToPoint(s,i),r.closestPointToPoint(i,s),o&&o.copy(i),c&&c.copy(s)),0;const h=a*a,u=r.min,l=r.max,d=this.points;let y=1/0;for(let z=0;z<8;z++){const b=d[z];s.copy(b).clamp(u,l);const p=b.distanceToSquared(s);if(p<y&&(y=p,o&&o.copy(b),c&&c.copy(s),p<h))return Math.sqrt(p)}let m=0;for(let z=0;z<3;z++)for(let b=0;b<=1;b++)for(let p=0;p<=1;p++){const x=(z+1)%3,g=(z+2)%3,w=b<<x|p<<g,B=1<<z|b<<x|p<<g,_=d[w],M=d[B];t[m].set(_,M);const A=f[z],C=f[x],T=f[g],E=e[m],I=E.start,F=E.end;I[A]=u[A],I[C]=b?u[C]:l[C],I[T]=p?u[T]:l[C],F[A]=l[A],F[C]=b?u[C]:l[C],F[T]=p?u[T]:l[C],m++}for(let z=0;z<=1;z++)for(let b=0;b<=1;b++)for(let p=0;p<=1;p++){s.x=z?l.x:u.x,s.y=b?l.y:u.y,s.z=p?l.z:u.z,this.closestPointToPoint(s,i);const x=s.distanceToSquared(i);if(x<y&&(y=x,o&&o.copy(i),c&&c.copy(s),x<h))return Math.sqrt(x)}for(let z=0;z<12;z++){const b=t[z];for(let p=0;p<12;p++){const x=e[p];Qi(b,x,i,s);const g=i.distanceToSquared(s);if(g<y&&(y=g,o&&o.copy(i),c&&c.copy(s),g<h))return Math.sqrt(g)}}return Math.sqrt(y)}})();class $n extends Xi{constructor(){super(()=>new ft)}}const ot=new $n,Ae=new S,ji=new S;function Jn(f,t,e={},i=0,s=1/0){const n=i*i,r=s*s;let a=1/0,o=null;if(f.shapecast({boundsTraverseOrder:h=>(Ae.copy(t).clamp(h.min,h.max),Ae.distanceToSquared(t)),intersectsBounds:(h,u,l)=>l<a&&l<r,intersectsTriangle:(h,u)=>{h.closestPointToPoint(t,Ae);const l=t.distanceToSquared(Ae);return l<a&&(ji.copy(Ae),a=l,o=u),l<n}}),a===1/0)return null;const c=Math.sqrt(a);return e.point?e.point.copy(ji):e.point=ji.clone(),e.distance=c,e.faceIndex=o,e}const je=parseInt("186")>=169,Gn=parseInt("186")<=161,qt=new S,vt=new S,Ot=new S,Ke=new Y,ti=new Y,ei=new Y,Os=new S,Ws=new S,Xs=new S,Se=new S;function Qn(f,t,e,i,s,n,r,a){let o;if(n===1?o=f.intersectTriangle(i,e,t,!0,s):o=f.intersectTriangle(t,e,i,n!==2,s),o===null)return null;const c=f.origin.distanceTo(s);return c<r||c>a?null:{distance:c,point:s.clone()}}function Ys(f,t,e,i,s,n,r,a,o,c,h){qt.fromBufferAttribute(t,n),vt.fromBufferAttribute(t,r),Ot.fromBufferAttribute(t,a);const u=Qn(f,qt,vt,Ot,Se,o,c,h);if(u){if(i){Ke.fromBufferAttribute(i,n),ti.fromBufferAttribute(i,r),ei.fromBufferAttribute(i,a),u.uv=new Y;const d=st.getInterpolation(Se,qt,vt,Ot,Ke,ti,ei,u.uv);je||(u.uv=d)}if(s){Ke.fromBufferAttribute(s,n),ti.fromBufferAttribute(s,r),ei.fromBufferAttribute(s,a),u.uv1=new Y;const d=st.getInterpolation(Se,qt,vt,Ot,Ke,ti,ei,u.uv1);je||(u.uv1=d),Gn&&(u.uv2=u.uv1)}if(e){Os.fromBufferAttribute(e,n),Ws.fromBufferAttribute(e,r),Xs.fromBufferAttribute(e,a),u.normal=new S;const d=st.getInterpolation(Se,qt,vt,Ot,Os,Ws,Xs,u.normal);u.normal.dot(f.direction)>0&&u.normal.multiplyScalar(-1),je||(u.normal=d)}const l={a:n,b:r,c:a,normal:new S,materialIndex:0};if(st.getNormal(qt,vt,Ot,l.normal),u.face=l,u.faceIndex=n,je){const d=new S;st.getBarycoord(Se,qt,vt,Ot,d),u.barycoord=d}}return u}function Hs(f){return f&&f.isMaterial?f.side:f}function ii(f,t,e,i,s,n,r){const a=i*3;let o=a+0,c=a+1,h=a+2;const{index:u,groups:l}=f;f.index&&(o=u.getX(o),c=u.getX(c),h=u.getX(h));const{position:d,normal:y,uv:m,uv1:z}=f.attributes;if(Array.isArray(t)){const b=i*3;for(let p=0,x=l.length;p<x;p++){const{start:g,count:w,materialIndex:B}=l[p];if(b>=g&&b<g+w){const _=Hs(t[B]),M=Ys(e,d,y,m,z,o,c,h,_,n,r);if(M)if(M.faceIndex=i,M.face.materialIndex=B,s)s.push(M);else return M}}}else{const b=Hs(t),p=Ys(e,d,y,m,z,o,c,h,b,n,r);if(p)if(p.faceIndex=i,p.face.materialIndex=0,s)s.push(p);else return p}return null}function D(f,t,e,i){const s=f.a,n=f.b,r=f.c;let a=t,o=t+1,c=t+2;e&&(a=e.getX(a),o=e.getX(o),c=e.getX(c)),s.x=i.getX(a),s.y=i.getY(a),s.z=i.getZ(a),n.x=i.getX(o),n.y=i.getY(o),n.z=i.getZ(o),r.x=i.getX(c),r.y=i.getY(c),r.z=i.getZ(c)}function jn(f,t,e,i,s,n,r,a){const{geometry:o,_indirectBuffer:c}=f;for(let h=i,u=i+s;h<u;h++)ii(o,t,e,h,n,r,a)}function Kn(f,t,e,i,s,n,r){const{geometry:a,_indirectBuffer:o}=f;let c=1/0,h=null;for(let u=i,l=i+s;u<l;u++){let d;d=ii(a,t,e,u,null,n,r),d&&d.distance<c&&(h=d,c=d.distance)}return h}function tr(f,t,e,i,s,n,r){const{geometry:a}=e,{index:o}=a,c=a.attributes.position;for(let h=f,u=t+f;h<u;h++){let l;if(l=h,D(r,l*3,o,c),r.needsUpdate=!0,i(r,l,s,n))return!0}return!1}function er(f,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=f.geometry,i=e.index?e.index.array:null,s=e.attributes.position;let n,r,a,o,c=0;const h=f._roots;for(let l=0,d=h.length;l<d;l++)n=h[l],r=new Uint32Array(n),a=new Uint16Array(n),o=new Float32Array(n),u(0,c),c+=n.byteLength;function u(l,d,y=!1){const m=l*2;if(N(m,a)){const z=X(l,r),b=G(m,a);let p=1/0,x=1/0,g=1/0,w=-1/0,B=-1/0,_=-1/0;for(let M=3*z,P=3*(z+b);M<P;M++){let A=i[M];const C=s.getX(A),T=s.getY(A),E=s.getZ(A);C<p&&(p=C),C>w&&(w=C),T<x&&(x=T),T>B&&(B=T),E<g&&(g=E),E>_&&(_=E)}return o[l+0]!==p||o[l+1]!==x||o[l+2]!==g||o[l+3]!==w||o[l+4]!==B||o[l+5]!==_?(o[l+0]=p,o[l+1]=x,o[l+2]=g,o[l+3]=w,o[l+4]=B,o[l+5]=_,!0):!1}else{const z=v(l),b=O(l,r);let p=y,x=!1,g=!1;if(t){if(!p){const A=z/q+d/J,C=b/q+d/J;x=t.has(A),g=t.has(C),p=!x&&!g}}else x=!0,g=!0;const w=p||x,B=p||g;let _=!1;w&&(_=u(z,d,p));let M=!1;B&&(M=u(b,d,p));const P=_||M;if(P)for(let A=0;A<3;A++){const C=z+A,T=b+A,E=o[C],I=o[C+3],F=o[T],R=o[T+3];o[l+A]=E<F?E:F,o[l+A+3]=I>R?I:R}return P}}}function kt(f,t,e,i,s){let n,r,a,o,c,h;const u=1/e.direction.x,l=1/e.direction.y,d=1/e.direction.z,y=e.origin.x,m=e.origin.y,z=e.origin.z;let b=t[f],p=t[f+3],x=t[f+1],g=t[f+3+1],w=t[f+2],B=t[f+3+2];return u>=0?(n=(b-y)*u,r=(p-y)*u):(n=(p-y)*u,r=(b-y)*u),l>=0?(a=(x-m)*l,o=(g-m)*l):(a=(g-m)*l,o=(x-m)*l),n>o||a>r||((a>n||isNaN(n))&&(n=a),(o<r||isNaN(r))&&(r=o),d>=0?(c=(w-z)*d,h=(B-z)*d):(c=(B-z)*d,h=(w-z)*d),n>h||c>r)?!1:((c>n||n!==n)&&(n=c),(h<r||r!==r)&&(r=h),n<=s&&r>=i)}function ir(f,t,e,i,s,n,r,a){const{geometry:o,_indirectBuffer:c}=f;for(let h=i,u=i+s;h<u;h++){let l=c?c[h]:h;ii(o,t,e,l,n,r,a)}}function sr(f,t,e,i,s,n,r){const{geometry:a,_indirectBuffer:o}=f;let c=1/0,h=null;for(let u=i,l=i+s;u<l;u++){let d;d=ii(a,t,e,o?o[u]:u,null,n,r),d&&d.distance<c&&(h=d,c=d.distance)}return h}function nr(f,t,e,i,s,n,r){const{geometry:a}=e,{index:o}=a,c=a.attributes.position;for(let h=f,u=t+f;h<u;h++){let l;if(l=e.resolveTriangleIndex(h),D(r,l*3,o,c),r.needsUpdate=!0,i(r,l,s,n))return!0}return!1}function rr(f,t,e,i,s,n,r){k.setBuffer(f._roots[t]),Ki(0,f,e,i,s,n,r),k.clearBuffer()}function Ki(f,t,e,i,s,n,r){const{float32Array:a,uint16Array:o,uint32Array:c}=k,h=f*2;if(N(h,o)){const l=X(f,c),d=G(h,o);jn(t,e,i,l,d,s,n,r)}else{const l=v(f);kt(l,a,i,n,r)&&Ki(l,t,e,i,s,n,r);const d=O(f,c);kt(d,a,i,n,r)&&Ki(d,t,e,i,s,n,r)}}const or=["x","y","z"];function ar(f,t,e,i,s,n){k.setBuffer(f._roots[t]);const r=ts(0,f,e,i,s,n);return k.clearBuffer(),r}function ts(f,t,e,i,s,n){const{float32Array:r,uint16Array:a,uint32Array:o}=k;let c=f*2;if(N(c,a)){const u=X(f,o),l=G(c,a);return Kn(t,e,i,u,l,s,n)}else{const u=Li(f,o),l=or[u],y=i.direction[l]>=0;let m,z;y?(m=v(f),z=O(f,o)):(m=O(f,o),z=v(f));const p=kt(m,r,i,s,n)?ts(m,t,e,i,s,n):null;if(p){const w=p.point[l];if(y?w<=r[z+u]:w>=r[z+u+3])return p}const g=kt(z,r,i,s,n)?ts(z,t,e,i,s,n):null;return p&&g?p.distance<=g.distance?p:g:p||g||null}}const si=new Q,le=new ft,ue=new ft,Be=new H,Zs=new j,ni=new j;function cr(f,t,e,i){k.setBuffer(f._roots[t]);const s=es(0,f,e,i);return k.clearBuffer(),s}function es(f,t,e,i,s=null){const{float32Array:n,uint16Array:r,uint32Array:a}=k;let o=f*2;if(s===null&&(e.boundingBox||e.computeBoundingBox(),Zs.set(e.boundingBox.min,e.boundingBox.max,i),s=Zs),N(o,r)){const h=t.geometry,u=h.index,l=h.attributes.position,d=e.index,y=e.attributes.position,m=X(f,a),z=G(o,r);if(Be.copy(i).invert(),e.boundsTree)return U(f,n,ni),ni.matrix.copy(Be),ni.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:p=>ni.intersectsBox(p),intersectsTriangle:p=>{p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let x=m*3,g=(z+m)*3;x<g;x+=3)if(D(ue,x,u,l),ue.needsUpdate=!0,p.intersectsTriangle(ue))return!0;return!1}});{const b=Qe(e);for(let p=m*3,x=(z+m)*3;p<x;p+=3){D(le,p,u,l),le.a.applyMatrix4(Be),le.b.applyMatrix4(Be),le.c.applyMatrix4(Be),le.needsUpdate=!0;for(let g=0,w=b*3;g<w;g+=3)if(D(ue,g,d,y),ue.needsUpdate=!0,le.intersectsTriangle(ue))return!0}}}else{const h=v(f),u=O(f,a);return U(h,n,si),!!(s.intersectsBox(si)&&es(h,t,e,i,s)||(U(u,n,si),s.intersectsBox(si)&&es(u,t,e,i,s)))}}const ri=new H,is=new j,Te=new j,hr=new S,lr=new S,ur=new S,fr=new S;function dr(f,t,e,i={},s={},n=0,r=1/0){t.boundingBox||t.computeBoundingBox(),is.set(t.boundingBox.min,t.boundingBox.max,e),is.needsUpdate=!0;const a=f.geometry,o=a.attributes.position,c=a.index,h=t.attributes.position,u=t.index,l=ot.getPrimitive(),d=ot.getPrimitive();let y=hr,m=lr,z=null,b=null;s&&(z=ur,b=fr);let p=1/0,x=null,g=null;return ri.copy(e).invert(),Te.matrix.copy(ri),f.shapecast({boundsTraverseOrder:w=>is.distanceToBox(w),intersectsBounds:(w,B,_)=>_<p&&_<r?(B&&(Te.min.copy(w.min),Te.max.copy(w.max),Te.needsUpdate=!0),!0):!1,intersectsRange:(w,B)=>{if(t.boundsTree)return t.boundsTree.shapecast({boundsTraverseOrder:M=>Te.distanceToBox(M),intersectsBounds:(M,P,A)=>A<p&&A<r,intersectsRange:(M,P)=>{for(let A=M,C=M+P;A<C;A++){D(d,3*A,u,h),d.a.applyMatrix4(e),d.b.applyMatrix4(e),d.c.applyMatrix4(e),d.needsUpdate=!0;for(let T=w,E=w+B;T<E;T++){D(l,3*T,c,o),l.needsUpdate=!0;const I=l.distanceToTriangle(d,y,z);if(I<p&&(m.copy(y),b&&b.copy(z),p=I,x=T,g=A),I<n)return!0}}}});{const _=Qe(t);for(let M=0,P=_;M<P;M++){D(d,3*M,u,h),d.a.applyMatrix4(e),d.b.applyMatrix4(e),d.c.applyMatrix4(e),d.needsUpdate=!0;for(let A=w,C=w+B;A<C;A++){D(l,3*A,c,o),l.needsUpdate=!0;const T=l.distanceToTriangle(d,y,z);if(T<p&&(m.copy(y),b&&b.copy(z),p=T,x=A,g=M),T<n)return!0}}}}}),ot.releasePrimitive(l),ot.releasePrimitive(d),p===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=p,i.faceIndex=x,s&&(s.point?s.point.copy(b):s.point=b.clone(),s.point.applyMatrix4(ri),m.applyMatrix4(ri),s.distance=m.sub(s.point).length(),s.faceIndex=g),i)}function yr(f,t=null){t&&Array.isArray(t)&&(t=new Set(t));const e=f.geometry,i=e.index?e.index.array:null,s=e.attributes.position;let n,r,a,o,c=0;const h=f._roots;for(let l=0,d=h.length;l<d;l++)n=h[l],r=new Uint32Array(n),a=new Uint16Array(n),o=new Float32Array(n),u(0,c),c+=n.byteLength;function u(l,d,y=!1){const m=l*2;if(N(m,a)){const z=X(l,r),b=G(m,a);let p=1/0,x=1/0,g=1/0,w=-1/0,B=-1/0,_=-1/0;for(let M=z,P=z+b;M<P;M++){const A=3*f.resolveTriangleIndex(M);for(let C=0;C<3;C++){let T=A+C;T=i?i[T]:T;const E=s.getX(T),I=s.getY(T),F=s.getZ(T);E<p&&(p=E),E>w&&(w=E),I<x&&(x=I),I>B&&(B=I),F<g&&(g=F),F>_&&(_=F)}}return o[l+0]!==p||o[l+1]!==x||o[l+2]!==g||o[l+3]!==w||o[l+4]!==B||o[l+5]!==_?(o[l+0]=p,o[l+1]=x,o[l+2]=g,o[l+3]=w,o[l+4]=B,o[l+5]=_,!0):!1}else{const z=v(l),b=O(l,r);let p=y,x=!1,g=!1;if(t){if(!p){const A=z/q+d/J,C=b/q+d/J;x=t.has(A),g=t.has(C),p=!x&&!g}}else x=!0,g=!0;const w=p||x,B=p||g;let _=!1;w&&(_=u(z,d,p));let M=!1;B&&(M=u(b,d,p));const P=_||M;if(P)for(let A=0;A<3;A++){const C=z+A,T=b+A,E=o[C],I=o[C+3],F=o[T],R=o[T+3];o[l+A]=E<F?E:F,o[l+A+3]=I>R?I:R}return P}}}function mr(f,t,e,i,s,n,r){k.setBuffer(f._roots[t]),ss(0,f,e,i,s,n,r),k.clearBuffer()}function ss(f,t,e,i,s,n,r){const{float32Array:a,uint16Array:o,uint32Array:c}=k,h=f*2;if(N(h,o)){const l=X(f,c),d=G(h,o);ir(t,e,i,l,d,s,n,r)}else{const l=v(f);kt(l,a,i,n,r)&&ss(l,t,e,i,s,n,r);const d=O(f,c);kt(d,a,i,n,r)&&ss(d,t,e,i,s,n,r)}}const pr=["x","y","z"];function xr(f,t,e,i,s,n){k.setBuffer(f._roots[t]);const r=ns(0,f,e,i,s,n);return k.clearBuffer(),r}function ns(f,t,e,i,s,n){const{float32Array:r,uint16Array:a,uint32Array:o}=k;let c=f*2;if(N(c,a)){const u=X(f,o),l=G(c,a);return sr(t,e,i,u,l,s,n)}else{const u=Li(f,o),l=pr[u],y=i.direction[l]>=0;let m,z;y?(m=v(f),z=O(f,o)):(m=O(f,o),z=v(f));const p=kt(m,r,i,s,n)?ns(m,t,e,i,s,n):null;if(p){const w=p.point[l];if(y?w<=r[z+u]:w>=r[z+u+3])return p}const g=kt(z,r,i,s,n)?ns(z,t,e,i,s,n):null;return p&&g?p.distance<=g.distance?p:g:p||g||null}}const oi=new Q,fe=new ft,de=new ft,Pe=new H,$s=new j,ai=new j;function gr(f,t,e,i){k.setBuffer(f._roots[t]);const s=rs(0,f,e,i);return k.clearBuffer(),s}function rs(f,t,e,i,s=null){const{float32Array:n,uint16Array:r,uint32Array:a}=k;let o=f*2;if(s===null&&(e.boundingBox||e.computeBoundingBox(),$s.set(e.boundingBox.min,e.boundingBox.max,i),s=$s),N(o,r)){const h=t.geometry,u=h.index,l=h.attributes.position,d=e.index,y=e.attributes.position,m=X(f,a),z=G(o,r);if(Pe.copy(i).invert(),e.boundsTree)return U(f,n,ai),ai.matrix.copy(Pe),ai.needsUpdate=!0,e.boundsTree.shapecast({intersectsBounds:p=>ai.intersectsBox(p),intersectsTriangle:p=>{p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let x=m,g=z+m;x<g;x++)if(D(de,3*t.resolveTriangleIndex(x),u,l),de.needsUpdate=!0,p.intersectsTriangle(de))return!0;return!1}});{const b=Qe(e);for(let p=m,x=z+m;p<x;p++){const g=t.resolveTriangleIndex(p);D(fe,3*g,u,l),fe.a.applyMatrix4(Pe),fe.b.applyMatrix4(Pe),fe.c.applyMatrix4(Pe),fe.needsUpdate=!0;for(let w=0,B=b*3;w<B;w+=3)if(D(de,w,d,y),de.needsUpdate=!0,fe.intersectsTriangle(de))return!0}}}else{const h=v(f),u=O(f,a);return U(h,n,oi),!!(s.intersectsBox(oi)&&rs(h,t,e,i,s)||(U(u,n,oi),s.intersectsBox(oi)&&rs(u,t,e,i,s)))}}const ci=new H,os=new j,Ce=new j,wr=new S,br=new S,zr=new S,_r=new S;function Mr(f,t,e,i={},s={},n=0,r=1/0){t.boundingBox||t.computeBoundingBox(),os.set(t.boundingBox.min,t.boundingBox.max,e),os.needsUpdate=!0;const a=f.geometry,o=a.attributes.position,c=a.index,h=t.attributes.position,u=t.index,l=ot.getPrimitive(),d=ot.getPrimitive();let y=wr,m=br,z=null,b=null;s&&(z=zr,b=_r);let p=1/0,x=null,g=null;return ci.copy(e).invert(),Ce.matrix.copy(ci),f.shapecast({boundsTraverseOrder:w=>os.distanceToBox(w),intersectsBounds:(w,B,_)=>_<p&&_<r?(B&&(Ce.min.copy(w.min),Ce.max.copy(w.max),Ce.needsUpdate=!0),!0):!1,intersectsRange:(w,B)=>{if(t.boundsTree){const _=t.boundsTree;return _.shapecast({boundsTraverseOrder:M=>Ce.distanceToBox(M),intersectsBounds:(M,P,A)=>A<p&&A<r,intersectsRange:(M,P)=>{for(let A=M,C=M+P;A<C;A++){const T=_.resolveTriangleIndex(A);D(d,3*T,u,h),d.a.applyMatrix4(e),d.b.applyMatrix4(e),d.c.applyMatrix4(e),d.needsUpdate=!0;for(let E=w,I=w+B;E<I;E++){const F=f.resolveTriangleIndex(E);D(l,3*F,c,o),l.needsUpdate=!0;const R=l.distanceToTriangle(d,y,z);if(R<p&&(m.copy(y),b&&b.copy(z),p=R,x=E,g=A),R<n)return!0}}}})}else{const _=Qe(t);for(let M=0,P=_;M<P;M++){D(d,3*M,u,h),d.a.applyMatrix4(e),d.b.applyMatrix4(e),d.c.applyMatrix4(e),d.needsUpdate=!0;for(let A=w,C=w+B;A<C;A++){const T=f.resolveTriangleIndex(A);D(l,3*T,c,o),l.needsUpdate=!0;const E=l.distanceToTriangle(d,y,z);if(E<p&&(m.copy(y),b&&b.copy(z),p=E,x=A,g=M),E<n)return!0}}}}}),ot.releasePrimitive(l),ot.releasePrimitive(d),p===1/0?null:(i.point?i.point.copy(m):i.point=m.clone(),i.distance=p,i.faceIndex=x,s&&(s.point?s.point.copy(b):s.point=b.clone(),s.point.applyMatrix4(ci),m.applyMatrix4(ci),s.distance=m.sub(s.point).length(),s.faceIndex=g),i)}function Js(f,t,e){return f===null?null:(f.point.applyMatrix4(t.matrixWorld),f.distance=f.point.distanceTo(e.ray.origin),f.object=t,f)}const hi=new j,li=new zn,Gs=new S,Qs=new H,js=new S,as=["getX","getY","getZ"];class Ee extends Xn{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,s=t._roots,n=t._indirectBuffer,r=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(a.roots=s.map(o=>o.slice()),a.index=r?r.array.slice():null,a.indirectBuffer=n?n.slice():null):(a.roots=s,a.index=r?r.array:null,a.indirectBuffer=n),a}static deserialize(t,e,i={}){i={setIndex:!0,indirect:!!t.indirectBuffer,...i};const{index:s,roots:n,indirectBuffer:r}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),o(n));const a=new Ee(e,{...i,[Ui]:!0});if(a._roots=n,a._indirectBuffer=r||null,i.setIndex){const c=e.getIndex();if(c===null){const h=new mt(t.index,1,!1);e.setIndex(h)}else c.array!==s&&(c.array.set(s),c.needsUpdate=!0)}return a;function o(c){for(let h=0;h<c.length;h++){const u=c[h],l=new Uint32Array(u),d=new Uint16Array(u);for(let y=0,m=u.byteLength/J;y<m;y++){const z=q*y,b=2*z;N(b,d)||(l[z+6]=l[z+6]/q-y)}}}}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use "targetLeafSize", instead.'),e={...e,targetLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const s=this.geometry,n=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,c=(n?n[t]:t)*3;let h=c+0,u=c+1,l=c+2;a&&(h=a[h],u=a[u],l=a[l]);for(let d=0;d<3;d++){const y=r[as[d]](h),m=r[as[d]](u),z=r[as[d]](l);let b=y;m<b&&(b=m),z<b&&(b=z);let p=y;m>p&&(p=m),z>p&&(p=z),e[i+d]=b,e[i+d+3]=p}return e}computePrimitiveBounds(t,e,i){const s=this.geometry,n=this._indirectBuffer,r=s.attributes.position,a=s.index?s.index.array:null,o=r.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const c=r.array,h=r.offset||0;let u=3;r.isInterleavedBufferAttribute&&(u=r.data.stride);const l=["getX","getY","getZ"],d=i.offset;for(let y=t,m=t+e;y<m;y++){const b=(n?n[y]:y)*3,p=(y-d)*6;let x=b+0,g=b+1,w=b+2;a&&(x=a[x],g=a[g],w=a[w]),o||(x=x*u+h,g=g*u+h,w=w*u+h);for(let B=0;B<3;B++){let _,M,P;o?(_=r[l[B]](x),M=r[l[B]](g),P=r[l[B]](w)):(_=c[x+B],M=c[g+B],P=c[w+B]);let A=_;M<A&&(A=M),P<A&&(A=P);let C=_;M>C&&(C=M),P>C&&(C=P);const T=(C-A)/2,E=B*2;i[p+E+0]=A+T,i[p+E+1]=T+(Math.abs(A)+T)*Ye}}return i}raycastObject3D(t,e,i=[]){const{material:s}=t;if(s===void 0)return;Qs.copy(t.matrixWorld).invert(),li.copy(e.ray).applyMatrix4(Qs),js.setFromMatrixScale(t.matrixWorld),Gs.copy(li.direction).multiply(js);const n=Gs.length(),r=e.near/n,a=e.far/n;if(e.firstHitOnly===!0){let o=this.raycastFirst(li,s,r,a);o=Js(o,t,e),o&&i.push(o)}else{const o=this.raycast(li,s,r,a);for(let c=0,h=o.length;c<h;c++){const u=Js(o[c],t,e);u&&i.push(u)}}return i}refit(t=null){return(this.indirect?yr:er)(this,t)}raycast(t,e=0,i=0,s=1/0){const n=this._roots,r=[],a=this.indirect?mr:rr;for(let o=0,c=n.length;o<c;o++)a(this,o,e,t,r,i,s);return r}raycastFirst(t,e=0,i=0,s=1/0){const n=this._roots;let r=null;const a=this.indirect?xr:ar;for(let o=0,c=n.length;o<c;o++){const h=a(this,o,e,t,i,s);h!=null&&(r==null||h.distance<r.distance)&&(r=h)}return r}intersectsGeometry(t,e){let i=!1;const s=this._roots,n=this.indirect?gr:cr;for(let r=0,a=s.length;r<a&&(i=n(this,r,t,e),!i);r++);return i}shapecast(t){const e=ot.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?nr:tr});return ot.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:s,intersectsTriangles:n}=i;const r=ot.getPrimitive(),a=this.geometry.index,o=this.geometry.attributes.position,c=this.indirect?y=>{const m=this.resolveTriangleIndex(y);D(r,m*3,a,o)}:y=>{D(r,y*3,a,o)},h=ot.getPrimitive(),u=t.geometry.index,l=t.geometry.attributes.position,d=t.indirect?y=>{const m=t.resolveTriangleIndex(y);D(h,m*3,u,l)}:y=>{D(h,y*3,u,l)};if(n){if(!(t instanceof Ee))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const y=(m,z,b,p,x,g,w,B)=>{for(let _=b,M=b+p;_<M;_++){d(_),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let P=m,A=m+z;P<A;P++)if(c(P),r.needsUpdate=!0,n(r,h,P,_,x,g,w,B))return!0}return!1};if(s){const m=s;s=function(z,b,p,x,g,w,B,_){return m(z,b,p,x,g,w,B,_)?!0:y(z,b,p,x,g,w,B,_)}}else s=y}return super.bvhcast(t,e,{intersectsRanges:s})}intersectsBox(t,e){return hi.set(t.min,t.max,e),hi.needsUpdate=!0,this.shapecast({intersectsBounds:i=>hi.intersectsBox(i),intersectsTriangle:i=>hi.intersectsTriangle(i)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},s={},n=0,r=1/0){return(this.indirect?Mr:dr)(this,t,e,i,s,n,r)}closestPointToPoint(t,e={},i=0,s=1/0){return Jn(this,t,e,i,s)}}const cs=self;cs.addEventListener("message",async({data:f})=>{let t=performance.now();function e(a){const o=performance.now();(o-t>=10||a===1)&&(postMessage({error:void 0,serialized:void 0,position:void 0,progress:a}),t=o)}const{id:i,index:s,position:n,options:r}=f;try{const a=new Ii;if(a.setAttribute("position",new mt(n,3,!1)),s&&a.setIndex(new mt(s,1,!1)),r.includedProgressCallback&&(r.onProgress=e),r.groups){const h=r.groups;for(const u in h){const l=h[u];a.addGroup(l.start,l.count,l.materialIndex)}}const o=new Ee(a,r),c=Ee.serialize(o,{cloneBuffers:!1});cs.postMessage({id:i,error:void 0,serialized:c,position:n,progress:1},[c.index.buffer,n.buffer,...c.roots])}catch(a){cs.postMessage({id:i,error:a,serialized:void 0,position:void 0,progress:1})}})})();
1533
- `,ao=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",ll],{type:"text/javascript;charset=utf-8"});function mu(c){let t;try{if(t=ao&&(self.URL||self.webkitURL).createObjectURL(ao),!t)throw"";const e=new Worker(t,{name:c?.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(ll),{name:c?.name})}}class cl{constructor(){g(this,"running");g(this,"worker");this.running=!1,this.worker=new mu,this.worker.onerror=t=>{throw t.message?new Error(`[GenerateMeshBVHWorker] Could not create Web Worker with error "${t.message}"`):new Error("[GenerateMeshBVHWorker] Could not create Web Worker.")}}isRunning(){return this.running}generate(t,e={}){if(this.running){P.warn("[GenerateMeshBVHWorker] Already running job.");return}if(!this.worker){P.warn("[GenerateMeshBVHWorker] Worker has been disposed.");return}const{worker:i}=this;this.running=!0;const s=new Map;t.forEach(r=>{s.set(r.id,r)});let n=0;return new Promise((r,a)=>{const o=()=>{++n===s.size&&(this.running=!1,i.onmessage=null,r())};i.onerror=l=>{P.warn("[GenerateMeshBVHWorker] "+l.message),a(new Error("[GenerateMeshBVHWorker] "+l.message)),this.running=!1},i.onmessage=l=>{this.running=!1;const{data:h}=l;if(h.error)P.warn(h.error),o();else if(h.serialized){const{serialized:d,position:u,id:f}=h,m=s.get(f),b=ps.deserialize(d,m,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},e);if(y.transferred&&(m.attributes.position.array=u),m.index)e.saveOriginalIndex&&!m.userData.originalIndex&&(m.userData.originalIndex=m.index.array),P.debug("before update, index:",m.index.array),m.index.array=d.index;else{const S=new L.BufferAttribute(d.index,1,!1);m.setIndex(S)}m.index&&(P.debug("after update, index:",m.index.array),m.index.needsUpdate=!0),y.setBoundingBox&&!m.boundingBox&&(m.boundingBox=b.getBoundingBox(new L.Box3)),m.boundsTree=b,o()}else e.onProgress&&e.onProgress(h.progress)};for(const[l,h]of s){const d=h.index?h.index.array:void 0,u=h.attributes.position,f=u.array;if(u.isInterleavedBufferAttribute||d&&d.isInterleavedBufferAttribute){P.warn("[GenerateMeshBVHWorker] InterleavedBufferAttribute are not supported for the geometry attributes."),o();continue}const m=[];e.transferred&&(m.push(f),d&&(m.push(d),e.saveOriginalIndex&&(h.userData.originalIndex=d.slice()))),i.postMessage({id:l,index:d,position:f,options:Object.assign(Object.assign({},e),{onProgress:null,includedProgressCallback:!!e.onProgress,groups:[...h.groups]})},m.length>0?m.map(b=>b.buffer):[])}})}dispose(){this.worker.terminate(),this.worker=void 0}}class zr{constructor(t){g(this,"running");g(this,"workers");this.running=!1,this.workers=[];let e=1;t?e=t:window.navigator&&(e=Math.max(e,window.navigator.hardwareConcurrency-1));for(let i=0;i<e;i++)this.workers[i]=new cl}isRunning(){return this.running}async generate(t,e={}){if(this.running){P.warn("[BVHHelper] Already running job.");return}if(this.workers.length===0){P.warn("[BVHHelper] Worker has been disposed.");return}return this.running=!0,new Promise(i=>{const s=this.workers.length,n=t.length,r=[],a=Math.floor(n/s),o=n%s;let l=0,h=0;for(let d=0;d<s;d++){const u=this.workers[d];if(d<o?(l=d*a+d,h=l+a+1):(l=d*a+o,h=l+a),l=Math.min(l,n),h=Math.min(h,n),l>=h)break;P.debug("startIndex: "+l+" endIndex: "+h),r.push(u.generate(t.slice(l,h),e))}Promise.allSettled(r).then(()=>{this.running=!1,i()})})}dispose(){for(let t=0;t<this.workers.length;t++)this.workers[t].dispose();this.workers=[]}static createMeshBvhSync(t,e={}){const i=new Set;t.forEach(s=>{s.traverse(n=>{const r=n;if(r.isMesh&&r.geometry&&fe.isMergedMesh(r)&&!(r instanceof p.InstancedMesh)){if(i.has(r.geometry.id))return;r.geometry.index&&e.saveOriginalIndex&&(r.geometry.userData.originalIndex=r.geometry.index.array.slice()),r.geometry.boundsTree=new ps(r.geometry,e),i.add(r.geometry.id)}})})}static createMeshBvhAsync(t,e={}){const i=new Set,s=[];t.forEach(r=>{r.traverse(a=>{const o=a;if(o.isMesh&&o.geometry&&fe.isMergedMesh(o)&&!(o instanceof p.InstancedMesh)){if(i.has(o.geometry.id))return;s.push(o.geometry),i.add(o.geometry.id)}})});const n=new zr;return n.generate(s,e).then(()=>{n.dispose()})}}class gu{constructor(t,e,i,s,n){g(this,"object");g(this,"camera");g(this,"targetPixelHeight",100);g(this,"canvasHeight",800);this.camera=t,this.object=i,this.targetPixelHeight=s,this.canvasHeight=n,this.adjustSize(),e.addEventListener("update",()=>{this.adjustSize()})}adjustSize(){const t=new p.Box3;if(this.object.updateMatrix(),t.expandByObject(this.object),!t)return;const e=t.max.x-t.min.x,i=this.camera.position.distanceTo(this.object.position),s=yu(e,i,this.canvasHeight);if(Math.abs(s-this.targetPixelHeight)<5)return;let r=this.object.scale.x;r*=this.targetPixelHeight/s,this.object.scale.set(r,r,r),this.object.updateMatrix()}}const yu=(c,t,e=800,i=45)=>{const s=i*(Math.PI/180),n=2*Math.tan(s/2)*t,r=c/n;return e*r},Js=new p.Vector2,Qs=new p.Vector2,en=new p.Vector2,oo=new p.Vector2,xu=new p.Vector2,bu=new p.Vector2,xe=class xe extends Nt{constructor(e){super(j.guid());g(this,"needsFrustumCulled");g(this,"renderOrder");g(this,"snapType");g(this,"osnapInfo");g(this,"drawSnapFunctions");g(this,"snapLineVisible");this.needsFrustumCulled=!1,this.renderOrder=1e3,this.snapType=Et.TripleCross,this.snapLineVisible=!1,this.snapType=e,this.drawSnapFunctions={TripleCross:this.drawTripleCorss.bind(this),Square:this.drawSquare.bind(this),Triangle:this.drawTriangle.bind(this),CircleWithCross:this.drawCircleWithCross.bind(this),Cross:this.drawCross.bind(this),Perpendicular:this.drawPerpendicular.bind(this)}}setSnapLineVisible(e){this.snapLineVisible=e}draw(e,i){this.osnapInfo&&(this.snapLineVisible&&this.drawSnapLine(e,i),e.save(),e.fillStyle=xe.FILL_COLOR_NONE,e.strokeStyle=xe.lineColor,e.lineWidth=xe.lineWidth,e.beginPath(),this.drawSnapFunctions[this.snapType](e,i),e.closePath(),e.fill(),e.stroke(),e.restore())}drawDebug(e,i){}drawSelect(e,i){}isPointInPath(e){return!1}drawSnapLine(e,i){e.save(),e.strokeStyle=xe.SNAP_LINE_COLOR,e.lineWidth=xe.lineWidth;const s=this.osnapInfo.line;if(!s)return;const n=this.transToScreenCoord(s.start,i),r=this.transToScreenCoord(s.end,i);e.moveTo(n.x,n.y),e.lineTo(r.x,r.y),e.stroke(),e.restore()}drawTripleCorss(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/1.6,r=Js.set(s.x,s.y-n),a=Qs.set(s.x-.87*n,s.y+n/1.4),o=en.set(s.x+.87*n,s.y+n/1.4);e.moveTo(s.x,s.y),e.lineTo(r.x,r.y),e.moveTo(s.x,s.y),e.lineTo(a.x,a.y),e.moveTo(s.x,s.y),e.lineTo(o.x,o.y)}drawSquare(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize,r=xe.iconSize;e.rect(s.x-n/2,s.y-r/2,n,r)}drawTriangle(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/1.6,r=Js.set(s.x,s.y-n),a=Qs.set(s.x-.87*n,s.y+n/2),o=en.set(s.x+.87*n,s.y+n/2);e.moveTo(r.x,r.y),e.lineTo(a.x,a.y),e.lineTo(o.x,o.y)}drawCircleWithCross(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/2;e.arc(s.x,s.y,n,0,Math.PI*2),e.moveTo(s.x-n/1.8,s.y),e.lineTo(s.x+n/1.8,s.y),e.moveTo(s.x,s.y-n/1.8),e.lineTo(s.x,s.y+n/1.8)}drawCross(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/2,r=Js.set(s.x-n,s.y-n),a=Qs.set(s.x+n,s.y+n),o=en.set(s.x+n,s.y-n),l=oo.set(s.x-n,s.y+n);e.moveTo(r.x,r.y),e.lineTo(a.x,a.y),e.moveTo(o.x,o.y),e.lineTo(l.x,l.y)}drawPerpendicular(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/2,r=Js.set(s.x,s.y),a=Qs.set(s.x-n,s.y),o=en.set(s.x,s.y+n),l=oo.set(s.x-n,s.y-n),h=xu.set(s.x-n,s.y+n),d=bu.set(s.x+n,s.y+n);e.moveTo(a.x,a.y),e.lineTo(r.x,r.y),e.lineTo(o.x,o.y),e.moveTo(l.x,l.y),e.lineTo(h.x,h.y),e.lineTo(d.x,d.y),e.lineTo(l.x,l.y)}update(e){this.osnapInfo=e}getClassType(){return"SnapDrawable"}};g(xe,"lineColor","rgba(255, 119, 0, 1)"),g(xe,"FILL_COLOR_NONE","rgba(0, 0, 0, 0)"),g(xe,"SNAP_LINE_COLOR","rgba(255, 240, 0, 0.3)"),g(xe,"lineWidth",2),g(xe,"iconSize",14);let _e=xe;bs._registerDrawableClass(_e);var hl=(c=>(c[c.None=0]="None",c[c.Vertex=1]="Vertex",c[c.MiddlePoint=2]="MiddlePoint",c[c.Edge=4]="Edge",c[c.Face=8]="Face",c[c.FootOfPerpendicular=16]="FootOfPerpendicular",c[c.Intersection=32]="Intersection",c[c.CircleCenter=64]="CircleCenter",c))(hl||{});const wu=1e-5,oe=new p.Vector3,Ee=new p.Vector3,Di=new p.Vector3,cs=new p.Vector3,ti=new p.Matrix4,hs=new p.Line3;function vu(c,t){let e=Number.MAX_VALUE,i=0;for(let s=0;s<c.vertices.length;s++){const n=t.distanceTo(c.vertices[s]);n<e&&(i=s,e=n)}return{vertex:c.vertices[i],distance:e}}function Mu(c){if(!(c.object instanceof p.Mesh)||!c.face)return;const t=c.object,e=t.geometry.attributes.position;let i=t.geometry.index;if(e.count<3)return;const s=fe.getBatchByFaceIndex(t,c.faceIndex);t.geometry.boundsTree&&(i=new p.BufferAttribute(t.geometry.userData.originalIndex,1,!1)),ti.identity(),t instanceof p.InstancedMesh&&c.instanceId!==void 0&&t.getMatrixAt(c.instanceId,ti),ti.premultiply(t.matrixWorld);const n=t.geometry.drawRange;let r,a=e.array;if(i){let f=Math.max(0,n.start),m=Math.min(i.count,n.start+n.count);if(r=i.array,s){f=Math.max(f,s.indexStart),m=Math.min(m,s.indexStart+s.indexCount),r=i.array.slice(f,m),a=e.array.slice(s.positionStart*3,(s.positionStart+s.positionCount)*3);for(let b=0;b<r.length;b++)r[b]=r[b]-s.positionStart}else(f!==0||m!==i.count)&&(r=i.array.slice(f,m))}else{let f=Math.max(0,n.start),m=Math.min(e.count,n.start+n.count);s?(f=Math.max(f,s.positionStart),m=Math.min(m,s.positionStart+s.positionCount),a=e.array.slice(s.positionStart*3,(s.positionStart+s.positionCount)*3)):(f!==0||m!==e.count)&&(a=e.array.slice(f*3,m*3));const b=a.length/3;r=b>65535?new Uint32Array(b):new Uint16Array(b);for(let y=0,S=b;y<S;y++)r[y]=y}const o=_o.buildEdge(a,r,20);let l=Number.MAX_VALUE,h=0;for(let f=0;f<o.length;f+=2){const m=o[f],b=o[f+1];oe.set(a[m*3],a[m*3+1],a[m*3+2]),oe.applyMatrix4(ti),Ee.set(a[b*3],a[b*3+1],a[b*3+2]),Ee.applyMatrix4(ti),hs.set(oe,Ee),hs.closestPointToPoint(c.point,!0,Di);const y=c.point.distanceTo(Di);y<l&&(h=f,l=y,cs.copy(Di))}const d=o[h],u=o[h+1];return oe.set(a[d*3],a[d*3+1],a[d*3+2]),oe.applyMatrix4(ti),Ee.set(a[u*3],a[u*3+1],a[u*3+2]),Ee.applyMatrix4(ti),{vertices:[oe.clone(),Ee.clone()],vertex:cs.clone(),distance:l}}class Tu{constructor(t){g(this,"drawableList",new ws("snap"));g(this,"overlayRender");g(this,"markers",{});g(this,"activeOSnapType",0);g(this,"snapToleranceInWorldCoord",1);g(this,"intersectionLimit",10);g(this,"osnapTypePriorities",{1:0,2:1,64:2,32:3,16:4,4:5,8:6,0:100});g(this,"enabledOSnapTypes",127);this.overlayRender=t,this.overlayRender?.addDrawableList(this.drawableList),this.initOSnapMarkers()}initOSnapMarkers(){const t=new _e(Et.TripleCross),e=new _e(Et.Square),i=new _e(Et.Triangle),s=new _e(Et.CircleWithCross),n=new _e(Et.Cross),r=new _e(Et.Perpendicular);this.markers[1]=e,this.markers[2]=i,this.markers[4]=t,this.markers[32]=n,this.markers[64]=s,this.markers[16]=r,Object.values(this.markers).forEach(a=>{a.visible=!1,this.drawableList.addDrawable(a)})}isOSnapTypeEnabled(t){return!!(this.enabledOSnapTypes&t)}setOSnapTypeEnabled(t,e){if(e)this.enabledOSnapTypes|=t;else{const i=~t;this.enabledOSnapTypes&=i}}setSnapTolerance(t){this.snapToleranceInWorldCoord=t}getSnapTolerance(){return this.snapToleranceInWorldCoord}setIntersectionLimit(t){this.intersectionLimit=t}getIntersectionLimit(){return this.intersectionLimit}getMarkerLineColor(){return Li.colorStr2Rgba(_e.lineColor)}setMarkerLineColor(t){_e.lineColor=Li.rgba2Color(t)}getMarkerLineWidth(){return _e.lineWidth}setMarkerLineWidth(t){_e.lineWidth=t}getMarkerIconSize(){return _e.iconSize}setMarkerIconSize(t){_e.iconSize=t}getMarker(t){return this.markers[t]}setAllSnapLinesVisible(t){Object.values(this.markers).forEach(e=>{e.setSnapLineVisible(t)})}deactivate(){this.activeOSnapType&&(this.markers[this.activeOSnapType].visible=!1,this.overlayRender?.render()),this.activeOSnapType=0}destroy(){}handleSnap(t,e,i){if(!t||t.length<1){this.deactivate();return}P.debug("[OSnap] intersections before handleSnap:",t);const s=[];let n=!1,r;for(const o of t)o.object instanceof p.Mesh?(!r&&(r=o.point),!n&&o.object.name!=="groundPlane"&&(s.push(o),n=!0)):s.push(o);if(!e&&r){r.setZ(0);for(const l of s)l.point.z=0,l.distance=l.point.distanceTo(r);const o=l=>l instanceof p.Points?0:l instanceof p.LineSegments?2:l instanceof p.Line?1:3;s.sort((l,h)=>{const d=o(l.object),u=o(h.object);return d!==u?d-u:l.distance-h.distance})}return r||(P.warn("[OSnap] Potential to produce erroneous snap results"),r=s[0].point),P.debug("[OSnap] intersections:",s),P.debug("[OSnap] mousePosition:",r),this.getSnapPointAndUpdateMarker(r,s,e,i)?.clone()||r}getSnapPointAndUpdateMarker(t,e,i,s){if(!e.length){this.activateMarker(0);return}const n=this.getSnapInfo(t,e,i,s);if(!n||n.type===0){this.activateMarker(0);return}return this.activateMarker(n.type,n),n.point}activateMarker(t,e){this.activeOSnapType&&(this.markers[this.activeOSnapType].visible=!1),this.activeOSnapType=t;const i=this.markers[t];i&&e&&(i.update(e),i.visible=!0),this.overlayRender?.render()}getFootOfPerpendicular(t,e,i=wu){const{start:s,end:n}=e,r=s.x-n.x,a=s.y-n.y,o=s.z-n.z;if(s.distanceTo(n)<i)return s.clone();let l=(t.x-s.x)*(s.x-n.x)+(t.y-s.y)*(s.y-n.y)+(t.z-s.z)*(s.z-n.z);return l=l/(r*r+a*a+o*o),new p.Vector3(s.x+l*r,s.y+l*a,s.z+l*o)}getSnapInfo(t,e,i,s){const n=this.snapToleranceInWorldCoord*2;P.debug("[OSnap] snap radius:",n);const r=[],a={line:void 0};let o=this.osnapTypePriorities[0];for(let l=0;l<e.length&&l<this.intersectionLimit;++l){const h=e[l],d=h.object;let u;d instanceof p.Mesh?u=this.getOsnapInfoListFromMesh(t,h,n,o):d instanceof p.Line?u=this.getOsnapInfoListFromLine(t,h,i,n,a,o,s):d instanceof p.Points&&(u=this.getOsnapInfoListFromPoint(t,h,i,n,o)),u&&(o=this.osnapTypePriorities[u.type],r.push(u))}if(r.length!==0)return r.sort((l,h)=>{const d=this.osnapTypePriorities[l.type],u=this.osnapTypePriorities[h.type];return d!==u?d-u:l.distance-h.distance}),r[0]}getOsnapInfoListFromMesh(t,e,i,s){if(s<this.osnapTypePriorities[1])return;const n=Date.now(),r=Mu(e);if(!r){P.warn("[OSnap] Failed to get edge !");return}const a=Date.now();P.debug("[OSnap] getEdgeSnappingInfo took "+(a-n)/1e3+"s "),P.debug("[OSnap] edge:",r);const o=vu(r,t);if(P.debug("[OSnap] vertex:",o),o.distance<=i&&this.isOSnapTypeEnabled(1))return{distance:o.distance,type:1,point:o.vertex};if(r.distance<=i){if(this.isOSnapTypeEnabled(2)&&s<this.osnapTypePriorities[2])return;oe.copy(r.vertices[0]),oe.add(r.vertices[1]),oe.divideScalar(2);const l=oe.distanceTo(t);return l<=i&&this.isOSnapTypeEnabled(2)?{distance:l,type:2,point:oe.clone()}:!this.isOSnapTypeEnabled(4)||s<this.osnapTypePriorities[4]?void 0:{distance:r.distance,type:4,point:r.vertex,line:{start:r.vertices[0],end:r.vertices[1]}}}else P.debug("[OSnap] Face")}getOsnapInfoFromSegment(t,e,i,s,n,r,a){const o={start:e,end:i};if(a&&r>=this.osnapTypePriorities[16]&&this.isOSnapTypeEnabled(16)){const f=this.getFootOfPerpendicular(a,o,s),m=t.distanceTo(f);if(m<=s)return{distance:z.floorNumber(m,7),type:16,point:f.clone()}}if(r<this.osnapTypePriorities[1])return;hs.set(e,i),hs.closestPointToPoint(t,!0,Di);const l=t.distanceTo(Di);if(l>s)return;const h=t.distanceTo(e),d=t.distanceTo(i);if(Math.min(h,d)<=s&&this.isOSnapTypeEnabled(1)){let f=h,m=e;return d<h&&(f=d,m=i),{distance:z.floorNumber(f,7),type:1,point:m.clone()}}if(r<this.osnapTypePriorities[2])return;hs.getCenter(cs);const u=t.distanceTo(cs);if(u<s&&this.isOSnapTypeEnabled(2))return{point:cs.clone(),distance:z.floorNumber(u,7),type:2};if(!(r<this.osnapTypePriorities[4])){if(n.line&&this.isOSnapTypeEnabled(32)){const f=H.getLineSegmentsIntersectingPoint(n.line,o);if(!f)return;const m=t.distanceTo(f)/2;return m<s?(n.line=void 0,{point:f.clone(),distance:z.floorNumber(m,7),type:32}):void 0}if(this.isOSnapTypeEnabled(4))return n.line={start:e.clone(),end:i.clone()},{point:Di.clone(),distance:z.floorNumber(l,7),type:4,line:{start:e.clone(),end:i.clone()}}}}getOsnapInfoListFromLine(t,e,i,s,n,r,a){const o=[],l=e.object,h=l instanceof p.LineSegments?2:1,d=l.geometry.index,u=l.geometry.attributes.position,f=l.geometry.drawRange,m=fe.getBatchByLineIndex(l,e.index);if(d){let b=Math.max(0,f.start),y=Math.min(d.count,f.start+f.count);m&&(b=Math.max(b,m.indexStart),y=Math.min(y,m.indexStart+m.indexCount));for(let S=b,w=y;S<w-1;S+=h){const x=d.getX(S),E=d.getX(S+1);oe.fromBufferAttribute(u,x),Ee.fromBufferAttribute(u,E),oe.applyMatrix4(l.matrixWorld),Ee.applyMatrix4(l.matrixWorld),!i&&(oe.setZ(0),Ee.setZ(0));const M=this.getOsnapInfoFromSegment(t,oe,Ee,s,n,r,a);M&&(r=this.osnapTypePriorities[M.type],o.push(M))}}else{let b=Math.max(0,f.start),y=Math.min(u.count,f.start+f.count);m&&(b=Math.max(b,m.positionStart),y=Math.min(y,m.positionStart+m.positionCount));for(let S=b,w=y;S<w-1;S+=h){oe.fromBufferAttribute(u,S),Ee.fromBufferAttribute(u,S+1),oe.applyMatrix4(l.matrixWorld),Ee.applyMatrix4(l.matrixWorld),!i&&(oe.setZ(0),Ee.setZ(0));const x=this.getOsnapInfoFromSegment(t,oe,Ee,s,n,r,a);x&&(r=this.osnapTypePriorities[x.type],o.push(x))}}if(o.length!==0)return o.sort((b,y)=>{const S=this.osnapTypePriorities[b.type],w=this.osnapTypePriorities[y.type];return S!==w?S-w:b.distance-y.distance}),o[0]}getOsnapInfoListFromPoint(t,e,i,s,n){if(n<this.osnapTypePriorities[1])return;const r=e.object,a=r.geometry.getAttribute("position");oe.fromBufferAttribute(a,e.index),oe.applyMatrix4(r.matrixWorld),Ee.copy(t),!i&&(oe.setZ(0),Ee.setZ(0));const o=Ee.distanceTo(oe);if(o>s)return;const l={distance:o,point:oe.clone(),type:1};if(r.userData.type==="CircleCenter"){if(!this.isOSnapTypeEnabled(64))return;l.type=64}else if(P.debug("[OSnap] Other types of vertices !"),!this.isOSnapTypeEnabled(1))return;return l}getIntersectsIncludeOutline(t,e){const i=t.slice(),s=[];for(let r=0;r<t.length&&r<this.intersectionLimit;r++){const a=t[r].object;if(a.updateWorldMatrix(!0,!1),a instanceof p.Mesh&&!J.hasOutline(a,!1)){const o=J.createOutline(a.geometry);o.visible=!1,a.add(o),o.updateWorldMatrix(!0,!1),s.push(o)}}let n=[];return s.length>0&&(n=e.intersectObjects(s)||[],P.debug("[OSnap] Intersected with newly created edges: ",n),n.length>0&&i.push(...n)),i.sort((r,a)=>r.distance-a.distance),i}}class dl{constructor(t,e,i){g(this,"node");g(this,"parentNode");g(this,"target");g(this,"childNode");g(this,"follow",t=>{this.node.style.left=t.offsetX+15+"px",this.node.style.top=t.offsetY-30+"px"});g(this,"show",()=>this.node.hasAttribute("hidden")&&this.node.removeAttribute("hidden"));g(this,"hide",()=>!this.node.hasAttribute("hidden")&&this.node.setAttribute("hidden",""));g(this,"destroy",()=>{this.target?this.target.removeEventListener("mousemove",this.follow):document.removeEventListener("mousemove",this.follow),this.parentNode.removeChild(this.node)});this.node=document.createElement("div"),this.node.id=t,e&&this.node.append(e),this.childNode=document.createElement("div"),this.target=i?.target,this.parentNode=i?.parentNode||document.body,i?.followPointer&&(this.node.classList.add("follow-tooltip"),this.target?this.target.addEventListener("mousemove",this.follow):document.addEventListener("mousemove",this.follow)),this.parentNode.appendChild(this.node),!i?.showOnCreate&&this.node.setAttribute("hidden","")}setContent(t){this.node.textContent&&(this.node.textContent=null);for(let e=0;e<this.node.children.length;++e){const i=this.node.children[e];this.node.removeChild(i)}this.node.append(t),this.node.appendChild(this.childNode)}updateChildContent(t){this.childNode.textContent&&(this.childNode.textContent=null);for(let e=0;e<this.node.children.length;++e){const i=this.node.children[e];this.node.removeChild(i)}this.childNode.append(t)}}class Cu{constructor(t){g(this,"viewer");g(this,"active",!1);g(this,"tooltip");g(this,"resolve");g(this,"reject");g(this,"isResolvedOrRejected",!1);g(this,"mouseClicked",t=>{const e=t;if(e.markupData){const i=e.markupData.id,s=this.viewer.getOverlayRender().getDrawableById(i);if(s){let n=s.getBounds();n=n.clone().expandByScalar(20*this.viewer.getPixelSizeInWorldCoord());const r=Oe.world2NormalizedScreen(n.min,this.camera,this.viewerContainer),a=Oe.world2NormalizedScreen(n.max,this.camera,this.viewerContainer),o=new p.Box2(new p.Vector2(Math.min(r.x,a.x),Math.min(r.y,a.y)),new p.Vector2(Math.max(r.x,a.x),Math.max(r.y,a.y)));o.min.x=Math.max(o.min.x,0)*this.viewerContainer.clientWidth,o.min.y=Math.max(o.min.y,0)*this.viewerContainer.clientHeight,o.max.x=Math.min(o.max.x,1)*this.viewerContainer.clientWidth,o.max.y=Math.min(o.max.y,1)*this.viewerContainer.clientHeight,this.resolve&&(this.resolve(o),this.isResolvedOrRejected=!0),this.deactivate();const l=this.viewer;typeof l.clearSelection=="function"&&l.clearSelection()}}});g(this,"keydown",t=>{t.code==="Escape"&&this.deactivate()});this.viewer=t}get viewerContainer(){return this.viewer.viewerContainer}get camera(){return this.viewer.camera}isActive(){return this.active}activate(){if(this.isActive()){this.reject&&(this.deactivate(),this.reject("PickMarkupHelper is already actived!"),this.isResolvedOrRejected=!0);return}this.active=!0,this.viewer.addEventListener(le.MouseClick,this.mouseClicked),this.viewer.getInputManager()?.addEventListener("keydown",this.keydown),this.tooltip=new dl("pick-markup-tooltip",We.t("Tooltip.pickMarkup"),{followPointer:!0,showOnCreate:!0,parentNode:this.viewer.widgetContainer,target:this.viewerContainer});const t=document.getElementById("pick-markup-tooltip");t&&(t.style.pointerEvents="none");const e=We.t("Tooltip.pickMarkup");e&&this.tooltip&&this.tooltip?.setContent(e),this.viewer.dispatchEvent(le.PickMarkupActivate)}deactivate(){this.active=!1,this.viewer.removeEventListener(le.MouseClick,this.mouseClicked),this.viewer.getInputManager()?.removeEventListener("keydown",this.keydown),this.tooltip?.hide(),this.tooltip?.destroy(),this.tooltip=void 0,this.viewer.dispatchEvent(le.PickMarkupDeactivate),this.resolve&&!this.isResolvedOrRejected&&(this.resolve(void 0),this.isResolvedOrRejected=!0)}async pick(){return new Promise((t,e)=>{this.resolve=t,this.reject=e,this.activate()})}destroy(){this.deactivate(),!this.isResolvedOrRejected&&this.reject&&this.reject("PickMarkupHelper is not done for some reason!")}}const Bi=class Bi{constructor(t){g(this,"viewer");g(this,"input");g(this,"mouseDown",!1);g(this,"mouseMove",!1);g(this,"mouseDownPositionX",-1);g(this,"mouseDownPositionY",-1);g(this,"tempKey");g(this,"tempTouch");g(this,"tempEnableRotate",!1);g(this,"rectDom");g(this,"tooltip");g(this,"active",!1);g(this,"resolve");g(this,"reject");g(this,"isResolvedOrRejected",!1);g(this,"mousedown",t=>{if(t.button===0){this.mouseDown=!0;const e=new p.Vector2(t.x,t.y);this.mouseDownPositionX=e.x,this.mouseDownPositionY=e.y,this.tooltip?.hide(),this.tooltip?.destroy(),this.tooltip=void 0}});g(this,"mousemove",t=>{if(!this.mouseDown)return;const e=new p.Vector2(t.x,t.y);if(this.mouseDownPositionX>=0&&this.mouseDownPositionY>=0&&(Math.abs(e.x-this.mouseDownPositionX)>=5||Math.abs(e.y-this.mouseDownPositionY)>=5)){this.mouseMove=!0;const s=new p.Vector2(Math.min(this.mouseDownPositionX,e.x),Math.min(this.mouseDownPositionY,e.y)),n=new p.Vector2(Math.max(this.mouseDownPositionX,e.x),Math.max(this.mouseDownPositionY,e.y));this.drawRect(s,n)}});g(this,"mouseup",t=>{if(this.mouseDown&&this.mouseMove){const e=new p.Vector2(t.x,t.y),i=new p.Vector2(Math.min(this.mouseDownPositionX,e.x),Math.min(this.mouseDownPositionY,e.y)),s=new p.Vector2(Math.max(this.mouseDownPositionX,e.x),Math.max(this.mouseDownPositionY,e.y)),n=new p.Box2(i,s);this.resolve&&(this.resolve(n),this.isResolvedOrRejected=!0),this.deactivate(),this.setRectDomVisible(!1)}this.mouseDown=!1,this.mouseMove=!1,this.mouseDownPositionX=-1,this.mouseDownPositionY=-1});g(this,"keydown",t=>{t.code==="Escape"&&this.deactivate()});this.viewer=t,this.input=t.getInputManager()}get viewerContainer(){return this.viewer.viewerContainer}isActive(){return this.active}activate(){if(this.isActive()){this.reject&&(this.deactivate(),this.reject("BoxSelectHelper is already actived!"),this.isResolvedOrRejected=!0);return}this.active=!0,this.input.addEventListener("pointerdown",this.mousedown),this.input.addEventListener("pointermove",this.mousemove),this.input.addEventListener("pointerup",this.mouseup),this.input.addEventListener("keydown",this.keydown),this.viewer.getCameraManager().enableMouseLeft(!1),this.tooltip=new dl("box-select-tooltip",We.t("Tooltip.boxSelect"),{followPointer:!0,showOnCreate:!0,parentNode:this.viewer.widgetContainer,target:this.viewerContainer});const t=document.getElementById("box-select-tooltip");t&&(t.style.pointerEvents="none");const e=We.t("Tooltip.boxSelect");e&&this.tooltip&&this.tooltip?.setContent(e),this.viewer.dispatchEvent(le.BoxSelectActivate)}deactivate(){this.active=!1,this.input.removeEventListener("pointerdown",this.mousedown),this.input.removeEventListener("pointermove",this.mousemove),this.input.removeEventListener("pointerup",this.mouseup),this.input.removeEventListener("keydown",this.keydown),this.tooltip?.hide(),this.tooltip?.destroy(),this.tooltip=void 0,this.viewer.getCameraManager().enableMouseLeft(!0),this.viewer.dispatchEvent(le.BoxSelectDeactivate),this.resolve&&!this.isResolvedOrRejected&&(this.resolve(void 0),this.isResolvedOrRejected=!0)}drawRect(t,e){!this.rectDom&&(this.rectDom=document.createElement("div"),this.rectDom.style.cssText=`position: absolute;border: ${Bi.BORDER_WIDTH} solid ${Bi.BORDER_COLOR};`,this.viewerContainer.appendChild(this.rectDom)),this.setRectDomVisible(!0),this.rectDom.style.left=t.x+"px",this.rectDom.style.top=t.y+"px";const i=Math.abs(e.x-t.x),s=Math.abs(e.y-t.y);this.rectDom.style.width=i+"px",this.rectDom.style.height=s+"px"}setRectDomVisible(t){this.rectDom&&(this.rectDom.style.display=t?"inline-block":"none")}async select(){return new Promise((t,e)=>{this.resolve=t,this.reject=e,this.activate()})}destroy(){this.deactivate(),this.rectDom?.remove(),this.rectDom=void 0,!this.isResolvedOrRejected&&this.reject&&this.reject("BoxSelectHelper is not done for some reason!")}};g(Bi,"BORDER_COLOR","#fff000"),g(Bi,"BORDER_WIDTH","2px");let xn=Bi;class ul{constructor(t){g(this,"viewer");g(this,"boxSelectHelper");g(this,"active",!1);this.viewer=t,this.boxSelectHelper=new xn(t)}get viewerContainer(){return this.viewer.viewerContainer}get camera(){return this.viewer.camera}get raycaster(){return this.viewer.getRaycaster()}isActive(){return this.active}activate(){this.active=!0,this.boxSelectHelper?.select().then(t=>{t&&this.handleZoomToRect(t.min,t.max)})}deactivate(){this.active=!1,this.boxSelectHelper?.deactivate()}pickPositionByScreenPoint(t){return this.viewer.pickObject(t)?.point}handleZoomToRect(t,e){const i=this.pickPositionByScreenPoint(t),s=this.pickPositionByScreenPoint(e);if(i&&s){const n=new p.Vector3(Math.min(i.x,s.x),Math.min(i.y,s.y),Math.min(i.z,s.z)),r=new p.Vector3(Math.max(i.x,s.x),Math.max(i.y,s.y),Math.max(i.z,s.z)),a=new p.Box3(n,r);this.viewer.zoomToBBox(a)}}destroy(){this.boxSelectHelper?.destroy(),this.boxSelectHelper=void 0}}function lo(c){return c?c.replace(/%%[dD]/g,"°").replace(/%%[cC]/g,"⌀").replace(/%%[pP]/g,"±").replace(/%%(U|O)/gi,"").replace(/\\P/g," ").replace(/\\[A-Za-z][^;\\]*;/g,"").replace(/[{}]/g,"").replace(/\\\\/g,"\\").replace(/\\[uU]\+([0-9a-fA-F]{4})/g,(t,e)=>String.fromCodePoint(parseInt(e,16))).trim():""}const tn=new p.Box3,Su=new p.Vector3;function Eu(c,t){return c.trim().toLowerCase()===t?2e6:0}function Ou(c,t){const e=c.toLowerCase(),i=e.indexOf(t);if(i>=0)return(e===t?2e6:1e6)+(1e3-i)-Math.min(e.length,500);let s=0,n=-1,r=-1,a=0;for(let l=0;l<t.length;l++){const h=t[l];let d=-1;for(;s<e.length;s++)if(e[s]===h){d=s;break}if(d<0)return 0;n<0?n=d:r>=0&&d-r>1&&(a+=d-r-1),r=d,s=d+1}const o=5e5-a*50-n*5-Math.min(e.length,500);return o>0?o:1}class Mr{constructor(t){g(this,"viewer");g(this,"overlayRender");g(this,"drawableList");g(this,"indexedModelObject");g(this,"index",[]);this.viewer=t,this.overlayRender=this.viewer.getOverlayRender()}getMasterModel(){return this.viewer.loadedModels.find(t=>this.viewer.masterModelId===t.modelId)}invalidateIndex(){this.index=[],this.indexedModelObject=void 0}buildIndex(){const t=this.getMasterModel();if(!t){this.index=[],this.indexedModelObject=void 0;return}const e=t.getModelObject();if(e===this.indexedModelObject&&this.index.length>0)return;this.indexedModelObject=e,this.index=[];const i=new p.Matrix4,s=new p.Vector3,n=new Map;e.updateWorldMatrix(!0,!0);const r=(a,o,l,h,d)=>{if(a&&n.has(a)){n.get(a).box.union(d);return}n.set(a||o+h,{text:o,layer:l,layoutName:h,box:d.clone()})};e.traverse(a=>{const o=a.userData;if(o){if(typeof o.textContent=="string"&&o.textContent.length){const l=lo(o.textContent);if(!l||(tn.makeEmpty(),tn.setFromObject(a),tn.isEmpty()))return;r(o.handle||"",l,o.layer||"0",this.findLayoutName(a),tn);return}if(Array.isArray(o.batches)){const l=a.geometry?.getAttribute?.("position");if(!l)return;i.copy(a.matrixWorld);for(const h of o.batches){const d=h?.userData?.textContent;if(typeof d!="string"||!d.length)continue;const u=lo(d);if(!u)continue;const f=new p.Box3,m=h.positionStart||0,b=h.positionCount||0;for(let y=m;y<m+b;y++)s.fromBufferAttribute(l,y).applyMatrix4(i),f.expandByPoint(s);f.isEmpty()||r(h.userData.handle||"",u,h.userData.layer||"0",this.findLayoutName(a),f)}}}}),n.forEach((a,o)=>{this.index.push({handle:o,layer:a.layer,layoutName:a.layoutName,text:a.text,box:a.box})})}findLayoutName(t){let e=t;for(;e;){if(e.userData?.isLayoutLevelObject===!0)return e.name||"Model";e=e.parent}return"Model"}search(t,e){const i=(t||"").trim().toLowerCase();if(!i)return[];this.buildIndex();const s=e?.mode??"fuzzy",n=e?.layer?.trim().toLowerCase(),r=e?.maxResults??200,a=[];for(const o of this.index){if(n&&o.layer.toLowerCase()!==n)continue;const l=s==="exact"?Eu(o.text,i):Ou(o.text,i);l>0&&a.push({item:o,score:l})}return a.sort((o,l)=>l.score-o.score),a.slice(0,r).map(o=>o.item)}focus(t){if(!t)return;this.viewer.activateLayout(t.layoutName),this.highlight(t);const e=t.box.clone();this.viewer.zoomToBBox(e.expandByScalar(Math.max(e.getSize(Su).length()*.5,1)))}highlight(t){this.overlayRender&&(!this.drawableList&&(this.drawableList=new ws("text-search"),this.overlayRender.addDrawableList(this.drawableList)),this.clearHighlight(),this.drawableList.addDrawable(new wt(j.guid(),[t.box.clone()],[1,.55,0,1],[1,.55,0,.15])),this.viewer.enableRender())}clearHighlight(){this.drawableList?.clear(),this.viewer.enableRender()}invalidate(){this.indexedModelObject=void 0,this.index=[]}destroy(){this.clearHighlight(),this.overlayRender=void 0,this.drawableList=void 0,this.index=[],this.indexedModelObject=void 0}}class _u extends Nt{constructor(e){super("MobileHelper");g(this,"position");g(this,"needsFrustumCulled");g(this,"renderOrder");this.needsFrustumCulled=!1,this.renderOrder=1e3,this.position=e}setPosition(e){this.position=e}isPointInPath(e,i){return!1}draw(e,i){this.drawInnerCircle(e),this.drawOuterRing(e),this.drawSnapTriangle(e)}drawInnerCircle(e){const{x:i,y:s}=this.position;e.save(),e.fillStyle="rgba(137, 137, 138, 0.8)",e.beginPath(),e.arc(i,s,25,0,Math.PI*2),e.closePath(),e.fill(),e.restore()}drawOuterRing(e){const{x:i,y:s}=this.position;e.save(),e.strokeStyle="rgba(17, 17, 19, 0.8)",e.lineWidth=10,e.beginPath(),e.arc(i,s,30,0,Math.PI*2),e.closePath(),e.stroke(),e.restore(),e.save(),e.strokeStyle="rgba(173, 173, 174, 0.8)",e.lineWidth=3,e.beginPath(),e.arc(i,s,35,0,Math.PI*2),e.closePath(),e.stroke(),e.restore()}drawSnapTriangle(e){const{x:i,y:s}=this.position;e.save(),e.fillStyle="rgba(17, 17, 19, 0.8)",e.strokeStyle="rgba(137, 137, 138, 0.8)",e.lineWidth=2,e.beginPath(),e.moveTo(i-35,s-35),e.lineTo(i-35+12,s-35),e.lineTo(i-35,s-35+12),e.closePath(),e.fill(),e.stroke(),e.restore()}translate(e,i){this.position.add(new p.Vector2(e,i))}getTouchPoint(){return{x:this.position.x-35,y:this.position.y-35}}isIntersect(e){return this.position.x-35<e.x&&this.position.y-35<e.y&&this.position.x+35>e.x&&this.position.y+35>e.y}drawSelect(e,i){}getClassType(){return"MobileTouchHelperDrawable"}}var Je=(c=>(c[c.Left=0]="Left",c[c.Middle=1]="Middle",c[c.Right=2]="Right",c[c.Back=3]="Back",c[c.Forward=4]="Forward",c))(Je||{});class fl extends Ht{constructor(e){super();g(this,"element");g(this,"enabled");g(this,"keyboardEnabled");g(this,"mouseDownPositionX");g(this,"mouseDownPositionY");g(this,"lastLeftPointerUpTime");g(this,"pointers");g(this,"handleClick");g(this,"handlePointerDown");g(this,"handlePointerMove");g(this,"handlePointerUp");g(this,"handlePointerCancel");g(this,"handleMouseWheel");g(this,"handleContextMenu");g(this,"handlePointerEnter");g(this,"handlePointerLeave");g(this,"handleResize");g(this,"handleKeydown");g(this,"handleKeyup");g(this,"style");this.enabled=!0,this.keyboardEnabled=!0,this.mouseDownPositionX=0,this.mouseDownPositionY=0,this.lastLeftPointerUpTime=0,this.pointers=[],this.handleClick=i=>{if(!this.enabled)return;const s=this.getBaseEvent(i);this.dispatchEvent("click",s)},this.handlePointerDown=i=>{if(!this.enabled)return;this.stop(i);const s=this.getBaseEvent(i);this.isDoubleClick(s)?(this.lastLeftPointerUpTime=0,this.mouseDownPositionX=-1,this.mouseDownPositionY=-1,this.dispatchEvent("dblclick",s)):(this.mouseDownPositionX=s.x,this.mouseDownPositionY=s.y),this.dispatchEvent("pointerdown",s),i.pointerType==="touch"?(this.pointers.push(s),s.pointers=this.pointers,this.dispatchEvent("touchstart",s)):this.dispatchEvent("mousedown",s)},this.handlePointerMove=i=>{if(!this.enabled)return;this.stop(i);const s=this.getBaseEvent(i);this.isCloseToLastPosition(s)||(this.dispatchEvent("pointermove",s),i.pointerType==="touch"?(this.updatePointers(s),s.pointers=this.pointers,this.dispatchEvent("touchmove",s)):this.dispatchEvent("mousemove",s))},this.handlePointerUp=i=>{if(!this.enabled)return;this.stop(i);const s=this.getBaseEvent(i);s.button===0&&(this.lastLeftPointerUpTime=s.timestamp),this.dispatchEvent("pointerup",s),i.pointerType==="touch"?(this.removePointers(s),s.pointers=this.pointers,this.dispatchEvent("touchend",s)):this.dispatchEvent("mouseup",s)},this.handlePointerCancel=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("pointercancel",this.getBaseEvent(i)))},this.handleMouseWheel=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("wheel",this.getBaseEvent(i)))},this.handleContextMenu=i=>{if(this.enabled)return this.stop(i),this.dispatchEvent("contextmenu",this.getBaseEvent(i)),!1},this.handlePointerEnter=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("pointerenter",this.getBaseEvent(i)))},this.handlePointerLeave=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("pointerleave",this.getBaseEvent(i)))},this.handleResize=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("resize",this.getBaseEvent(i)))},this.handleKeydown=i=>{!this.enabled||!this.keyboardEnabled||this.dispatchEvent("keydown",this.getBaseEvent(i))},this.handleKeyup=i=>{!this.enabled||!this.keyboardEnabled||this.dispatchEvent("keyup",this.getBaseEvent(i))},this.style={},this.element=e,this.bindEvents()}getEnabled(){return this.enabled}setEnabled(e){this.enabled=e}getkKeyboardEnabled(){return this.keyboardEnabled}setkKeyboardEnabled(e){this.keyboardEnabled=e}setCursor(e){this.element.style&&(this.element.style.cursor=e||"default")}bindEvents(){this.element.style.touchAction="none",this.element.style.userSelect="none",this.element.style.webkitUserSelect="none",this.element.addEventListener("click",this.handleClick),this.element.addEventListener("pointerdown",this.handlePointerDown),this.element.addEventListener("pointermove",this.handlePointerMove),this.element.addEventListener("pointerup",this.handlePointerUp),this.element.addEventListener("pointercancel",this.handlePointerCancel),this.element.addEventListener("pointerenter",this.handlePointerEnter),this.element.addEventListener("pointerleave",this.handlePointerLeave),this.element.addEventListener("contextmenu",this.handleContextMenu),this.element.addEventListener("wheel",this.handleMouseWheel,{passive:!1}),window.addEventListener("resize",this.handleResize),window.addEventListener("keydown",this.handleKeydown),window.addEventListener("keyup",this.handleKeyup)}unBindEvents(){this.element.removeEventListener("pointerdown",this.handlePointerDown),this.element.removeEventListener("pointermove",this.handlePointerMove),this.element.removeEventListener("pointerup",this.handlePointerUp),this.element.removeEventListener("pointerenter",this.handlePointerEnter),this.element.removeEventListener("pointerleave",this.handlePointerLeave),this.element.removeEventListener("contextmenu",this.handleContextMenu),this.element.removeEventListener("wheel",this.handleMouseWheel),window.removeEventListener("resize",this.handleResize),window.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("keyup",this.handleKeyup),this.element.style.touchAction="",this.element.style.userSelect="",this.element.style.webkitUserSelect=""}getBaseEvent(e){const i=e,s={x:0,y:0,pageX:0,pageY:0,clientX:0,clientY:0,deltaX:0,deltaY:0,movementX:0,movementY:0,deltaMode:0,pointerId:0,timestamp:0,buttons:0,pointerType:"mouse",altKey:!1,ctrlKey:!1,shiftKey:!1,metaKey:!1,originalEvent:i};if(s.timestamp=i.timeStamp,sn(i,"clientX"))if(s.altKey=i.altKey,s.ctrlKey=i.ctrlKey,s.shiftKey=i.shiftKey,s.clientX=i.clientX,s.clientY=i.clientY,s.button=i.button,sn(i,"pointerId")){s.pointerType=i.pointerType,s.buttons=i.buttons,s.pageX=i.pageX,s.pageY=i.pageY,s.pointerId=i.pointerId;const n=Oe.getScreenCoordinateByEvent(i,this.element);s.x=n.x,s.y=n.y,s.movementX=i.movementX,s.movementY=i.movementY}else sn(i,"deltaX")&&(s.deltaMode=i.deltaMode,s.deltaX=i.deltaX,s.deltaY=i.deltaY);else sn(i,"code")&&(s.altKey=i.altKey,s.ctrlKey=i.ctrlKey,s.shiftKey=i.shiftKey,s.metaKey=i.metaKey,s.code=i.code);return s}stop(e){e.preventDefault()}updatePointers(e){for(let i=0;i<this.pointers.length;i++)if(e.pointerId==this.pointers[i].pointerId){this.pointers[i]=e;break}}removePointers(e){for(let i=0;i<this.pointers.length;i++)if(this.pointers[i].pointerId==e.pointerId){this.pointers.splice(i,1);break}}getBoundingClientRect(){return this.element.getBoundingClientRect()}isCloseToLastPosition(e){return this.mouseDownPositionX===-1||this.mouseDownPositionY===-1?!1:Math.abs(e.x-this.mouseDownPositionX)<5&&Math.abs(e.y-this.mouseDownPositionY)<5}isDoubleClick(e){const s=e.timestamp-this.lastLeftPointerUpTime;return!!(e.button===0&&s<300&&this.isCloseToLastPosition(e))}}function sn(c,t){return c[t]!==void 0}class Pu{constructor(t){g(this,"CLEAR_COLOR");g(this,"CLEAR_COLOR_ALPHA");g(this,"EMPTY_MODEL_ID");g(this,"viewer");g(this,"raycaster");g(this,"pickingTexture");this.CLEAR_COLOR=new p.Color().setRGB(1,1,1),this.CLEAR_COLOR_ALPHA=1,this.EMPTY_MODEL_ID=255,this.viewer=t,this.raycaster=new p.Raycaster,this.pickingTexture=new p.WebGLRenderTarget(1,1)}get scene(){return this.viewer.scene}get camera(){return this.viewer.camera}get renderer(){return this.viewer.renderer}get overlayRender(){return this.viewer.getOverlayRender()}get viewerContainer(){return this.viewer.viewerContainer}getRaycaster(){return this.raycaster}pickObjectsByNdc(t,e,i){return!e||e.length===0?[]:(this.raycaster.setFromCamera(t,this.camera),this.setLayerChannels(i),this.raycaster.intersectObjects(e,!0)||[])}pickObject(t,e,i,s){const n=this.pickObjects(t,e,i,s);if(n.length!==0)return n[0]}pickObjects(t,e,i,s=0){const n=Oe.screen2Ndc(t,this.camera,this.viewerContainer);if(s>0){const r=[],a=new Map,o=Oe.screen2Ndc(t,this.camera,this.viewerContainer),l=Oe.screen2Ndc({x:t.x+s,y:t.y},this.camera,this.viewerContainer),h=new p.Vector3(o.x,o.y,0).unproject(this.camera),d=new p.Vector3(l.x,l.y,0).unproject(this.camera),u=h.distanceTo(d),f=this.raycaster.params.Line.threshold;this.raycaster.params.Line.threshold=u,this.setLayerChannels(i);const m=8;for(let y=0;y<m;y++){const S=y/m*Math.PI*2,w=Math.cos(S)*s,x=Math.sin(S)*s,E={x:t.x+w,y:t.y+x},M=Oe.screen2Ndc(E,this.camera,this.viewerContainer);this.raycaster.setFromCamera(M,this.camera),this.raycaster.layers.enableAll();const O=this.raycaster.intersectObjects(e,!0)||[];for(const T of O)T.object&&!a.has(T.object.uuid)&&(a.set(T.object.uuid,T),r.push(T))}this.raycaster.setFromCamera(o,this.camera);const b=this.raycaster.intersectObjects(e,!0)||[];for(const y of b)y.object&&!a.has(y.object.uuid)&&(a.set(y.object.uuid,y),r.push(y));if(this.raycaster.params.Line.threshold=f,r.length>1){const y=this.raycaster.ray.origin.clone();r.sort((S,w)=>{const x=S.point||S.object.getWorldPosition(new p.Vector3),E=w.point||w.object.getWorldPosition(new p.Vector3);return x.distanceTo(y)-E.distanceTo(y)})}return r}return this.pickObjectsByNdc(n,e,i)}pickDrawable(t){return this.overlayRender.getDrawablesByPosition(t)}pick(t,e){const i=this.pickBuffer(t,e),s=[i[0],i[1],i[2],i[3]],n=Z1(s),r=K1(s);if(n!==this.EMPTY_MODEL_ID)return P.info("[PickMgr] Picked: tilesetId("+n+"), userId("+r+")"),{tilesetId:n,userId:r}}setLayerChannels(t){t&&t.length>0?(this.raycaster.layers.disableAll(),t.forEach(e=>{this.raycaster.layers.enable(e)})):this.raycaster.layers.enableAll()}pickBuffer(t,e,i=1,s=1){const{pickingTexture:n,renderer:r,camera:a}=this;n.setSize(i,s);const o=r.getPixelRatio(),l=r.getContext().drawingBufferWidth,h=r.getContext().drawingBufferHeight,d=t.x*o|0,u=t.y*o|0;a.setViewOffset(l,h,d,u,i,s),r.setRenderTarget(n);const f=new p.Color;r.getClearColor(f);const m=r.getClearAlpha();r.setClearColor(this.CLEAR_COLOR,this.CLEAR_COLOR_ALPHA),r.render(e,a);const b=new Uint8Array(4*i*s);return r.readRenderTargetPixels(n,0,0,i,s,b),r.setRenderTarget(null),a.clearViewOffset(),r.setClearColor(f,m),b}}const co=new p.Vector3;class Au{constructor(t){g(this,"viewer");g(this,"scene");g(this,"renderer");g(this,"pmremGenerator");g(this,"lights");g(this,"modelGroup");this.viewer=t;const e=new p.Scene;e.matrixAutoUpdate=et,e.matrixWorldAutoUpdate=et,this.scene=e,this.modelGroup=new p.Group,this.modelGroup.name="models",this.scene.add(this.modelGroup);const{width:i,height:s,viewerContainer:n}=t.container;let r;try{r=new p.WebGLRenderer({antialias:!0,preserveDrawingBuffer:!0})}catch{try{r=new p.WebGLRenderer,P.warn("WebGL context created with fallback settings (antialias disabled).")}catch(o){throw this.showWebGLUnavailable(n),new Error("WebGLUnavailable: failed to create WebGL context. "+o.message)}}r.setPixelRatio(window.devicePixelRatio),r.setSize(i,s),r.outputColorSpace=p.SRGBColorSpace,r.toneMappingExposure=1,r.localClippingEnabled=!0,r.shadowMap.enabled=!1,r.shadowMap.type=p.PCFSoftShadowMap,r.shadowMap.autoUpdate=!1,r.domElement.style.outlineWidth="0",n?.appendChild(r.domElement),this.renderer=r,j.printGpuInfo(r.getContext())}showWebGLUnavailable(t){if(!t)return;const e=document.createElement("div");e.style.cssText=["position:absolute","left:0","top:0","width:100%","height:100%","display:flex","align-items:center","justify-content:center","text-align:center","padding:0 24px","box-sizing:border-box","background:rgba(255,255,255,0.95)","color:#333","font-size:14px","line-height:1.8","z-index:9999"].join(";"),e.textContent=We.t("WebGL.NotAvailable"),t.appendChild(e)}initLights(){const t=new p.Group;t.name="lights";const e=1.5,i=16777215,s=new p.DirectionalLight(i,e);s.name="sun",s.castShadow=!0,s.position.set(-2,2,4),s.shadow.autoUpdate=!1,s.shadow.mapSize.width=1024,s.shadow.mapSize.height=1024;const n=new p.AmbientLight(i);n.name="ambient";const r=new p.HemisphereLight(i,14540253,.2);r.name="hemisphere",r.position.set(0,300,0);const a=new p.Group;a.name="lightHelpers",a.visible=!1;const o=new p.DirectionalLightHelper(s),l=new p.CameraHelper(s.shadow.camera);return a.add(o),a.add(l),t.add(s),t.add(s.target),t.add(n),t.add(r),t.add(a),this.scene.add(t),this.lights=t,t}initPMREMGenerator(){this.pmremGenerator=new p.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader()}get maxFragmentUniforms(){return this.renderer.capabilities.maxFragmentUniforms-20}addModel(t){this.modelGroup.add(t.getModelObject())}removeModel(t){this.modelGroup.remove(t.getModelObject())}enableShadow(t){this.renderer.shadowMap.enabled=t,this.directionalLight.castShadow=t,t&&(this.tryAdjustDirectionalLight(),this.updateDirectionalLightShadow()),this.modelGroup.traverse(e=>{e.isMesh&&(e.castShadow=t,e.receiveShadow=t)})}enableClipping(t){this.renderer.localClippingEnabled=t}setClipPlanes(t){this.renderer.clippingPlanes=t}enableLights(t){let e=this.lights;e||(e=this.initLights()),e.visible=t}debugLights(t){!this.lights||!this.lightHelpers||(this.lightHelpers.visible=t)}setBackground(t){this.scene.background=t}get directionalLight(){return this.lights?.getObjectByName("sun")}get ambientLight(){return this.lights?.getObjectByName("ambient")}get hemisphereLight(){return this.lights?.getObjectByName("hemisphere")}get lightHelpers(){return this.lights?.getObjectByName("lightHelpers")}get directionalLightHelper(){let t;for(let e=0;this.lightHelpers&&e<this.lightHelpers?.children.length;++e){const i=this.lightHelpers.children[e];if(i instanceof p.DirectionalLightHelper){t=i;break}}return t}get cameraHelper(){let t;for(let e=0;this.lightHelpers&&e<this.lightHelpers?.children.length;++e){const i=this.lightHelpers.children[e];i instanceof p.CameraHelper&&(t=i)}return t}async setEnvironmentFromData(t){this.pmremGenerator||this.initPMREMGenerator();const e=await ms.createEnvTextureFromDataArray(this.pmremGenerator,t);this.scene.environment=e}async setEnvironment(t){this.pmremGenerator||this.initPMREMGenerator();const e=await ms.createEnvTexture(this.pmremGenerator,t);this.scene.environment?.dispose(),this.scene.environment=e}resize(){const{width:t,height:e}=this.viewer.container;this.renderer.setSize(t,e)}getRaycastableObjects(){const t=[];return this.modelGroup.traverse(e=>{t.push(e)}),t}tryAdjustDirectionalLight(){const t=this.directionalLight;if(!t)return;const e=this.viewer.getBBox(),i=new p.Sphere;e.getBoundingSphere(i);const s=i.center,n=i.radius,r=t.shadow.camera;r.zoom=1,r.top=n,r.bottom=-n,r.right=n,r.left=-n,r.near=.1,r.far=2*n,r.updateProjectionMatrix();const a=new p.Vector3(-1,-.5,1);a.normalize().multiplyScalar(n),t.position.copy(s).addScaledVector(a,-1),t.target.position.copy(s),P.debug("[Scene] directionalLight.position",t.position),P.debug("[Scene] directionalLight.target.position",t.target.position),this.updateDirectionalLight(),this.viewer.enableRender()}updateDirectionalLight(){const t=this.directionalLight;if(t&&(t.updateMatrixWorld(),t.target.updateMatrixWorld(),this.directionalLightHelper&&(this.directionalLightHelper.update(),this.scene?.matrixAutoUpdate||this.directionalLightHelper.updateWorldMatrix(!1,!0)),t.shadow.needsUpdate=!0,t.shadow.camera.updateProjectionMatrix(),this.cameraHelper&&(this.cameraHelper.update(),!this.scene?.matrixAutoUpdate))){const e=t.shadow.camera;e.position.setFromMatrixPosition(t.matrixWorld),co.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(co),e.updateMatrixWorld(),this.cameraHelper.updateWorldMatrix(!1,!0)}}updateDirectionalLightShadow(){this.directionalLight&&(this.directionalLight.shadow.needsUpdate=!0)}showDirectionalLightHelper(t){this.directionalLightHelper&&(this.directionalLightHelper.visible=t),this.cameraHelper&&(this.cameraHelper.visible=t)}destroy(){this.lightHelpers?.clear(),this.lightHelpers?.removeFromParent(),this.lightHelpers?.traverse(t=>{t.dispose?.call(t)}),this.lights?.clear(),this.lights?.removeFromParent(),this.lights?.traverse(t=>{t.dispose?.call(t)}),this.lights=void 0,this.pmremGenerator?.dispose(),this.renderer.domElement.remove(),this.renderer.clear(),this.renderer.dispose(),this.renderer.forceContextLoss(),this.scene.clear()}}class Iu{constructor(t){g(this,"history");g(this,"step");g(this,"maxCount");g(this,"isBatchCommand");g(this,"batchCommands");this.history=[],this.step=0,this.maxCount=50,this.isBatchCommand=!1,this.batchCommands=[],this.maxCount=t||this.maxCount}addCommand(t){this.isBatchCommand?this.batchCommands.push(t):(this.history.length===this.maxCount&&this.history.shift(),this.step!==this.history.length&&this.history.splice(this.step),this.history.push(t),this.step++)}startTransaction(){this.isBatchCommand=!0}endTransaction(){this.history.length===this.maxCount&&this.history.shift(),this.step!==this.history.length&&this.history.splice(this.step),this.batchCommands.length>0&&(this.history.push(this.batchCommands.slice()),this.step++),this.isBatchCommand=!1,this.batchCommands=[]}undo(){if(this.canUndo())return!1;this.step--;const t=this.history[this.step];return t&&(Array.isArray(t)?t.forEach(e=>e.undo()):t.undo()),!0}redo(){if(this.canRedo())return!1;this.step++;const t=this.history[this.step-1];return t&&(Array.isArray(t)?t.forEach(e=>e.redo()):t.redo()),!0}getCommands(){return this.history}canUndo(){return this.step<=0}canRedo(){return this.step>=this.history.length}clear(){this.history=[],this.step=0}destroy(){this.clear(),this.maxCount=0}}class Mn extends Ht{constructor(e){super();g(this,"name");g(this,"viewerCfg");g(this,"clock");g(this,"targetMaxFps");g(this,"timeStamp");g(this,"renderEnabled");g(this,"requestAnimationFrameHandle");g(this,"container");g(this,"plugins");g(this,"loadedModels");g(this,"raf");g(this,"timeoutSymbol");g(this,"homeView");g(this,"inputManager");g(this,"cameraManager");g(this,"sceneManager");g(this,"fontManager");g(this,"pickManager");g(this,"undoManager");g(this,"overlayRender");g(this,"css2dRenderer");g(this,"spinner");g(this,"progressBar");g(this,"loaderHelper");g(this,"zoomToRectHelper");g(this,"_enableSelection");g(this,"enableRender");this.name=$e.BaseViewer,this.clock=new p.Clock,this.targetMaxFps=60,this.timeStamp=0,this.renderEnabled=!0,this.plugins=[],this.loadedModels=[],this.raf=new ol,this._enableSelection=!0,this.enableRender=(i=1e3)=>{this.renderEnabled=!0,this.raf&&(this.timeoutSymbol&&this.raf.clearTimeout(this.timeoutSymbol),this.timeoutSymbol=this.raf.setTimeout(()=>{this.renderEnabled=!1},i))},this.viewerCfg=e,this.initLogLevel(),this.initLocalization(),this.container=new Rr(e.containerId),e.enableProgressBar&&(this.progressBar=new Fr(this.container)),this.spinner=new tl(this.container),this.sceneManager=new Au(this),this.pickManager=new Pu(this),this.overlayRender=new bs(this),this.css2dRenderer=this.initCSS2DRenderer(),this.inputManager=new fl(this.viewerContainer),this.cameraManager=new ou(this),this.loaderHelper=new Vt,this.undoManager=new Iu,this.resize(),this.clock.start(),this.animate()}initLogLevel(){const e=this.viewerCfg.logLevel;e&&To(e)}initLocalization(){const e=this.viewerCfg.language||So;We.changeLanguage(e)}get viewerContainer(){return this.container.viewerContainer}get widgetContainer(){return this.container.widgetContainer}getUndoManager(){return this.undoManager}getInputManager(){return this.inputManager}getCssRender(){return this.css2dRenderer}getCameraManager(){return this.cameraManager}getOverlayRender(){return this.overlayRender}getSceneManager(){return this.sceneManager}get renderer(){return this.sceneManager.renderer}get camera(){return this.cameraManager.camera}get scene(){return this.sceneManager.scene}getRaycaster(){return this.pickManager.getRaycaster()}getViewerConfig(){return this.viewerCfg}getSpinner(){return this.spinner}getFontManager(){return this.fontManager}initCSS2DRenderer(){const e=new yo.CSS2DRenderer,{width:i,height:s}=this.viewerContainer.getBoundingClientRect();return e.setSize(i,s),e.domElement.style.height="0",e.domElement.style.width="0",e.domElement.style.position="absolute",e.domElement.style.top="0",e.domElement.style.left="0",e.domElement.style.overflow="visible",e.domElement.classList.add("css2d-renderer"),this.viewerContainer?.appendChild(e.domElement),e}animate(){const e=Date.now()-this.timeStamp,i=1/this.targetMaxFps;if(e<i){this.requestAnimationFrameHandle=requestAnimationFrame(this.animate.bind(this));return}const s=this.cameraManager.update(this.clock.getDelta());this.container.needResize&&(this.resize(),this.renderEnabled=!0),(this.renderEnabled||s)&&(this.dispatchEvent(le.BeforeRender),this.renderer.render(this.scene,this.camera),this.css2dRenderer.render(this.scene,this.camera),this.dispatchEvent(le.AfterRender),this.renderEnabled=!1),this.requestAnimationFrameHandle=requestAnimationFrame(this.animate.bind(this)),this.timeStamp=Date.now(),this.dispatchEvent(le.OnAnimate)}resize(){this.sceneManager.resize(),this.cameraManager.updateAspect();const{clientWidth:e,clientHeight:i}=this.viewerContainer;this.css2dRenderer.setSize(e,i),this.overlayRender.setSize(e,i)}setDracoDecoderPath(e){Vt.setDracoDecoderPath(e)}addModel(e){const i=e.getModelObject();i.name=e.modelId,this.sceneManager.addModel(e),i.matrixAutoUpdate=et,i.updateMatrix(),i.updateMatrixWorld(!0),this.loadedModels.push(e),this.enableRender(0)}async setFont(e){!this.fontManager&&(this.fontManager=new xt),await this.fontManager.loadFonts(e)}is3d(){return!1}getPixelSizeInWorldCoord(){const e=this.camera,{clientWidth:i,clientHeight:s}=this.viewerContainer;let n=1;if(e.type==="OrthographicCamera"){const r=e;n=Math.max(r.right-r.left,r.top-r.bottom)/r.zoom/Math.max(i,s)}else if(e.type==="PerspectiveCamera"){const r=e,a=new p.Vector3;e.getWorldPosition(a);const o=this.cameraManager.getTarget();a&&o&&(n=2*(a.distanceTo(o)*Math.tan(r.fov/2*(Math.PI/180)))/s)}return n}zoomToRect(){!this.zoomToRectHelper&&(this.zoomToRectHelper=new ul(this)),this.zoomToRectHelper.activate()}deactivateZoomRect(){this.zoomToRectHelper?.deactivate()}getUniqueModelId(e){let i=e;const s=n=>!!this.loadedModels.find(r=>r.modelId===n);if(s(i)){let n=1;for(;s(i+"_"+n);)n++;i=i+"_"+n,P.warn("[Viewer] Model '"+i+"' is loaded more than once!")}return i}getBBox(){const e=new p.Box3;return this.loadedModels.forEach(i=>{e.union(i.getBBox())}),e}flyToObject(e){this.cameraManager.flyToObject(e)}flyToObjects(e){const i=new p.Box3;e.forEach(n=>{const r=new p.Box3().setFromObject(n);i.union(r)});const s=new p.Sphere;i.getBoundingSphere(s),this.cameraManager.fitToSphere(s)}flyTo(e,i,s=!0){const n=this.camera;if(e.equals(i)){P.error("[Viewer] camera position and lookAt cannot be the same!");return}else if(!j.isVectorValid(e)||!j.isVectorValid(i)){P.error("[Viewer] invalid position or lookAt!");return}const r=e.distanceTo(i);r<n.near?(e=e.clone().sub(i).normalize().multiplyScalar(n.near*1.1),P.warn("[Viewer] camera could be too close to see the object!")):r>n.far&&(e=e.clone().sub(i).normalize().multiplyScalar(n.far*.9),P.warn("[Viewer] camera could be too far to see the object!")),this.cameraManager.flyTo(e,i,s)}flyToDirection(e){const i=this.getBBox(),s=i.getSize(new p.Vector3);let n=Math.max(s.x,s.y,s.z)/2;n===0&&(n=1);const r=this.cameraManager.getDistanceToFitSphere(n),a=new p.Vector3;i.getCenter(a);const o=a.clone().add(e.clone().multiplyScalar(r));this.flyTo(o,a)}goToHomeView(){if(this.homeView)this.cameraManager.flyToViewpoint(this.homeView);else{const e=new p.Vector3(1,.5,1);this.flyToDirection(e)}}viewFitAll(){const e=this.getBBox(),i=new p.Sphere;e.getBoundingSphere(i),this.cameraManager.fitToSphere(i)}zoomToBBox(e){this.cameraManager.flyToBox(e)}pickObject(e,i,s){let n=this.pickManager.pickObject(e,this.getRaycastableObjects(),i,s);return this.renderer&&this.renderer.clippingPlanes.length>0&&this.renderer?.clippingPlanes?.every(a=>{n&&a.distanceToPoint(n.point)>0})&&(n=void 0),n}pickObjects(e,i){let s=this.pickManager.pickObjects(e,this.getRaycastableObjects(),i);return s&&this.renderer.clippingPlanes.length>0&&(s=s.filter(n=>this.renderer.clippingPlanes.every(r=>r.distanceToPoint(n.point)>0))),s}getRaycastableObjects(){return this.sceneManager.getRaycastableObjects()}setBackgroundColor(e,i,s){if(!this.scene.background&&(this.scene.background=new p.Color(e,i,s)),this.scene.background instanceof p.Color){const n=new p.Color;n.setRGB(e,i,s,this.renderer.outputColorSpace),this.scene.background.copy(n)}this.enableRender()}setGlobalClipPlanes(e){}getCameraProjection(){return this.cameraManager.getProjection()}setCameraProjection(e){this.cameraManager.setProjection(e)}enableControl(e){this.cameraManager.enableControl(e)}enableRotate(e){this.cameraManager.enableRotate=e}enableZoom(e){this.cameraManager.enableZoom(e)}enablePan(e){this.cameraManager.enablePan(e)}getHomeView(){return this.homeView}setHomeView(e){this.homeView=e}getCameraConfig(){return this.cameraManager.getCameraConfig()}setCameraConfig(e){return this.cameraManager.setCameraConfig(e)}getCameraDirection(){return this.cameraManager.getCameraDirection()}getRenderInfo(){const e=this.renderer.info;return{drawCalls:e.render.calls,lines:e.render.lines,points:e.render.points,triangles:e.render.triangles,geometries:e.memory.geometries,textures:e.memory.textures,materials:e.programs?.length||0}}removeModel(e){const i=this.loadedModels.findIndex(n=>n.modelId===e);if(i===-1)return;const s=this.loadedModels.splice(i,1)[0];return this.sceneManager.removeModel(s),J.disposeObject(s.getModelObject()),this.enableRender(),s}destroy(){this.requestAnimationFrameHandle&&cancelAnimationFrame(this.requestAnimationFrameHandle),this.loaderHelper.abortDxfLoading(),this.css2dRenderer.domElement.remove(),this.container.destroy(),this.sceneManager.destroy(),this.cameraManager.destroy(),this.overlayRender.destroy(),this.spinner.destroy(),this.progressBar?.destroy(),this.undoManager.destroy()}addPlugin(e){if(this.plugins.find(s=>s.id===e.id)){P.warn("[Viewer] Plugin already exist: "+e.id);return}this.plugins.push(e),P.debug("[Viewer] Added plugin: "+e.id)}removePlugin(e){for(let i=0,s=this.plugins.length;i<s;i++)if(this.plugins[i]===e){this.plugins.splice(i,1);return}}clearPlugins(){this.plugins=[]}findPlugin(e){return this.plugins.find(i=>i.id===e)}}const pl=-1e3,Mi=new p.Vector3,ho=new p.Matrix4,uo=new p.Frustum,nr=new p.Box3,fo=new p.Matrix4;class Vr extends Mn{constructor(e){super(e);g(this,"name");g(this,"loadedModels");g(this,"masterModelId");g(this,"activeLayoutName");g(this,"dxfLayoutBar");g(this,"layoutInfos");g(this,"units");g(this,"enableHideVisuallySmallObjects");g(this,"sortedHidableObjects");g(this,"lastCameraZoom");g(this,"groundPlane");g(this,"raycastableObjects");g(this,"selectedObject");g(this,"loadingDxfCount");g(this,"textSearchHelper");g(this,"clickHighlightList");g(this,"_enableClickHighlight",!1);g(this,"requestHeaders");g(this,"_printCaptureMode",!1);this.name=$e.Viewer2d,this.loadedModels=[],this.masterModelId="",this.activeLayoutName="",this.layoutInfos={},this.units=void 0,this.enableHideVisuallySmallObjects=e.enableHideVisuallySmallObjects===!0,this.sortedHidableObjects={},this.lastCameraZoom=1/0,this.loadingDxfCount=0,e.enableLayoutBar&&(this.dxfLayoutBar=new tu(this)),this.cameraManager.setProjection(bt.Orthographic),this.cameraManager.setNavigationMode(lt.Plan);const i=new p.Vector3(0,0,100),s=new p.Vector3(0,0,0);this.cameraManager.setCameraConfig({eye:i,look:s}),this.resize(),this.setupDefaultEvents(),this.setDefaultBackground(),this.addEventListener(le.BeforeRender,()=>{this.updateRaycasterThreshold(),this.updateCameraZoomUniform(this.camera.zoom),this.updateHidableObjectsVisibility()})}get camera(){return this.cameraManager.camera}setupDefaultEvents(){let e=!1,i=!1;this.inputManager.addEventListener("pointerdown",s=>{i=!1,e=!0,s.button===Je.Middle&&this.inputManager?.setCursor("move")}),this.inputManager.addEventListener("pointermove",()=>{e&&(i=!0,this.inputManager?.setCursor("move"))}),this.inputManager.addEventListener("pointerup",s=>{if(e=!1,this.inputManager?.setCursor("default"),i){i=!1;return}const n=new p.Vector2(s.x,s.y),r=this.getWorldPositionByMousePick(n),a=this.pickManager.pickObjects(n,this.getRaycastableObjects(),void 0,3);let o;for(const d of a){const u=this.resolveEntityFromPick(d);if(u){u.hit=d,o=u;break}}const l=o?.userData;if(this._enableClickHighlight&&o){const d=this.getEntityBoundingBox(o);d&&this.highlightEntityBox(d)}else this.clearClickHighlight();const h={event:s,position:n,worldPosition:r,pooo:r,entity:l?o?.object:void 0,object:l?o?.object:void 0,point:l?o?.hit?.point:void 0,userData:l,handle:l?.handle};this.dispatchEvent(le.MouseClick,h)})}resolveEntityFromPick(e){if(!e)return;const i=e.object,s=i.userData?.batches;if(s&&s.length>0){const r=i.geometry,a=i.isMesh===!0,o=e.index;let l;a&&typeof e.faceIndex=="number"&&(l=r?.index?r.index.getX(e.faceIndex*3):e.faceIndex*3);const h=s.find(d=>{const u=typeof o=="number"&&o>=d.indexStart&&o<d.indexStart+(d.indexCount||1),f=typeof o=="number"&&o>=d.positionStart&&o<d.positionStart+d.positionCount||typeof l=="number"&&l>=d.positionStart&&l<d.positionStart+d.positionCount;return u||f});if(h?.userData)return{userData:h.userData,batch:h,object:i}}let n=i;for(;n;){if(n.userData?.handle)return{userData:n.userData,object:n};n=n.parent??void 0}}getEntityBoundingBox(e){const i=e.object,s=i.geometry?.getAttribute?.("position");if(e.batch&&s){const r=new p.Box3,a=e.batch.positionStart||0,o=e.batch.positionCount||0;if(o>0){i.updateWorldMatrix(!0,!1),fo.copy(i.matrixWorld);for(let l=a;l<a+o&&l<s.count;l++)Mi.fromBufferAttribute(s,l).applyMatrix4(fo),r.expandByPoint(Mi);if(!r.isEmpty())return r}}const n=new p.Box3;return n.setFromObject(i),n.isEmpty()?void 0:n}highlightEntityBox(e){const i=this.getOverlayRender();i&&(!this.clickHighlightList&&(this.clickHighlightList=new ws("entity-click-highlight"),i.addDrawableList(this.clickHighlightList)),this.clickHighlightList.clear(),this.clickHighlightList.addDrawable(new wt(j.guid(),[e.clone()],[.031,.906,.867,1],[.031,.906,.867,.15])),this.enableRender())}get enableClickHighlight(){return this._enableClickHighlight}set enableClickHighlight(e){this._enableClickHighlight=e,e||this.clearClickHighlight()}clearClickHighlight(){this.clickHighlightList?.clear(),this.enableRender()}setRequestHeaders(e){this.requestHeaders=e}handleMouseClick(e){if(!this.enableSelection)return;const i=new p.Vector2(e.x,e.y),s=this.getWorldPositionByMousePick(i);if(!s)return;const n=this.overlayRender.getDrawablesByPosition(s)[0];if(n){this.selectedObject===n?(this.selectedObject.selected=!1,this.selectedObject=void 0):(this.selectedObject&&this.clearSelection(),this.selectedObject=n,this.selectedObject.selected=!0),this.enableRender();return}const r=this.pickObject(i,[Ut]);if(r){const a=r?.object;this.selectedObject===a?(this.setObjectUnHighlight(this.selectedObject),this.selectedObject=void 0):(this.selectedObject&&this.clearSelection(),this.selectedObject=a,this.setObjectHighlight(this.selectedObject)),this.enableRender();return}this.clearSelection(),this.enableRender()}setDefaultBackground(){this.setBackgroundColor(.0295,.0212,.0152)}async loadModel(e,i,s){this.loaderHelper.abortDxfLoading();const n=this.getUniqueModelId(e.modelId||e.src);this.spinner.increaseJobCount(),this.loaderHelper.setFont(this.fontManager),this.masterModelId||(this.masterModelId=n);const r=n,a=We.t("ProgressBar.Loading"),o=d=>{this.progressBar?.updateProgress(r,a,d),i?.(new ProgressEvent("LoadProgress",{loaded:d,total:100}))},l=(d,u,f)=>{let m=d.loaded*100/d.total;m=m*(f-u)/100+u,this.progressBar?.updateProgress(r,a,m),i?.(new ProgressEvent("LoadProgress",{loaded:m,total:100}))},h=d=>l(d,0,90);this.progressBar?.addProgressItem(r),o(0);try{this.loadingDxfCount++;const d=this.viewerCfg,u=await this.loaderHelper.loadDxfData(e.src,e.modelId,h,void 0,{ignorePaperSpace:e.ignorePaperSpace,enableLocalCache:d.enableLocalCache,enableMerge:e.merge,encoding:e.encoding,overrideColor:e.overrideColor,requestHeaders:e.headers??this.requestHeaders}).finally(()=>{this.loadingDxfCount--,this.loadingDxfCount===0&&this.fontManager?.releaseFontData()}),f=u.threejsObject;if(s&&s({threejsObject:f,llbMesh:u.llbMesh}),e.matrix&&e.matrix.length===16){const b=new p.Matrix4;b.elements=e.matrix,f.applyMatrix4(b)}const m=new Ri({modelId:n,dxfData:u});this.addModel(m),o(100),this.progressBar?.delayRemoveProgressItem(r),this.dispatchEvent(le.ModelLoad)}catch(d){throw this.progressBar?.removeProgressItem(r),P.error("[Viewer2d] Failed to load model '"+e.src+"'",d),d}finally{this.spinner.decreaseJobCount()}}removeModel(e){const i=super.removeModel(e);return i&&this.textSearchHelper?.invalidateIndex(),i&&this.loadedModels.length===0&&(this.masterModelId="",this.activeLayoutName="",this.layoutInfos={},this.units=void 0),i}addModel(e){super.addModel(e);const i=e.modelId;if(e.dxfData){this.masterModelId===i?this.activateLayout(X.MODEL_LAYOUT_NAME):this.handleOverlayDxf(i);const s=e.getBBox(),n=new p.Vector3;s.getCenter(n),this.cameraManager.adjustCameraByBBox(s);const r=this.getDxfUnits(e);this.masterModelId===i&&(this.units=r)}else{const s=e.getModelObject();this.activeLayoutName=X.MODEL_LAYOUT_NAME;const n=new p.Box3().setFromObject(s);this.layoutInfos[this.activeLayoutName]={homeViewExtent:n,extent:n},s.matrixAutoUpdate=et,this.scene.add(s);const r=n.max.z;r>this.camera.position.z&&(this.camera.position.z=r,this.camera.updateProjectionMatrix()),this.flyToObject(s)}this.updateGroundPlane()}getDxfUnits(e){return!e&&this.loadedModels.length>0&&(e=this.loadedModels.find(i=>this.masterModelId===i.modelId)),e?e.getUnits():Ke.Unitless}handleOverlayDxf(e){const i=this.loadedModels.find(n=>e===n.modelId);if(!i){P.warn("[Viewer] Can't find model for modelId '"+e+"'!");return}i.switchTransformMs(X.MODEL_LAYOUT_NAME),i.getLayoutLevelObject(X.MODEL_LAYOUT_NAME)?.traverse(n=>{i.addSpatialFilterSection(n,i.dxfData)}),i.showLayoutObjects(X.MODEL_LAYOUT_NAME)}setObjectHighlight(e){this.loadedModels.forEach(i=>i.highlightObject(e)),this.enableRender()}setObjectUnHighlight(e){this.loadedModels.forEach(i=>i.unHighlightObject(e)),this.enableRender()}clearHighlight(){this.loadedModels.forEach(e=>e.clearHighlight()),this.enableRender()}clearSelection(){this.selectedObject instanceof p.Object3D&&this.setObjectUnHighlight(this.selectedObject),this.selectedObject instanceof Nt&&(this.selectedObject.selected=!1),this.selectedObject=void 0,this.clickHighlightList?.clear()}get enableSelection(){return this._enableSelection}set enableSelection(e){e||this.clearSelection(),this._enableSelection=e}updateGroundPlane(){const e=this.getActiveLayoutInfo();if(!e.homeViewExtent)return;const i=e.homeViewExtent.clone(),s=[],n=(o,l,h)=>{s.push(new p.Vector3(o,l,h))},r=i.getSize(new p.Vector3),a=i.getCenter(new p.Vector3);if(n(-r.x/2,-r.y/2,0),n(r.x/2,-r.y/2,0),n(r.x/2,r.y/2,0),n(-r.x/2,r.y/2,0),this.groundPlane)this.groundPlane.position.set(a.x,a.y,-r.z),this.groundPlane.geometry.setFromPoints(s),this.groundPlane.geometry.computeBoundingSphere(),this.groundPlane.geometry.computeBoundingBox();else{const o=new p.BufferGeometry;o.setFromPoints(s),o.setIndex([0,3,2,0,2,1]);const l=new p.MeshBasicMaterial({color:"#888",side:p.DoubleSide});this.groundPlane=new p.Mesh(o,l),this.groundPlane.visible=!1,this.groundPlane.position.set(a.x,a.y,-r.z),this.groundPlane.scale.set(1e5,1e5,1),this.groundPlane.name="groundPlane",this.groundPlane.renderOrder=pl,this.groundPlane.layers.enableAll(),J.disableLayerChannels(this.groundPlane,[Ut]),this.scene.add(this.groundPlane)}this.groundPlane.updateMatrix(),this.groundPlane.updateMatrixWorld(!0)}getRaycastableObjects(){const e=[],i=Date.now();if(this.activeLayoutName===X.MODEL_LAYOUT_NAME){if(this.raycastableObjects)return this.raycastableObjects;if(this.renderer?.renderLists){const s=this.renderer?.renderLists.get(this.scene,0);s&&(s.opaque.forEach(n=>{n.object&&n.object.geometry&&e.push(n.object)}),s.transparent.forEach(n=>{n.object&&n.object.geometry&&e.push(n.object)}))}ho.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),uo.setFromProjectionMatrix(ho);for(const s of this.loadedModels){const n=s.getModelObject(),r=n.children.find(a=>a.name===this.activeLayoutName);r&&r.children.find(o=>o.name===X.SNAP_GROUP_NAME)?.traverse(o=>{if(J.isLeafObject(o)){if(nr.makeEmpty(),nr.expandByObject(o),!uo.intersectsBox(nr))return;e.push(o)}})}this.groundPlane&&e.push(this.groundPlane),P.debug("[Viewer] getRaycastableObjectsByMouse() from modelSpace"),this.raycastableObjects=e}else{const s=new WeakSet,n=this.getLayoutByName(this.activeLayoutName);n&&n.directAssociatedLeafObjectSet?.forEach(o=>{o.visible&&!s.has(o)&&(e.push(o),s.add(o))});const r=this.getViewportByPoint(this.pickManager.getRaycaster().ray.origin);r&&r.associatedLeafObjectSet?(r.associatedLeafObjectSet?.forEach(a=>{!s.has(a)&&(a.visible||a.userData.isSnapObject)&&(e.push(a),s.add(a))}),P.debug("[Viewer] getRaycastableObjectsByMouse() from inside of viewport:",r.viewportId)):P.debug("[Viewer] getRaycastableObjectsByMouse() from out of viewport"),this.groundPlane&&e.push(this.groundPlane)}return P.debug("[Viewer] getRaycastableObjectsByMouse() took "+(Date.now()-i)/1e3+" s"),e}getViewportByPoint(e){if(this.activeLayoutName.length===0||this.activeLayoutName===X.MODEL_LAYOUT_NAME)return;const i=this.getLayoutByName(this.activeLayoutName);if(!i)return;const s=a=>e.x<a.min.x||e.x>a.max.x||e.y<a.min.y||e.y>a.max.y,n=this.loadedModels.find(a=>this.masterModelId===a.modelId);if(!n)return;const r=n.getFilteredViewports(i);for(let a=0,o=r.length;a<o;a++){const l=r[a];if(!s(l.psBBox))return l}}getWorldPositionByMousePick(e){const i=[];this.groundPlane&&i.push(this.groundPlane);for(const n of this.loadedModels){const r=n.getModelObject();r&&(i.push(r),r.traverse(a=>{(a.isMesh||a.isLine)&&i.push(a)}))}return this.pickManager.pickObject(e,i)?.point}activateLayout(e=X.MODEL_LAYOUT_NAME){if(this.activeLayoutName===e||!this.masterModelId)return;const i=this.loadedModels.find(d=>this.masterModelId===d.modelId);if(!i)return;const s=i.getLayoutByName(e);if(!s)return;const n=this.getActiveLayoutInfo();if(this.groundPlane){const d=this.getCurrentViewExtent(),u=this.camera.position.z;n.lastViewExtent=new p.Box3(new p.Vector3(d.min.x,d.min.y,0),new p.Vector3(d.max.x,d.max.y,u))}const r=d=>!!this.layoutInfos[d]?.lastViewExtent,a=r(e);i?.activateLayout(e,a),this.activeLayoutName=e;const o=i.getFilteredViewports(s);if(P.debug("[Viewer] Active layout:",e,", viewports:",o),!a){const d=this.camera.position.z;let u=0;o.forEach(m=>{const b=m?.msToPsMatrix?.elements[14];b&&b>u&&(u=b)});const f=this.cameraManager.getPosition();if(u>f.z+d){const m=Math.ceil(u+d);f.z=m,P.info("[Viewer] Changing camera's z value from "+f.z+" to "+m),this.cameraManager.setCameraPosition(f)}}const l=this.getActiveLayoutInfo();if(l.lastViewExtent)this.zoomToBBox(l.lastViewExtent);else{l.extent=this.getBBox();let d=this.getLayoutExtentEx(s);if(d){const b=d.max.x-d.min.x,y=d.max.y-d.min.y;(b<1e-16||y<1e-16||b>1e16||y>1e16)&&(P.warn("[Viewer] Got wired bbox, max: "+d.max.toArray()+", min: "+d.min.toArray()+", going to use the calculated one..."),d=l.extent)}else P.warn("[Viewer] Failed to get layout extent, going to use the calculated one..."),d=l.extent;const u=l.extent;d&&!u.isEmpty()&&(d.intersectsBox(u)?d.union(u):(P.warn("[Viewer] Layout extent from header is far from actual geometry, using computed bbox instead."),d=u.clone())),l.homeViewExtent=d,this.zoomToBBox(d)}const h=i.getLayoutLevelObject(e);h&&this.setLayoutHidableObjectArray(h),this.enableRender()}getLayoutExtentEx(e){const i=this.loadedModels.find(s=>this.masterModelId===s.modelId);if(i)return e.layoutName===X.MODEL_LAYOUT_NAME?i.getModelSpaceExtent():i.getLayoutExtent(e)}getActiveLayoutInfo(){return this.getLayoutInfo(this.activeLayoutName)}getLayoutByName(e){let i;const s=this.loadedModels.find(r=>this.masterModelId===r.modelId);if(!s)return;const n=s.getLayouts();for(const r of n)if(r.layoutName===e){i=r;break}return i}getEntityCount(){let e=0;return this.loadedModels.forEach(i=>{e+=i.loadedEntityCount}),e}getLayoutNames(){const e=[];return(this.loadedModels.find(n=>this.masterModelId===n.modelId)?.getLayouts()||[]).forEach(n=>{e.push(n.layoutName)}),e}getLayoutInfo(e){return this.layoutInfos[e]||(this.layoutInfos[e]={}),this.layoutInfos[e]}goToHomeView(){const e=this.getActiveLayoutInfo();e.homeViewExtent?this.zoomToBBox(e.homeViewExtent):P.error("[Viewer] Failed to find extent for "+this.activeLayoutName)}zoomToBBox(e){const i=e.getCenter(Mi),s=e.max.x-e.min.x,n=e.max.y-e.min.y,r=this.camera.right-this.camera.left,a=this.camera.top-this.camera.bottom;let o=Math.min(r/s,a/n);o/=1.1,this.cameraManager.cameraControls.moveTo(i.x,i.y,i.z),this.cameraManager.cameraControls.zoomTo(o)}getCurrentViewExtent(){const e=this.getHitResultByNdcCoordinate(new p.Vector2(-1,-1)),i=this.getHitResultByNdcCoordinate(new p.Vector2(1,1));return new p.Box2(e,i)}getHitResultByNdcCoordinate(e){const i=[];this.groundPlane&&i.push(this.groundPlane);const s=this.pickManager.pickObjectsByNdc(e,i);if(s.length>0){const n=s[0].point;return new p.Vector2(n.x,n.y)}}getHitResult(e){const i=this.viewerContainer,s=Oe.getScreenCoordinateByEvent(e,i),n=Oe.screen2Ndc(s,this.camera,i);return this.getHitResultByNdcCoordinate(n)}getActiveLayoutName(){return this.activeLayoutName}searchText(e,i){return!this.textSearchHelper&&(this.textSearchHelper=new Mr(this)),this.textSearchHelper.search(e,i)}focusText(e){!this.textSearchHelper&&(this.textSearchHelper=new Mr(this)),this.textSearchHelper.focus(e)}clearTextHighlight(){this.textSearchHelper?.clearHighlight()}zoomIn(e=.01){this.cameraManager.cameraControls.zoom(e)}zoomOut(e=.01){this.cameraManager.cameraControls.zoom(-e)}async print(e={}){const{area:i="view",paperSize:s="A4",orientation:n="auto",invertColors:r=!1,fitToPage:a=!0,margins:o=10,title:l="图纸"}=e;if(!this.loadedModels.length){P.warn("[Viewer] print: no model loaded.");return}const h=this.capturePrintImage(i,r),d=new Image;await new Promise((f,m)=>{d.onload=()=>f(),d.onerror=()=>m(new Error("Failed to load captured print image.")),d.src=h});const u=n==="auto"?d.width>=d.height?"landscape":"portrait":n;this.printImageInIframe({dataUrl:h,width:d.width,height:d.height,paperSize:s,orientation:u,invertColors:r,fitToPage:a,margins:o,title:l})}capturePrintImage(e,i){const s=this.cameraManager.cameraControls,n=this.renderer,r=s.getPosition(new p.Vector3),a=s.getTarget(new p.Vector3),o=this.camera.zoom,l=n.getPixelRatio();let h;e==="extents"&&(h=this.getActiveLayoutInfo().homeViewExtent??this.getBBox(),this.zoomToBBox(h)),this._printCaptureMode=!0;const d=this.sortedHidableObjects[this.activeLayoutName],u=[];if(d)for(const O of d)O.object.userData?.layerVisible!==!1&&(u.push({object:O.object,visible:O.object.visible}),O.object.visible=!0);const{clientWidth:f,clientHeight:m}=this.viewerContainer,b=Math.min(n.capabilities.maxTextureSize||4096,8192),y=Math.min(4,b/Math.max(f,m));y>l&&n.setPixelRatio(y),this.cameraManager.update(0),this.dispatchEvent(le.BeforeRender),n.render(this.scene,this.camera),this.dispatchEvent(le.AfterRender);const S=n.domElement,w=this.overlayRender.getCanvas(),x=document.createElement("canvas");x.width=S.width,x.height=S.height;const E=x.getContext("2d");if(E.drawImage(S,0,0),w&&w.width>0&&w.height>0&&E.drawImage(w,0,0,x.width,x.height),i){const O=new p.Color(1973806);this.scene.background instanceof p.Color?O.copy(this.scene.background):n.getClearColor(O),O.convertLinearToSRGB(),this.invertForPrint(x,Math.max(1,Math.round(y/2)),{r:O.r*255,g:O.g*255,b:O.b*255})}let M=x.toDataURL("image/png");if(h&&this.camera.type==="OrthographicCamera"){const O=this.cropCanvasToBox(x,h);O&&(M=O)}this._printCaptureMode=!1;for(const{object:O,visible:T}of u)O.visible=T;return n.setPixelRatio(l),s.zoomTo(o),s.setLookAt(r.x,r.y,r.z,a.x,a.y,a.z),this.cameraManager.update(0),this.enableRender(),M}invertForPrint(e,i,s){const n=e.getContext("2d",{willReadFrequently:!0});if(!n)return;const r=e.width,a=e.height,o=n.getImageData(0,0,r,a),l=o.data,h=r*a,d=45,u=.72,f=new Float32Array(h);for(let T=0,v=0;T<h;T++,v+=4){const C=l[v],_=l[v+1],A=l[v+2],I=C-s.r,B=_-s.g,k=A-s.b;if(Math.sqrt(I*I+B*B+k*k)<d){l[v]=255,l[v+1]=255,l[v+2]=255,f[T]=255;continue}const D=C/255,F=_/255,ie=A/255,se=Math.max(D,F,ie),Fe=Math.min(D,F,ie),ht=(se+Fe)/2,Te=se-Fe,Vi=Te===0?0:Te/(1-Math.abs(2*ht-1));let tt=0;Te!==0&&(se===D?tt=(F-ie)/Te%6:se===F?tt=(ie-D)/Te+2:tt=(D-F)/Te+4,tt/=6,tt<0&&(tt+=1));const Tn=Math.min(.55,(1-ht)*u),ke=(1-Math.abs(2*Tn-1))*Vi,At=ke*(1-Math.abs(tt*6%2-1)),ji=Tn-ke/2;let Gt=0,qt=0,Wt=0;const Yt=Math.floor(tt*6)%6;Yt===0?(Gt=ke,qt=At):Yt===1?(Gt=At,qt=ke):Yt===2?(qt=ke,Wt=At):Yt===3?(qt=At,Wt=ke):Yt===4?(Gt=At,Wt=ke):(Gt=ke,Wt=At),l[v]=(Gt+ji)*255,l[v+1]=(qt+ji)*255,l[v+2]=(Wt+ji)*255,f[T]=.299*l[v]+.587*l[v+1]+.114*l[v+2]}const m=Math.max(1,i),b=new Float32Array(h),y=new Uint8ClampedArray(h),S=new Uint8ClampedArray(h),w=new Uint8ClampedArray(h);for(let T=0;T<a;T++){const v=T*r;for(let C=0;C<r;C++){let _=255,A=v+C;const I=Math.max(0,C-m),B=Math.min(r-1,C+m);for(let k=I;k<=B;k++){const D=f[v+k];D<_&&(_=D,A=v+k)}b[v+C]=_,y[v+C]=l[A*4],S[v+C]=l[A*4+1],w[v+C]=l[A*4+2]}}const x=new Float32Array(h),E=new Uint8ClampedArray(h),M=new Uint8ClampedArray(h),O=new Uint8ClampedArray(h);for(let T=0;T<r;T++)for(let v=0;v<a;v++){let C=255,_=v*r+T;const A=Math.max(0,v-m),I=Math.min(a-1,v+m);for(let k=A;k<=I;k++){const D=b[k*r+T];D<C&&(C=D,_=k*r+T)}const B=v*r+T;x[B]=C,E[B]=y[_],M[B]=S[_],O[B]=w[_]}for(let T=0,v=0;T<h;T++,v+=4)f[T]>250&&x[T]<250&&(l[v]=E[T],l[v+1]=M[T],l[v+2]=O[T]);n.putImageData(o,0,0)}cropCanvasToBox(e,i){const s=this.camera,n=s.zoom||1,r=s.position.x,a=s.position.y,o=r+s.left/n,l=r+s.right/n,h=a+s.bottom/n,d=a+s.top/n,u=l-o,f=d-h;if(u<=0||f<=0)return;const m=v=>(v-o)/u*e.width,b=v=>(d-v)/f*e.height,y=Math.max(u,f)*.01,S=Math.max(0,Math.floor(m(i.min.x-y))),w=Math.min(e.width,Math.ceil(m(i.max.x+y))),x=Math.max(0,Math.floor(b(i.max.y+y))),E=Math.min(e.height,Math.ceil(b(i.min.y-y))),M=w-S,O=E-x;if(M<16||O<16)return;const T=document.createElement("canvas");return T.width=M,T.height=O,T.getContext("2d").drawImage(e,S,x,M,O,0,0,M,O),T.toDataURL("image/png")}printImageInIframe(e){const{dataUrl:i,width:s,height:n,paperSize:r,orientation:a,invertColors:o,fitToPage:l,margins:h,title:d}=e,u={A4:[210,297],A3:[297,420],A2:[420,594],A1:[594,841],A0:[841,1189],Letter:[215.9,279.4]};let[f,m]=u[r]??u.A4;a==="landscape"&&([f,m]=[m,f]);const b=document.createElement("iframe");b.setAttribute("aria-hidden","true");const y=96/25.4;b.style.cssText=`position:fixed;left:-20000px;top:0;border:0;visibility:hidden;width:${Math.ceil(f*y)}px;height:${Math.ceil(m*y)}px;`;const S=v=>v.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),w=l?"max-width:100%;max-height:100%;width:auto;height:auto;":"width:100%;height:auto;",x=`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${S(d)}</title><style>@page{size:${r} ${a};margin:${h}mm;}html,body{margin:0;padding:0;background:#fff;}body{display:flex;align-items:center;justify-content:center;width:${f-2*h}mm;height:${m-2*h}mm;overflow:hidden;}img{display:block;${w}}</style></head><body><img src="${i}" alt="${S(d)}"></body></html>`;document.body.appendChild(b);const E=()=>{b.contentWindow?.removeEventListener("afterprint",E),setTimeout(()=>b.remove(),100)},M=b.contentDocument;M.open(),M.write(x),M.close();const O=M.querySelector("img"),T=()=>{const v=b.contentWindow;v.addEventListener("afterprint",E),v.focus(),v.print(),setTimeout(E,6e4)};O.complete?T():(O.onload=T,O.onerror=E)}getLayers(){const e=[];if(this.masterModelId){const i=this.loadedModels.find(n=>this.masterModelId===n.modelId),s=i?.layers;s&&e.push({modelId:this.masterModelId,layers:s})}for(const i of this.loadedModels){const s=i.modelId;if(s===this.masterModelId)continue;const n=i.layers;n&&e.push({modelId:s,layers:n})}return e}setModelVisibility(e,i){const s=this.loadedModels.find(n=>e===n.modelId);if(!s)throw new Error("Failed to find model by modelId '"+e+"'!");s.setVisible(i),this.enableRender()}setLayerVisibility(e,i,s){const n=this.camera;s=s||this.masterModelId;const r=this.loadedModels.find(a=>s===a.modelId);if(!r)throw new Error("Failed to find layer by modelId '"+s+"'!");r.setLayerVisible(e,i,this.enableHideVisuallySmallObjects,n.zoom),this.raycastableObjects=void 0,this.enableRender()}setLayerOpacity(e,i,s){s=s||this.masterModelId;const n=this.loadedModels.find(r=>s===r.modelId);if(!n)throw new Error("Failed to find layer by modelId '"+s+"'!");n.setLayerOpacity(e,i),this.enableRender()}setLayerColor(e,i,s){s=s||this.masterModelId;const n=this.loadedModels.find(r=>s===r.modelId);if(!n)throw new Error("Failed to find layer by modelId '"+s+"'!");this.clearSelection(),n.setLayerColor(e,i),this.enableRender()}resetLayerColor(e,i){i=i||this.masterModelId;const s=this.loadedModels.find(n=>i===n.modelId);if(!s)throw new Error("Failed to find model by modelId '"+i+"'!");this.clearSelection(),s.resetLayerColor(e),this.enableRender()}getVisiblePixelSize(e){const i=p.MathUtils.smoothstep(e,1e4,3e4)*6.5+.5;return P.debug("[Viewer] visiblePixelSize:",i),i}setLayoutHidableObjectArray(e){const i=this.camera;if(!this.enableHideVisuallySmallObjects||!i)return;const s=Date.now(),n=e.name;this.sortedHidableObjects[n]||(this.sortedHidableObjects[n]=[]);const r=this.sortedHidableObjects[n];this.cameraManager.update(0);const a=i.zoom;this.lastCameraZoom=a;let o=1;e.traverse(h=>{if(h.userData.isSnapObject||!J.isLeafObject(h))return;const d=h.geometry;d.boundingBox||d.computeBoundingBox();const u=d.boundingBox.clone();if(!u||!j.isBoxValid(u))return;u.applyMatrix4(h.matrixWorld),u.getSize(Mi);const f=Math.max(Mi.x,Mi.y),m=o/f;m<1/0?r.push({visibleMinZoom:m,object:h}):h instanceof p.Points?r.push({visibleMinZoom:o,object:h}):P.warn("[Viewer] The size of bbox is 0 ! ",h)}),o=this.getVisiblePixelSize(r.length);let l=0;r.forEach(h=>{const d=h.visibleMinZoom*o;h.visibleMinZoom=d,h.object.userData.visibleMinZoom=d,d>a&&(h.object.visible=!1,l++)}),r.sort((h,d)=>h.visibleMinZoom-d.visibleMinZoom),P.debug("[Viewer] setLayoutHidableObjectArray took: "+(Date.now()-s)/1e3+"s, "+l+" objects changed to hidden")}updateRaycasterThreshold(){const e=this.getPixelSizeInWorldCoord()*3,i=this.getRaycaster().params;i.Line?i.Line.threshold=e:i.Line={threshold:e},i.Points?i.Points.threshold=e:i.Points={threshold:e}}updateHidableObjectsVisibility(){const e=this.camera,i=Date.now();this.cameraManager.update(0);const s=e.zoom;if(Math.abs(s-this.lastCameraZoom)<1e-5)return;if(this.updateRaycasterThreshold(),this.updateCameraZoomUniform(s),this.raycastableObjects=void 0,this._printCaptureMode){this.lastCameraZoom=s;return}if(!this.sortedHidableObjects[this.activeLayoutName])return;const n=this.sortedHidableObjects[this.activeLayoutName];if(n.length===0)return;const r=s>this.lastCameraZoom,a=Math.min(s,this.lastCameraZoom),o=Math.max(s,this.lastCameraZoom),l=[];let h=0;for(let d=0;d<n.length;++d)if(n[d].object.userData.layerVisible!==!1){if(n[d].visibleMinZoom<a){l.push(n[d].object);continue}else if(n[d].visibleMinZoom>o)break;n[d].object.visible=r,r&&l.push(n[d].object),h++}this.lastCameraZoom=s,P.debug("[Viewer] updateHidableObjectsVisibility took: "+(Date.now()-i)/1e3+"s, "+h+"(out of "+n.length+") objects changed to "+(r?"visible":"hidden"))}updateCameraZoomUniform(e){X.CameraZoomUniform.value=e*this.container.height/50}}class ml{constructor(t){g(this,"viewer");g(this,"fontManager");g(this,"loader");g(this,"loadingManager");g(this,"changes");g(this,"container");g(this,"spinner");g(this,"jobCount");g(this,"loadingProgressBar");this.jobCount=0,this.viewer=new Vr(t);const e=document.getElementById(t.containerId);this.container=e?.parentElement||document.body;const i=new Rr(t.containerId);this.loadingProgressBar=new Fr(i);const s={ignorePaperSpace:!0};this.loader=new X(this.loadingManager,s),this.initSpinner()}initSpinner(){const t=document.createElement("div");t.classList.add("x-spinner"),t.appendChild(document.createElement("span")),t.appendChild(document.createElement("span")),t.appendChild(document.createElement("span")),t.appendChild(document.createElement("span")),this.container.appendChild(t),this.spinner=t,this.setSpinnerVisibility(this.jobCount>0)}async setFont(t){const e=Date.now();!this.fontManager&&(this.fontManager=new xt),await this.fontManager.loadFonts(t),P.info("[DxfCompareHelper] Font file(s) load time in "+(Date.now()-e)/1e3+"s")}async compare(t,e,i,s){const{src:n,modelId:r}=t,{src:a}=e;this.viewer.masterModelId=r||n;const o=Date.now();this.increaseJobCount();try{if(!this.fontManager)throw"[DxfCompareHelper] Should set font first!";this.loader.setFont(this.fontManager),await this.fontManager.getFontFromIndexeddb();const l=n+a,h=We.t("ProgressBar.Comparing"),d=B=>{this.loadingProgressBar?.updateProgress(l,h,B),s&&s(new ProgressEvent("CompareProgress",{loaded:B,total:100}))},u=(B,k,D)=>{let F=B.loaded*100/B.total;F=F*(D-k)/100+k,this.loadingProgressBar?.updateProgress(l,h,F),s&&s(new ProgressEvent("CompareProgress",{loaded:F,total:100}))},f=B=>u(B,0,15),m=B=>u(B,15,30),b=B=>u(B,30,60),y=B=>u(B,60,95);j.printMemory("Before comparing"),this.loadingProgressBar?.addProgressItem(l),d(0);let S=Date.now();const w=this.loader.parse(n,f),x=this.loader.parse(a,m),[E,M]=await Promise.allSettled([w,x]);if(E.status==="rejected")throw"[DxfCompareHelper] Failed to parse "+n;if(M.status==="rejected")throw"[DxfCompareHelper] Failed to parse "+a;if(P.info("[DxfCompareHelper] loadFiles in "+(Date.now()-S)/1e3+"s"),this.loader.isAborted())throw"[DxfCompareHelper] compare loadFile aborted";const O=E.value,T=M.value;S=Date.now();const v=await new ot(O,T,i).compare(b);if(P.info("[DxfCompareHelper] Compared in "+(Date.now()-S)/1e3+"s"),P.debug("[DxfCompareHelper] Compared results:",v),this.loader.isAborted())throw"[DxfCompareHelper] compare change aborted";j.printMemory("After getting the comparison results"),S=Date.now(),await this.loader.loadEntitiesForCompare(O,T,v,!0,y),j.printMemory("After Creating threejs objects based on comparison result"),this.fontManager?.releaseFontData(),this.changes=v,P.info("[DxfCompareHelper] Creates threejs objects based on comparison result in "+(Date.now()-S)/1e3+"s");const C=O,_=T;if(!Object.keys(v).length&&P.info("[DxfCompareHelper] No change found"),C.threejsObject?.children.length===0&&_.threejsObject?.children.length===0){const B="[DxfCompareHelper] Nothing was loaded from "+n+" and "+a;throw P.warn(B),B}const A=C.threejsObject,I=_.threejsObject;A.name=n,I.name=a,S=Date.now(),this.viewer.addModel(new Ri({modelId:t.modelId||t.src,dxfData:C})),this.viewer.flyToObject(A),j.printMemory("After adding first loaded Model to scene"),d(95),this.viewer.addModel(new Ri({modelId:e.modelId||e.src,dxfData:_})),j.printMemory("After adding second loaded Model to scene"),P.info("[DxfCompareHelper] Added compared objects to scene in "+(Date.now()-S)/1e3+"s"),P.info("[DxfCompareHelper] The comparison between "+n+"' and '"+a+"' is completed in "+(Date.now()-o)/1e3+"s !"),d(100),this.loadingProgressBar?.delayRemoveProgressItem(l)}catch(l){throw this.loadingProgressBar?.removeProgressItem(n+a),l}finally{this.decreaseJobCount()}}getChanges(){return this.changes}zoomToChange(t){if(this.changes){const e=this.changes[t];if(!e)return;const i=e.box;i&&this.viewer.zoomToBBox(i.clone().expandByScalar(1.2))}}setSpinnerVisibility(t){this.spinner&&(t?this.spinner.classList.remove("hidden"):this.spinner.classList.add("hidden"))}increaseJobCount(){this.setSpinnerVisibility(++this.jobCount>0)}decreaseJobCount(){this.setSpinnerVisibility(--this.jobCount>0)}}class Bu extends ml{constructor(e,i){super(e);g(this,"viewer2");g(this,"syncCamera");g(this,"markupManager1");g(this,"markupManager2");g(this,"syncCameraControls");this.syncCamera=!1,this.syncCameraControls=(s,n,r)=>{const a=new p.Vector3,o=new p.Vector3,l=new p.Vector3;s.getPosition(o),s.getTarget(l),s.getFocalOffset(a),n.setLookAt(o.x,o.y,o.z,l.x,l.y,l.z),n.zoomTo(r),n.dispatchEvent({type:"control"})},this.viewer2=new Vr(i),this.initSyncCameraEvent()}initSyncCameraEvent(){const e=this.viewer.getCameraManager().cameraControls,i=this.viewer2.getCameraManager().cameraControls;let s=!1;e.addEventListener("control",()=>{s=!1}),e.addEventListener("update",()=>{!this.syncCamera||s||this.syncCameraControls(e,i,this.viewer.camera.zoom)}),i.addEventListener("control",()=>{s=!0}),i.addEventListener("update",()=>{!this.syncCamera||!s||this.syncCameraControls(i,e,this.viewer2.camera.zoom)})}enableSyncCamera(e){if(this.syncCamera=e,e){const i=this.viewer.getCameraManager().cameraControls,s=this.viewer2.getCameraManager().cameraControls;this.syncCameraControls(i,s,this.viewer.camera.zoom)}}async compare(e,i,s,n){const{src:r,modelId:a}=e,{src:o,modelId:l}=i;this.viewer.masterModelId=a||r,this.viewer2.masterModelId=l||o;const h=Date.now();this.increaseJobCount();try{if(!this.fontManager)throw"[DxfCompareHelper] Should set font first!";this.loader.setFont(this.fontManager),await this.fontManager.getFontFromIndexeddb();const d=r+o,u=We.t("ProgressBar.Comparing"),f=D=>{this.loadingProgressBar?.updateProgress(d,u,D),n&&n(new ProgressEvent("CompareProgress",{loaded:D,total:100}))},m=(D,F,ie)=>{let se=D.loaded*100/D.total;se=se*(ie-F)/100+F,this.loadingProgressBar?.updateProgress(d,u,se),n&&n(new ProgressEvent("CompareProgress",{loaded:se,total:100}))},b=D=>m(D,0,15),y=D=>m(D,15,30),S=D=>m(D,30,60),w=D=>m(D,60,95);j.printMemory("Before comparing"),this.loadingProgressBar?.addProgressItem(d),f(0);let x=Date.now();const E=this.loader.parse(r,b),M=this.loader.parse(o,y),[O,T]=await Promise.allSettled([E,M]);if(O.status==="rejected")throw"[DxfCompareHelper] Failed to parse "+r;if(T.status==="rejected")throw"[DxfCompareHelper] Failed to parse "+o;if(P.info("[DxfCompareHelper] loadFiles in "+(Date.now()-x)/1e3+"s"),this.loader.isAborted())throw"[DxfCompareHelper] compare loadFile aborted";const v=O.value,C=T.value;x=Date.now();const _=await new ot(v,C,s).compare(S);if(P.info("[DxfCompareHelper] Compared in "+(Date.now()-x)/1e3+"s"),P.debug("Compared results:",_),this.loader.isAborted())throw"[DxfCompareHelper] compare change aborted";j.printMemory("After getting the comparison results"),x=Date.now(),await this.loader.loadEntitiesForCompare(v,C,_,!1,w),j.printMemory("After Creating threejs objects based on comparison result"),this.fontManager?.releaseFontData(),this.changes=_,P.info("[DxfCompareHelper] Creates threejs objects based on comparison result in "+(Date.now()-x)/1e3+"s");const A=v,I=C;if(!Object.keys(_).length&&P.info("[DxfCompareHelper] No change found"),A.threejsObject?.children.length===0&&I.threejsObject?.children.length===0){const D="[DxfCompareHelper] Nothing was loaded from "+r+" and "+o;throw P.warn(D),D}const B=A.threejsObject,k=I.threejsObject;B.name=r,k.name=o,x=Date.now(),this.viewer.addModel(new Ri({modelId:e.modelId||e.src,dxfData:A})),j.printMemory("After adding first loaded Model to scene"),f(95),this.viewer2.addModel(new Ri({modelId:i.modelId||i.src,dxfData:I})),j.printMemory("After adding second loaded Model to scene"),this.drawCompareBoxes(),P.info("[DxfCompareHelper] Added compared objects to scene in "+(Date.now()-x)/1e3+"s"),P.info("[DxfCompareHelper] The comparison between "+r+"' and '"+o+"' is completed in "+(Date.now()-h)/1e3+"s !"),f(100),this.loadingProgressBar?.delayRemoveProgressItem(d)}catch(d){throw this.loadingProgressBar?.removeProgressItem(r+o),d}finally{this.decreaseJobCount()}}drawCompareBoxes(){this.changes&&(this.markupManager1??(this.markupManager1=new vr(this.viewer)),this.markupManager2??(this.markupManager2=new vr(this.viewer2)),requestAnimationFrame(()=>{this.markupManager1?.drawCompareDrawable(this.changes),this.markupManager2?.drawCompareDrawable(this.changes),this.viewer.enableRender(),this.viewer2.enableRender()}))}zoomToChange(e){if(this.changes){const i=this.changes[e];if(!i)return;const s=i.box;s&&(this.viewer.zoomToBBox(s.clone().expandByScalar(1.2)),this.viewer2.zoomToBBox(s.clone().expandByScalar(1.2)))}}}class Pi{constructor(t,e){g(this,"current");g(this,"next");g(this,"inNormal");g(this,"outNormal");this.current=t,this.next=e,this.inNormal=this.inwardsNormal(),this.outNormal=this.outwardsNormal()}outwardsNormal(){const t=this.inwardsNormal();return[-t[0],-t[1]]}inwardsNormal(){const t=this.next[0]-this.current[0],e=this.next[1]-this.current[1],i=Math.sqrt(t*t+e*e);if(i===0)throw new Error("Vertices overlap");return[-e/i,t/i]}offset(t,e){return Pi.offsetEdge(this.current,this.next,t,e)}inverseOffset(t,e){return Pi.offsetEdge(this.next,this.current,t,e)}inverse(){return new Pi(this.next,this.current)}static offsetEdge(t,e,i,s){return new Pi([t[0]+i,t[1]+s],[e[0]+i,e[1]+s])}}const ss=Array.isArray,po=(c,t)=>c[0]===t[0]&&c[1]===t[1],rr=c=>Array.isArray(c)&&c.length,gl=(c,t=0,e=!1)=>{let i,s;if(rr(c)&&typeof c[0][0]=="number"){let n=0;const r=c;for(i=0,s=r.length;i<s;i++){const a=r[i],o=r[(i+1)%s];n+=a[0]*o[1],n-=o[0]*a[1]}(!e&&n>0||e&&n<0)&&r.reverse()}else for(i=0,s=c.length;i<s;i++)gl(c[i],t+1,i>0);if(t===0&&rr(c)&&rr(c[0])&&typeof c[0][0][0]=="number"){const n=c[0].slice(0,1)[0];c[0].pop(),c[0].push([n[0],n[1]])}return c};class ku{constructor(t,e=5){g(this,"vertices");g(this,"edges");g(this,"arcSegments");g(this,"distance");if(this.distance=0,this.arcSegments=e,!ss(t))throw new Error("Offset requires at least one coodinate to work with");this.edges=[],ss(t)&&typeof t[0]=="number"?this.vertices=t:(this.vertices=gl(t),this.processContour(this.vertices,this.edges))}processContour(t,e){let i,s;if(ss(t[0])&&typeof t[0][0]=="number")for(t=t,e=e,s=t.length,po(t[0],t[s-1])&&(s-=1),i=0;i<s;i++)e.push(new Pi(t[i],t[(i+1)%s]));else for(t=t,e=e,i=0,s=t.length;i<s;i++)e.push([]),this.processContour(t[i],e[e.length-1])}setArcSegments(t){return this.arcSegments=t,this}createArc(t,e,i,s,n,r,a){const o=Math.PI*2;let l=Math.atan2(s[1]-e[1],s[0]-e[0]),h=Math.atan2(n[1]-e[1],n[0]-e[0]);r%2===0&&(r-=1),l<0&&(l+=o),h<0&&(h+=o);let d=l>h?l-h:l+o-h;const u=(a?-d:o-d)/r;t.push(s);for(let f=1;f<r;++f)d=l+u*f,t.push([e[0]+Math.cos(d)*i,e[1]+Math.sin(d)*i]);return t.push(n),t}setDistance(t){return this.distance=t,this}ensureLastPoint(t){return po(t[0],t[t.length-1])||t.push([t[0][0],t[0][1]]),t}offset(t){return this.setDistance(t),this.distance===0?this.vertices:this.distance>0?this.margin(this.distance):this.padding(-this.distance)}offsetSegment(t,e,i,s){const n=[i.offset(i.inNormal[0]*s,i.inNormal[1]*s),i.inverseOffset(i.outNormal[0]*s,i.outNormal[1]*s)],r=[];for(let a=0,o=2;a<o;a++){const l=n[a],h=n[(a+o-1)%o];this.createArc(r,a===0?t:e,s,h.next,l.current,this.arcSegments,!0)}return r}margin(t){if(this.setDistance(t),typeof this.vertices[0]=="number")return this.offsetPoint(this.distance);if(t===0)return this.vertices;let e=this.offsetLines(this.distance);return e=Ui.union(this.vertices,e),e}padding(t){if(this.setDistance(t),this.distance===0)return this.vertices;if(this.vertices.length===2&&typeof this.vertices[0]=="number")return this.vertices;const e=this.offsetLines(this.distance);return Ui.difference(this.vertices,e)}offsetLine(t){return t===0?this.vertices:this.offsetLines(t)}offsetLines(t){if(t<0)throw new Error("Cannot apply negative margin to the line");this.setDistance(t);let e=[];if(ss(this.vertices[0])&&typeof this.vertices[0][0]!="number"){const i=[];for(let s=0,n=this.edges.length;s<n;s++){const r=this.offsetContour(this.vertices[s],this.edges[s]);r.length>0&&i.push(r)}i.length>0&&(e=i.length===1?i[0]:Ui.union(i[0],...i.slice(1)))}else e=this.vertices.length===1?this.offsetPoint(t):this.offsetContour(this.vertices,this.edges);return e}offsetContour(t,e){let i=[],s=0,n=0;if(ss(t[0])&&typeof t[0][0]=="number"){for(s=0,n=t.length-1;s<n;s++){const r=this.ensureLastPoint(this.offsetSegment(t[s],t[s+1],e[s],this.distance)),a=[r];i.push(a)}i.length>0&&(i=i.length===1?[i[0]]:Ui.union(i[0],i.slice(1)))}else{const r=[];for(s=0,n=e.length;s<n;s++){const a=this.offsetContour(t[s],e[s]);a.length>0&&r.push(a)}r.length>0&&(i=r.length===1?r[0]:Ui.union(r[0],...r.slice(1)))}return i}offsetPoint(t){this.setDistance(t);let e=this.arcSegments*2;const i=[],s=this.vertices,n=this.distance;let r=0;e%2===0&&e++;for(let a=0;a<e;a++)r+=2*Math.PI/e,i.push([s[0]+n*Math.cos(r),s[1]+n*Math.sin(r)]);return[[this.ensureLastPoint(i)]]}}class yl{constructor(t){g(this,"viewer");g(this,"composerEnabled");g(this,"composer");g(this,"renderPass");g(this,"effectFxaaPass");g(this,"saoPass");g(this,"ssaoPass");g(this,"outlinePass");g(this,"ssaaRenderPass");g(this,"bloomPass");g(this,"unrealBloomPass");g(this,"vertexNormalsHelpers");this.composerEnabled=!0,this.viewer=t,this.composer=new ec.EffectComposer(this.viewer.renderer),this.viewer.addEventListener(le.AfterRender,()=>this.render())}get enabled(){return this.composerEnabled}set enabled(t){this.composerEnabled=t}get renderPassEnabled(){return!!this.renderPass?.enabled}set renderPassEnabled(t){const e=this.viewer.scene,i=this.viewer.camera,{width:s,height:n}=this.viewer.container;if(this.composer){if(t&&!this.renderPass){const r=new tc.RenderPass(e,i);r.setSize(s,n),this.composer.addPass(r),this.renderPass=r}this.renderPass&&(this.renderPass.enabled=t),this.viewer.enableRender()}}get fxaaPassEnabled(){return!!this.effectFxaaPass?.enabled}set fxaaPassEnabled(t){if(!this.composer)return;const{width:e,height:i}=this.viewer.container;if(t&&!this.effectFxaaPass){const s=new ic.ShaderPass(cc.FXAAShader);s.uniforms.resolution.value.set(1/e,1/i),s.renderToScreen=!0,s.setSize(e,i),this.composer.addPass(s),this.effectFxaaPass=s}this.effectFxaaPass&&(this.effectFxaaPass.enabled=t),this.viewer.enableRender()}get saoPassEnabled(){return!!this.saoPass?.enabled}set saoPassEnabled(t){const{width:e,height:i}=this.viewer.container,s=this.viewer.scene,n=this.viewer.camera;if(this.composer){if(t&&!this.saoPass){const r=new sc.SAOPass(s,n,new p.Vector2(1/e,1/i));r.setSize(e,i),r.params.output=0,r.params.saoBias=.5,r.params.saoIntensity=3e-4,r.params.saoScale=8,r.params.saoKernelRadius=40,r.params.saoMinResolution=0,this.composer.addPass(r),this.saoPass=r}this.saoPass&&(this.saoPass.enabled=t),this.viewer.enableRender()}}get ssaoPassEnabled(){return!!this.ssaoPass?.enabled}set ssaoPassEnabled(t){const e=this.viewer.scene,i=this.viewer.camera,{width:s,height:n}=this.viewer.container;if(this.composer){if(t&&!this.ssaoPass){const r=new nc.SSAOPass(e,i,s,n);r.kernelRadius=16,r.minDistance=1e-4,r.maxDistance=.3,this.composer.addPass(r),this.ssaoPass=r}this.ssaoPass&&(this.ssaoPass.enabled=t),this.viewer.enableRender()}}get outlinePassEnabled(){return!!this.outlinePass?.enabled}set outlinePassEnabled(t){const e=this.viewer.scene,i=this.viewer.camera,{width:s,height:n}=this.viewer.container;if(this.composer){if(t&&!this.outlinePass){const r=new rc.OutlinePass(new p.Vector2(s,n),e,i);r.edgeStrength=3,r.edgeGlow=0,r.edgeThickness=2,r.pulsePeriod=0,r.visibleEdgeColor.set(16711680),r.hiddenEdgeColor.set(16752768),this.composer.addPass(r),this.outlinePass=r}this.outlinePass&&(this.outlinePass.enabled=t),this.viewer.enableRender()}}get ssaaPassEnabled(){return!!this.ssaaRenderPass?.enabled}set ssaaPassEnabled(t){const e=this.viewer.scene,i=this.viewer.camera;if(this.composer){if(t&&!this.ssaaRenderPass){const s=new ac.SSAARenderPass(e,i,16777215,0);this.composer.addPass(s),this.ssaaRenderPass=s,this.ssaaRenderPass=s}this.ssaaRenderPass&&(this.ssaaRenderPass.enabled=t),this.viewer.enableRender()}}get bloomPassEnabled(){return!!this.bloomPass?.enabled}set bloomPassEnabled(t){if(this.composer){if(t&&!this.bloomPass){const e=new oc.BloomPass(1,25,4);e.renderToScreen=!0,this.composer.addPass(e),this.bloomPass=e}this.bloomPass&&(this.bloomPass.enabled=t),this.viewer.enableRender()}}get unrealBloomPassEnabled(){return!!this.unrealBloomPass?.enabled}set unrealBloomPassEnabled(t){const{width:e,height:i}=this.viewer.container;if(this.composer){if(t&&!this.unrealBloomPass){const s=new lc.UnrealBloomPass(new p.Vector2(e,i),1,0,0);s.threshold=0,s.strength=.5,s.radius=0,this.composer.addPass(s),this.unrealBloomPass=s}this.unrealBloomPass&&(this.unrealBloomPass.enabled=t),this.viewer.enableRender()}}setOutlinePassSelectObjects(t){this.outlinePass&&(this.outlinePass.selectedObjects=t)}enableModelEdges(t){const e=this.viewer.loadedModels;for(let i=0;i<e.length;++i){const s=e[i];if(s instanceof kr)if(t&&!s.edges){const n=s.getModelObject();n&&(P.debug("[Viewer] Generating outlines for model '"+n.id+"'"),s.enableOutline(t))}else s.edges&&s.edges.forEach(n=>n.visible=t);else s instanceof Lr&&P.warn("[BimTiles] enableModelEdges() is not implemented for bimtiles yet.")}this.viewer.enableRender()}showVertexNormals(t,e=.1){t?(!this.vertexNormalsHelpers&&(this.vertexNormalsHelpers=new p.Group),this.viewer.scene.traverseVisible(i=>{const s=["SKYBOX","GROUND_GRID","GROUND_GRASS","BIM_VIEWER_BOX_HELPER"];if(i instanceof p.Mesh&&!s.includes(i.name)){if(!i.geometry.attributes.normal)return;const r=new hc.VertexNormalsHelper(i,e,16711680);this.vertexNormalsHelpers?.add(r)}}),this.viewer.scene.add(this.vertexNormalsHelpers)):this.vertexNormalsHelpers&&(this.viewer.scene.remove(this.vertexNormalsHelpers),this.vertexNormalsHelpers=void 0)}render(){!this.composer||!this.enabled||this.composer.render()}destroy(){this.renderPass&&(this.composer?.removePass(this.renderPass),this.renderPass.dispose(),this.renderPass=void 0),this.effectFxaaPass&&(this.composer?.removePass(this.effectFxaaPass),this.effectFxaaPass.dispose(),this.effectFxaaPass=void 0),this.saoPass&&(this.composer?.removePass(this.saoPass),this.saoPass.dispose(),this.saoPass=void 0),this.ssaoPass&&(this.composer?.removePass(this.ssaoPass),this.ssaoPass.dispose(),this.ssaoPass=void 0),this.outlinePass&&(this.composer?.removePass(this.outlinePass),this.outlinePass.dispose(),this.outlinePass=void 0),this.ssaaRenderPass&&(this.composer?.removePass(this.ssaaRenderPass),this.ssaaRenderPass.dispose(),this.ssaaRenderPass=void 0),this.bloomPass&&(this.composer?.removePass(this.bloomPass),this.bloomPass.dispose(),this.bloomPass=void 0),this.unrealBloomPass&&(this.composer?.removePass(this.unrealBloomPass),this.unrealBloomPass.dispose(),this.unrealBloomPass=void 0),this.composer&&(this.composer?.dispose(),this.composer=void 0)}}class Du extends Mn{constructor(e,i){super(e);g(this,"name");g(this,"loadedModels");g(this,"distanceCullingFactor");g(this,"selectedObject");g(this,"effect");if(this.name=$e.Viewer3d,this.loadedModels=[],this.distanceCullingFactor=150,this.effect=new yl(this),this.sceneManager.enableLights(!0),i)this.setHomeView(i),this.cameraManager.flyToViewpoint(i);else{const s=new p.Vector3(100,50,100),n=new p.Vector3(0,0,0),r={eye:s,look:n};this.cameraManager.flyToViewpoint(r)}this.cameraManager.setProjection(bt.Perspective),this.cameraManager.setNavigationMode(lt.Orbit),this.setupDefaultEvents(),this.setDefaultBackground()}setupDefaultEvents(){let e=!1,i,s=0,n=0,r=0;const a=300,o=u=>n===-1||r===-1?!1:Math.abs(u.x-n)<5&&Math.abs(u.y-r)<5,l=u=>{const f=u.timestamp-s;return!!(u.button===Je.Left&&f<a&&o(u))};let h,d=!1;this.inputManager.addEventListener("pointerdown",u=>{e=!1,i=u.button;const f=new p.Vector2(u.x,u.y);h=this.pickObject(f),d=h?.object===this.selectedObject,u.button===Je.Left&&this.handleAnchorPoint(h)}),this.inputManager.addEventListener("pointermove",u=>{i!==void 0&&(e=!o(u),i===Je.Left&&this.cameraManager.enableRotate&&this.cameraManager.setOrbitPointVisible(!0))}),this.inputManager.addEventListener("pointerup",u=>{if(i=void 0,this.cameraManager.setOrbitPointVisible(!1),e){e=!1;return}u.button===Je.Left?l(u)?(h?.object?this.flyToObject(h.object):this.viewFitAll(),s=0,n=-1,r=-1):(this.selectedObject&&(this.selectedObject instanceof Nt?this.selectedObject.selected=!1:this.clearHighlight(),this.selectedObject=void 0),s=u.timestamp,n=u.x,r=u.y,h?.object&&!d&&this.handleClickObject(h.object)):(u.button,Je.Right)})}setDefaultBackground(){this.sceneManager.renderer.setClearColor(11119017,1),this.sceneManager.setBackground(null),this.sceneManager.setEnvironmentFromData()}handleAnchorPoint(e){const i=new p.Vector3;this.selectedObject?new p.Box3().setFromObject(this.selectedObject).getCenter(i):e&&e.point?i.copy(e.point):this.getBBox().getCenter(i),this.cameraManager.setOrbitPoint(i),this.cameraManager.update(0)}handleClickObject(e){if(!this.enableSelection)return;const i=r=>!r.userData.modelId&&r.parent?i(r.parent):r.userData.modelId,s=i(e);this.loadedModels.find(r=>r.modelId===s)?.highlightObject(e),this.selectedObject=e,this.enableRender()}is3d(){return!0}async loadLocalModel(e,i,s,n){return this.loadModelInternal(i,n,!0,e,s)}async loadModel(e,i){return this.loadModelInternal(e,i)}async loadModelInternal(e,i,s,n,r){this.spinner.increaseJobCount();const a=e.modelId||e.src,o=We.t("ProgressBar.Loading"),l=f=>{this.progressBar?.updateProgress(a,o,f),i?.(new ProgressEvent("LoadProgress",{loaded:f,total:100}))};let h=!1;const d=(f,m,b)=>{let y=f.loaded*100/f.total;y=y*(b-m)/100+m,y>b&&(h||(P.warn("[Progress] Invalid ProgressEvent:",f),h=!0),y=b),this.progressBar?.updateProgress(a,o,y),i?.(new ProgressEvent("LoadProgress",{loaded:y,total:100}))},u=f=>d(f,0,50);this.progressBar?.addProgressItem(a),l(0);try{let f;if(s?(this.loaderHelper.setLoadManager(r),f=await this.loaderHelper.loadLocalModel(n,e.src,i)):f=await this.loaderHelper.loadModel(e.src,e.fileFormat,u),e.matrix&&e.matrix.length===16){const x=new p.Matrix4;x.elements=e.matrix,f.applyMatrix4(x)}const m=this.getUniqueModelId(e.modelId||e.src),b=new kr({modelId:m,object:f});this.addModel(b),l(90);const y=b.getBBox();this.loadedModels.length===1&&setTimeout(()=>this.goToHomeView(),0);const w=new p.Vector3;y.getCenter(w),this.cameraManager.setOrbitPoint(w),l(100),this.progressBar?.delayRemoveProgressItem(a),this.dispatchEvent(le.ModelLoad)}catch(f){throw this.progressBar?.removeProgressItem(a),P.error("[Viewer3d] Failed to load model '"+e.src+"'",f),f}finally{this.spinner.decreaseJobCount()}}setDistanceCullingFactor(e){this.distanceCullingFactor=e}getDistanceCullingFactor(){return this.distanceCullingFactor}setObjectOpacity(e,i){this.loadedModels.forEach(s=>s.setObjectOpacity(e,i)),this.enableRender()}setOtherObjectsOpacity(e,i){this.loadedModels.forEach(s=>{s.setOpacity(i),s.clearObjectOpacity(e)}),this.enableRender()}clearObjectOpacity(e){this.loadedModels.forEach(i=>i.clearObjectOpacity(e)),this.enableRender()}setModelOpacity(e){this.loadedModels.find(s=>s.modelId===e)?.setOpacity(),this.enableRender()}clearModelOpacity(e){this.loadedModels.find(s=>s.modelId===e)?.clearOpacity(),this.enableRender()}setModelsOpacity(e){this.loadedModels.forEach(i=>i.setOpacity(e)),this.enableRender()}clearModelsOpacity(){this.loadedModels.forEach(e=>e.clearOpacity()),this.enableRender()}setObjectVisible(e,i){this.loadedModels.forEach(s=>s.setObjectVisible(e,i)),this.enableRender()}hideOtherObjects(e){this.loadedModels.forEach(i=>{i.setVisible(!1),i.setObjectVisible(e,!0)}),this.enableRender()}setModelVisible(e,i){this.loadedModels.find(n=>n.modelId===e)?.setVisible(i),this.enableRender()}setModelsVisible(e){this.loadedModels.forEach(i=>i.setVisible(e)),this.enableRender()}enableModelOutline(e,i){this.loadedModels.find(n=>n.modelId===e)?.enableOutline(i),this.enableRender()}enableModelsOutline(e){this.loadedModels.forEach(i=>i.enableOutline(e)),this.enableRender()}setObjectHighlight(e){this.loadedModels.forEach(i=>i.highlightObject(e)),this.enableRender()}clearHighlight(){this.loadedModels.forEach(e=>e.clearHighlight()),this.enableRender()}setDoubleSidedMaterials(){this.loadedModels.forEach(e=>e.setDoubleSidedMaterials()),this.enableRender()}revertDoubleSidedMaterials(){this.loadedModels.forEach(e=>e.revertDoubleSidedMaterials()),this.enableRender()}clearSelection(){this.selectedObject instanceof Nt&&(this.selectedObject.selected=!1),this.selectedObject=void 0,this.clearHighlight()}get enableSelection(){return this._enableSelection}set enableSelection(e){e||this.clearSelection(),this._enableSelection=e}hasVisibleObject(){for(const e of this.loadedModels)if(e.hasVisibleObject())return!0;return!1}hasInvisibleObject(){for(const e of this.loadedModels)if(e.hasInvisibleObject())return!0;return!1}enableSsao(e){this.effect.enabled=e,this.effect.renderPassEnabled=e,this.effect.ssaaPassEnabled=e,this.effect.ssaoPassEnabled=e}getSsaoEnabled(){return this.effect.enabled&&this.effect.ssaoPassEnabled}async setEnvironmentData(e){await this.sceneManager.setEnvironmentFromData(e),this.enableRender()}async setEnvironment(e){await this.sceneManager.setEnvironment(e),this.enableRender()}showVertexNormals(e,i=.1){this.effect.showVertexNormals(e,i)}getLights(){return{sun:this.sceneManager.directionalLight,ambient:this.sceneManager.ambientLight,hemisphere:this.sceneManager.hemisphereLight}}debugLights(e){this.sceneManager.debugLights(e)}setModelClipPlanes(e,i){this.loadedModels.find(n=>n.modelId===""+e)?.setClipPlanes(i),this.enableRender()}setGlobalClipPlanes(e){const i=e.length>0;this.sceneManager.enableClipping(i),this.sceneManager.setClipPlanes(e)}}function mo(c){return Object.assign(Object.assign({},{asset:"",version:"",datetime:"",root:"",modelSize:0,generateTool:""}),c)}function go(c){return Object.assign(Object.assign({},{elementCount:0,batchElementCount:0,instanceElementCount:0,batchCount:0,instanceCount:0,tileCount:0,userDataCount:0,materialCount:0,meshVertexCount:0,meshFaceCount:0,textureCount:0,texturePixels:0}),c)}function Lu(c){const t={transform:new p.Matrix4,boundingVolume:new p.Box3};return Object.assign(Object.assign({},t),c)}class Ru{constructor(t){g(this,"url");g(this,"metadata");g(this,"statistics");g(this,"view");this.url=t,this.metadata=mo(),this.statistics=go(),this.view=Lu()}async parse(){return await fetch(this.url).then(t=>t.ok?t.json():(P.error('[BimTiles] Failed to request "'+this.url+'", status '+t.status+" : "+t.statusText),Promise.reject(!1))).then(t=>(this.metadata=mo(t.metadata),this.statistics=go(t.statistics),t.view.transform&&t.view.transform.length===16&&this.view.transform.fromArray(t.view.transform),t.view.boundingVolume&&t.view.boundingVolume.length===6&&this.view.boundingVolume.setFromArray(t.view.boundingVolume),Promise.resolve(!0)))}getMetadata(){return this.metadata}getStatistics(){return this.statistics}getView(){return this.view}}let Fu=0;class zu extends Mn{constructor(e,i){super(e);g(this,"name");g(this,"pickUsageScene");g(this,"effect");g(this,"loadedModels");g(this,"selectedObject");g(this,"enableHoverEffect");if(this.name=$e.BimTilesViewer,this.loadedModels=[],this.enableHoverEffect=!1,this.effect=new yl(this),this.pickUsageScene=new p.Scene,this.sceneManager.enableLights(!0),i)this.setHomeView(i),this.cameraManager.flyToViewpoint(i);else{const s=new p.Vector3(100,50,100),n=new p.Vector3(0,0,0),r={eye:s,look:n};this.cameraManager.flyToViewpoint(r)}this.cameraManager.setProjection(bt.Perspective),this.cameraManager.setNavigationMode(lt.Orbit),this.setupDefaultEvents(),this.setDefaultBackground(),this.addEventListener(le.BeforeRender,()=>{this.update3dTiles()})}setupDefaultEvents(){let e=!1,i,s=0,n=0,r=0;const a=300,o=u=>n===-1||r===-1?!1:Math.abs(u.x-n)<5&&Math.abs(u.y-r)<5,l=u=>{const f=u.timestamp-s;return!!(u.button===Je.Left&&f<a&&o(u))};let h,d=!1;this.inputManager.addEventListener("pointerdown",u=>{e=!1,i=u.button,this.renderImmediately();const f=new p.Vector2(u.x,u.y);if(h=this.pickManager.pick(f,this.pickUsageScene),d=!!this.selectedObject&&h?.tilesetId===this.selectedObject?.tilesetId&&h?.userId===this.selectedObject?.userId,u.button===Je.Left){let m=this.pickUsageScene;if(h){const y=this.loadedModels.find(S=>S.modelId===""+h?.tilesetId);if(y){const S=y.getObjectByUserId(h.userId);S&&(m=S)}}const b=this.pickManager.pickObject(f,[m]);this.handleAnchorPoint(b)}}),this.inputManager.addEventListener("pointermove",u=>{if(i!==void 0)e=!o(u),i===Je.Left&&this.cameraManager.enableRotate&&this.cameraManager.setOrbitPointVisible(!0);else if(this.enableHoverEffect){const f=new p.Vector2(u.x,u.y),m=this.pickManager.pick(f,this.pickUsageScene),b=this.getHoveredObject();m?(!b||b.tilesetId!==m.tilesetId||b.userId!==m.userId)&&this.setObjectHoveredByUserId(m.tilesetId,m.userId,!0):b&&this.clearHovered()}this.handleMouseMove(u)}),this.inputManager.addEventListener("pointerup",u=>{if(i=void 0,this.cameraManager.setOrbitPointVisible(!1),e){e=!1;return}u.button===Je.Left?l(u)?(h?this.flyToUserId(h.tilesetId,h.userId):this.viewFitAll(),s=0,n=-1,r=-1):(this.selectedObject&&(this.clearHighlight(),this.selectedObject=void 0),s=u.timestamp,n=u.x,r=u.y,h&&!d&&this.handleClickObject(h)):(u.button,Je.Right)})}setDefaultBackground(){this.sceneManager.setBackground(new p.Color(11119017)),this.sceneManager.setEnvironmentFromData()}renderImmediately(){const{renderer:e,scene:i,camera:s}=this;!e||!i||!s||e.render(i,s)}handleAnchorPoint(e){const i=new p.Vector3;this.selectedObject?this.getBoxByUserId(this.selectedObject.tilesetId,this.selectedObject.userId)?.getCenter(i):e&&e.point?i.copy(e.point):this.getBBox().getCenter(i),this.cameraManager.setOrbitPoint(i),this.cameraManager.update(0)}handleClickObject(e){if(!this.enableSelection)return;const i=this.loadedModels.find(s=>s.modelId===""+e.tilesetId);i&&(i?.setObjectHighlightedByUserIds([e.userId],!0),this.selectedObject=e),this.enableRender()}is3d(){return!0}setModelOpacity(e,i){this.loadedModels.find(n=>n.modelId===e)?.setOpacity(i),this.enableRender()}clearModelOpacity(e){this.loadedModels.find(s=>s.modelId===e)?.clearOpacity(),this.enableRender()}setModelsOpacity(e){this.loadedModels.forEach(i=>i.setOpacity(e)),this.enableRender()}clearModelsOpacity(){this.loadedModels.forEach(e=>e.clearOpacity()),this.enableRender()}enableModelOutline(e,i){P.warn("Outline for bimtiles is not implemented yet.")}enableModelsOutline(e){P.warn("Outline for bimtiles is not implemented yet.")}setModelVisible(e,i){this.loadedModels.find(n=>n.modelId===e)?.setVisible(i),this.enableRender()}setModelsVisible(e){this.loadedModels.forEach(i=>i.setVisible(e)),this.enableRender()}clearHighlight(){this.loadedModels.forEach(e=>e.clearHighlight()),this.enableRender()}setDoubleSidedMaterials(){this.loadedModels.forEach(e=>e.setDoubleSidedMaterials()),this.enableRender()}revertDoubleSidedMaterials(){this.loadedModels.forEach(e=>e.revertDoubleSidedMaterials()),this.enableRender()}clearSelection(){this.selectedObject instanceof Nt&&(this.selectedObject.selected=!1),this.selectedObject=void 0,this.clearHighlight()}get enableSelection(){return this._enableSelection}set enableSelection(e){e||this.clearSelection(),this._enableSelection=e}flyToUserId(e,i){const s=this.getBoxByUserId(e,i);s&&this.cameraManager.flyToBox(s)}getBoxByUserId(e,i){const s=this.loadedModels.find(n=>n.modelId===""+e);if(s)return s.getBBoxByUserId(i)}handleMouseMove(e){}update3dTiles(){if(!this.camera)return;const e=this.loadedModels.filter(i=>!!i.tilesRenderer);e.length!==0&&(this.camera.updateMatrixWorld(),e.forEach(i=>{i.tilesRenderer.update()}))}async loadModel(e,i){if(e.src.length===0)return Promise.reject();const s=new Ru(e.src);if(!await s.parse())return Promise.reject();let r=e.src.replace(/\/[^\\/]*\/?$/,"/");r=new URL(r,window.location.href).toString(),this.spinner.increaseJobCount();try{const a=s.getView().boundingVolume.clone();a.applyMatrix4(s.getView().transform);const o=new Lr({modelId:""+Fu++,bbox:a},r,s),l=o.getTilesRenderer(),h=l.group;if(l.onBeforeParseTile=()=>{this.spinner.increaseJobCount()},l.onLoadModel=d=>{d.traverse(u=>{!et&&u.matrixAutoUpdate&&(u.matrixAutoUpdate=et,u.updateMatrix()),u.isMesh&&(u.castShadow=!0,u.receiveShadow=!0),u.geometry&&u.layers.enableAll()}),this.enableRender(),setTimeout(()=>this.spinner.decreaseJobCount(),100)},l.setCamera(this.camera),l.setResolutionFromRenderer(this.camera,this.renderer),l.update(),h){h.applyMatrix4(s.getView().transform),o.pickUsageGroup.applyMatrix4(s.getView().transform),this.pickUsageScene.add(o.pickUsageGroup),this.addModel(o),this.cameraManager.adjustCameraByBBox(a);const d=new p.Vector3;return a.getCenter(d),this.cameraManager.setOrbitPoint(d),this.loadedModels.length===1&&this.goToHomeView(),this.dispatchEvent(le.ModelLoad),Promise.resolve()}return Promise.reject()}finally{this.spinner.decreaseJobCount()}}setObjectHighlightedByUserIds(e,i,s){this.loadedModels.find(r=>r.modelId===""+e)?.setObjectHighlightedByUserIds(i,s),this.enableRender()}setObjectOpacityByUserIds(e,i,s){this.loadedModels.find(r=>r.modelId===""+e)?.setObjectOpacityByUserIds(i,s),this.enableRender()}setOtherObjectOpacityByUserIds(e,i,s){this.loadedModels.forEach(a=>{a.setOpacity(s)});const n=""+e;this.loadedModels.find(a=>a.modelId===n)?.clearObjectOpacityByUserIds(i),this.enableRender()}setObjectVisibleByUserIds(e,i,s){this.loadedModels.find(r=>r.modelId===""+e)?.setObjectVisibleByUserIds(i,s),this.enableRender()}setOtherObjectVisibleByUserIds(e,i,s){this.loadedModels.forEach(r=>{r.setVisible(s)}),this.loadedModels.find(r=>r.modelId===""+e)?.setObjectVisibleByUserIds(i,!s),this.enableRender()}setObjectHoveredByUserId(e,i,s){if(!this.enableHoverEffect)return;this.clearHovered(),this.loadedModels.find(r=>r.modelId===""+e)?.setObjectHoveredByUserId(i,s),this.enableRender()}getHoveredObject(){for(const e of this.loadedModels){const i=e.getHoveredObject();if(i)return i}}clearHovered(){this.loadedModels.forEach(e=>e.clearHovered()),this.enableRender()}hasVisibleObject(){for(const e of this.loadedModels)if(e.hasVisibleObject())return!0;return!1}hasInvisibleObject(){for(const e of this.loadedModels)if(e.hasInvisibleObject())return!0;return!1}setModelClipPlanes(e,i){this.loadedModels.find(n=>n.modelId===""+e)?.setClipPlanes(i),this.enableRender()}setGlobalClipPlanes(e){const i=e.length>0;this.sceneManager.enableClipping(!i),this.sceneManager.setClipPlanes(e)}showVertexNormals(e,i=.1){this.effect.showVertexNormals(e,i)}getLights(){return{sun:this.sceneManager.directionalLight,ambient:this.sceneManager.ambientLight,hemisphere:this.sceneManager.hemisphereLight}}debugLights(e){this.sceneManager.debugLights(e)}pickObjects(e,i){const s=this.pickManager.pick(e,this.pickUsageScene);let n=this.pickUsageScene;if(s){const a=this.loadedModels.find(o=>o.modelId===""+s?.tilesetId);if(a){const o=a.getObjectByUserId(s.userId);o&&(n=o)}}let r=this.pickManager.pickObjects(e,[n],i);return r&&this.renderer.clippingPlanes.length>0&&(r=r.filter(a=>this.renderer.clippingPlanes.every(function(o){return o.distanceToPoint(a.point)>0}))),r}getErrorTarget(){return this.loadedModels.length>0?this.loadedModels[0].getTilesRenderer().errorTarget:8}setErrorTarget(e){this.loadedModels.forEach(i=>{i.getTilesRenderer().errorTarget=e})}}class Vu extends Ht{constructor(e,i){if(!i.id)throw new Error("[Plugin] Missing plugin id!");super();g(this,"id");g(this,"viewer");this.id=i.id,this.viewer=e,e.addPlugin(this)}destroy(){this.viewer.removePlugin(this)}}$.install({THREE:p});class ju extends ${constructor(e,i){super(e,i);g(this,"minZoom");g(this,"draggingSmoothTime");g(this,"dollySpeedBackup");g(this,"azimuthRotateSpeedBackup");g(this,"polarRotateSpeedBackup");g(this,"truckSpeedBackup");g(this,"onKeyDown");g(this,"onKeyUp");g(this,"keyTruckSpeed");g(this,"keys");this.minZoom=0,this.draggingSmoothTime=0,this.keyTruckSpeed=7,this.keys={left:"ArrowLeft",up:"ArrowUp",right:"ArrowRight",bottom:"ArrowDown"},this.onKeyDown=s=>{if(this.enabled){switch(s.code){case this.keys.up:s.ctrlKey||s.metaKey||s.shiftKey?(this._rotateInternal(0,1),this._isUserControllingRotate=!0):(this._truckInternal(0,this.keyTruckSpeed,!1),this._isUserControllingTruck=!0);break;case this.keys.bottom:s.ctrlKey||s.metaKey||s.shiftKey?(this._rotateInternal(0,-1),this._isUserControllingRotate=!0):(this._truckInternal(0,-this.keyTruckSpeed,!1),this._isUserControllingTruck=!0);break;case this.keys.left:s.ctrlKey||s.metaKey||s.shiftKey?(this._rotateInternal(1,0),this._isUserControllingRotate=!0):(this._truckInternal(this.keyTruckSpeed,0,!1),this._isUserControllingTruck=!0);break;case this.keys.right:s.ctrlKey||s.metaKey||s.shiftKey?(this._rotateInternal(-1,0),this._isUserControllingRotate=!0):(this._truckInternal(-this.keyTruckSpeed,0,!1),this._isUserControllingTruck=!0);break}this.dispatchEvent({type:"control"})}},this.onKeyUp=s=>{this.dispatchEvent({type:"controlend"})},this._getClientRect(this._elementRect),this.dollySpeedBackup=this.dollySpeed,this.azimuthRotateSpeedBackup=this.azimuthRotateSpeed,this.polarRotateSpeedBackup=this.polarRotateSpeed,this.truckSpeedBackup=this.truckSpeed}get enableZoom(){return!!this.dollySpeed}set enableZoom(e){e?this.dollySpeed=this.dollySpeedBackup:(this.dollySpeedBackup=this.dollySpeed,this.dollySpeed=0)}get enableRotate(){return!!this.azimuthRotateSpeed||!!this.polarRotateSpeed}set enableRotate(e){e?(this.azimuthRotateSpeed=this.azimuthRotateSpeedBackup,this.polarRotateSpeed=this.polarRotateSpeedBackup):(this.azimuthRotateSpeedBackup=this.azimuthRotateSpeed,this.polarRotateSpeedBackup=this.polarRotateSpeed,this.azimuthRotateSpeed=0,this.polarRotateSpeed=0)}get enableTruck(){return!!this.truckSpeed}set enableTruck(e){e?this.truckSpeed=this.truckSpeedBackup:(this.truckSpeedBackup=this.truckSpeed,this.truckSpeed=0)}listenToKeyEvents(){this._domElement?.addEventListener("keydown",this.onKeyDown),this._domElement?.addEventListener("keyup",this.onKeyUp)}stopListenToKeyEvents(){this._domElement?.removeEventListener("keydown",this.onKeyDown),this._domElement?.removeEventListener("keyup",this.onKeyUp)}dispose(){super.dispose(),this.stopListenToKeyEvents()}}var xl=(c=>(c[c.Browser=0]="Browser",c[c.Browserless=1]="Browserless",c[c.Headless=2]="Headless",c))(xl||{});class Uu{constructor(t,e,i){g(this,"containerOrCanvas");g(this,"glContext");g(this,"camera");g(this,"scene");g(this,"renderer");g(this,"renderTarget");g(this,"controls");g(this,"selectedObject");g(this,"loadedModels");g(this,"pmremGenerator");g(this,"clock");g(this,"viewerMode");g(this,"raycaster");g(this,"savedMaterialsForOpacity");g(this,"jobCount");g(this,"bbox");g(this,"outlineMaterial");g(this,"outlineRoot");g(this,"transparentObjectIds");g(this,"requestAnimationFrameHandle");g(this,"applyOptionsAndAddToScene");g(this,"getMeshes");if(this.scene=this.initScene(),this.selectedObject=void 0,this.loadedModels=[],this.clock=new p.Clock,this.viewerMode=0,this.raycaster=new p.Raycaster,this.savedMaterialsForOpacity=[],this.jobCount=0,this.bbox=new p.Box3,this.outlineMaterial=new p.LineBasicMaterial({color:1118481}),this.outlineRoot=new p.Group,this.transparentObjectIds=[],this.applyOptionsAndAddToScene=async(s,n,r,a)=>{if(P.info("[Viewer] '"+s+"' is loaded, adding to scene..."),r.matrix&&r.matrix.length===16){const u=new p.Matrix4;u.elements=r.matrix,n.applyMatrix4(u)}n.traverse(u=>{u.geometry&&u.layers.enableAll(),u instanceof p.Light&&(u.visible=!1)});let o;r.edges&&(o=await J.createOutlines(n,void 0,a));let l=r.modelId||r.src;const h=u=>!!this.loadedModels.find(f=>f.modelId===u);if(h(l)){let u=1;for(;h(l+"_"+u);)u++;l=l+"_"+u,P.warn("[Viewer] Model '"+l+"' is loaded more than once!")}const d={modelId:l,object:n,edges:o};this.addModel(d)},this.getMeshes=s=>{const n=[];return s instanceof p.Mesh?n.push(s):s.traverseVisible(r=>{r instanceof p.Mesh&&n.push(r)}),n},this.containerOrCanvas=t,e&&(this.viewerMode=e),this.glContext=i,this.viewerMode===1&&!(!(t instanceof HTMLDivElement)&&i))throw new Error("[Viewer] Parameters don't match Browserless viewerMode !");this.increaseJobCount(),this.init(),this.decreaseJobCount(),P.info("[Viewer] Initialized"),this.animate()}init(){this.initRenderer(),this.initCamera(),this.initControls(),this.initLights(),this.initPointerEvents(),this.scene.add(this.outlineRoot)}initScene(){const t=new p.Scene;return t.background=new p.Color(7112861),t.matrixAutoUpdate=!0,t}isBrowserlessMode(){return this.viewerMode===1}isBrowserMode(){return this.viewerMode===0}initRenderer(){const t={antialias:!0,preserveDrawingBuffer:!0},e=this.isBrowserlessMode();e&&Object.assign(t,{canvas:this.containerOrCanvas,context:this.glContext});let i;try{i=new p.WebGLRenderer(t)}catch(s){if(e||!t.antialias)throw s;i=new p.WebGLRenderer({canvas:this.containerOrCanvas}),P.warn("WebGL context created with fallback settings (antialias disabled).")}if(e){const s=this.containerOrCanvas.width,n=this.containerOrCanvas.height;P.info("[Viewer] Render target size: "+s+" x "+n),this.renderTarget=new p.WebGLRenderTarget(s,n,{minFilter:p.LinearFilter,magFilter:p.NearestFilter,format:p.RGBAFormat,type:p.UnsignedByteType}),i.setRenderTarget(this.renderTarget)}else{const s=this.containerOrCanvas.clientWidth,n=this.containerOrCanvas.clientHeight;this.containerOrCanvas.append(i.domElement),i.setPixelRatio(window.devicePixelRatio),i.setSize(s,n)}i.outputColorSpace=p.SRGBColorSpace,i.toneMappingExposure=1,i.setClearColor(11119017,1),i.shadowMap.enabled=!0,i.shadowMap.type=p.PCFSoftShadowMap,this.renderer=i,e||(this.pmremGenerator=new p.PMREMGenerator(i),this.pmremGenerator.compileEquirectangularShader(),this.setEnvironmentFromDataArray())}initCamera(){if(!this.scene)return;const t=this.containerOrCanvas.clientWidth||this.containerOrCanvas.width||0,e=this.containerOrCanvas.clientHeight||this.containerOrCanvas.height||0;let i=1;t&&e&&(i=t/e),this.camera=new p.PerspectiveCamera(68,i,.05,1e4),this.camera.position.set(10,10,10),this.camera.lookAt(0,0,0),this.scene.add(this.camera)}initControls(){if(!this.renderer)return;const t=this.camera;if(!t)return;const e=new ju(t,this.renderer.domElement);e.smoothTime=.05,e.enabled=!0,e.keyTruckSpeed=10,e.keys={left:"KeyD",up:"KeyE",right:"KeyA",bottom:"KeyQ"},e.update(0),this.controls=e,e.addEventListener("update",()=>{!this.isBrowserMode()&&this.renderer&&this.renderer.render(this.scene,t)})}initLights(){if(!this.scene)return;const t=16777215,e=.3,i=new p.DirectionalLight(t,e);i.position.set(-2,2,4);const s=new p.AmbientLight(3158064),n=new p.HemisphereLight(t,14540253,3);n.position.set(0,300,0),this.scene.add(i),this.scene.add(s),this.scene.add(n)}initPointerEvents(){if(!this.renderer||!this.camera||!this.controls)return;let t=!1,e=!1,i=-1,s=-1;this.renderer.domElement.addEventListener("pointerdown",n=>{i=n.x,s=n.y,t=!1}),this.renderer.domElement.addEventListener("pointermove",n=>{i>=0&&s>=0&&(Math.abs(n.x-i)>5||Math.abs(n.y-s)>5)&&(t=!0)}),this.renderer.domElement.addEventListener("pointerup",()=>{e&&setTimeout(()=>{e=!1},200),i=-1,s=-1}),this.renderer.domElement.addEventListener("dblclick",n=>{e=!0,t||(this.handleMouseClick(n),this.flyToSelectedObject())})}animate(){this.isBrowserMode()&&requestAnimationFrame(this.animate.bind(this));const t=this.clock.getDelta();this.controls&&this.controls.update(t),this.scene&&this.camera&&this.renderer?.render(this.scene,this.camera)}destroy(){this.camera=void 0,this.scene&&this.scene.clear(),this.requestAnimationFrameHandle&&(cancelAnimationFrame(this.requestAnimationFrameHandle),this.requestAnimationFrameHandle=void 0),this.renderer&&(this.containerOrCanvas.removeChild(this.renderer.domElement),this.renderer.clear(),this.renderer.dispose(),this.renderer=void 0),this.controls&&(this.controls.dispose(),this.controls=void 0),this.renderTarget&&(this.renderTarget.dispose(),this.renderTarget=void 0),this.raycaster=void 0,this.selectedObject=void 0,this.savedMaterialsForOpacity=void 0,this.loadedModels=[]}async loadLocalModel(t,e,i){const n=await new Vt().loadLocalModel(t,e.src,i);return n?(await this.applyOptionsAndAddToScene(t,n,e),Promise.resolve()):Promise.reject()}async loadModel(t,e){this.increaseJobCount();const s=await new Vt().loadModel(t.src,t.fileFormat,e);return s?(await this.applyOptionsAndAddToScene(t.src,s,t),Promise.resolve()):Promise.reject()}parseGltf(t,e,i,s){this.increaseJobCount(),new Vt().parseGltf(t,e.src,n=>{this.applyOptionsAndAddToScene(e.src,n,e),i&&i(n)},n=>{s&&s(n)})}addModel(t){if(!this.scene||!this.renderer)return;this.increaseJobCount();const e=new p.Box3().setFromObject(t.object);t.bbox||(t.bbox=e),this.scene.add(t.object),this.loadedModels.push(t),this.computeBoundingBox(),this.loadedModels.length===1&&(this.tryAdjustCameraNearAndFar(),this.goToHomeView()),this.renderer.shadowMap.needsUpdate=!0,P.info("[Viewer] Added '"+t.modelId+"' to scene"),this.decreaseJobCount()}addOrRemoveObjectOpacity(t=!0,e=.3,i,s){if(this.savedMaterialsForOpacity||(this.savedMaterialsForOpacity=[]),!this.scene)return;const n=this.scene,r=[];this.loadedModels.forEach(a=>{const o=a.object.id;if(t){this.savedMaterialsForOpacity&&this.savedMaterialsForOpacity.length>0&&J.revertObjectOpacityById(n,o,this.savedMaterialsForOpacity);const l=J.setObjectOpacityById(n,o,e,i,s);r.push(...l)}else this.savedMaterialsForOpacity&&J.revertObjectOpacityById(n,o,this.savedMaterialsForOpacity)}),t?this.savedMaterialsForOpacity=r:this.savedMaterialsForOpacity=[]}hasTransparentObject(){return!!(this.savedMaterialsForOpacity&&this.savedMaterialsForOpacity.length>0)}getIntersections(t){if(!this.raycaster||!this.camera||!this.scene)return[];let e=new p.Vector2;t&&(e=Oe.getScreenCoordinateByEvent(t,this.containerOrCanvas));const i=Oe.screen2Ndc(e,this.camera,this.containerOrCanvas);this.raycaster.setFromCamera(i,this.camera);const s=[];return this.loadedModels.forEach(n=>{const r=n.object;r&&r.visible&&s.push(r)}),this.raycaster.intersectObjects(s,!0)||[]}handleMouseClick(t){this.raycaster&&this.raycaster.layers.set(Ut);const i=this.getIntersections(t).find(n=>{const r=n.object;return r.visible&&r instanceof p.Mesh});let s=i&&i.object||void 0;s&&this.selectedObject&&this.selectedObject.id===s.id&&(s=void 0),s?this.selectObject(s):this.clearSelection()}selectObject(t){if(this.selectedObject){const i=this.selectedObject.userData;if(i.originalMaterial){if(this.selectedObject.material){const s=this.selectedObject.material;Array.isArray(s)?s.forEach(n=>n.dispose()):s instanceof p.Material&&s.dispose()}this.selectedObject.material=i.originalMaterial,delete i.originalMaterial}this.selectedObject=void 0}if(!this.scene||!t)return;const e=be.clonedHighlightMaterials(t);e&&(this.selectedObject=t,this.selectedObject.userData.originalMaterial=this.selectedObject.material,this.selectedObject.material=e)}clearSelection(){this.selectObject()}flyToObjects(t){if(!t||t.length===0||!this.camera)return;const e=new p.Box3;t.forEach(n=>{const r=_t.getBoundingBox(n);e.union(r)});const i=new p.Sphere;e.getBoundingSphere(i),this.controls?.fitToSphere(i,!0)}flyToObject(t){this.flyToObjects([t])}flyToSelectedObject(){this.selectedObject&&this.flyToObject(this.selectedObject)}flyTo(t,e,i){const s=this.camera,n=this.controls;if(!s||!n)return;t=Array.isArray(t)?new p.Vector3(t[0],t[1],t[2]):t,e=Array.isArray(e)?new p.Vector3(e[0],e[1],e[2]):e;const r=t,a=e;P.info("[Viewer] flyTo: ",j.vectorToString(r)),n.setPosition(r.x,r.y,r.z),n.setTarget(a.x,a.y,a.z),this.isBrowserMode()||this.renderer?.render(this.scene,s),i&&i()}goToHomeView(){const t=new p.Sphere;this.bbox.getBoundingSphere(t),this.controls?.fitToSphere(t,!0)}setEnvironmentFromDataArray(t){ms.createEnvTextureFromDataArray(this.pmremGenerator,t).then(e=>{this.scene.environment=e,this.isBrowserMode()||this.animate()})}tryAdjustCameraNearAndFar(){const t=this.camera;if(!this.scene||!t)return;const e=this.bbox,i=t.near,s=t.far,n=e.max.x-e.min.x,r=e.max.y-e.min.y,a=e.max.z-e.min.z,o=Math.max(n,r,a),l=5,h=o/l,d=o*l;if(i>h||s<d){const u=f=>j.numberToString(f);P.info("[Viewer] BBox's longest side is: "+u(o)),i>h&&(P.warn("[Viewer] camera.near("+u(i)+") shouldn't bigger than "+u(h)+", will change it!"),t.near=h),s<d&&(P.warn("[Viewer] camera.far("+u(s)+") shouldn't smaller than "+u(d)+", will change it!"),t.far=d)}t.updateProjectionMatrix()}isolateObjects(t){const e=this.transparentObjectIds.length>0?void 0:this.transparentObjectIds,i=this.transparentObjectIds.length>0?this.transparentObjectIds:void 0,s=new p.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.1});this.loadedModels.forEach(r=>{const a=r.object.id;J.applyMaterialToObjectById(this.scene,a,s,i,e)}),this.outlineRoot.clear();let n=[];if(t.forEach(r=>{const a=r.modelId;let l=this.loadedModels.find(h=>h.modelId===a)?.object;l||(P.warn("[Viewer] The ModelId of "+a+" has no corresponding model."),l=this.scene),l.traverse(h=>{if(jr.includes(r.id,jr.get(h.userData,"UniqueId"))){const d=this.getMeshes(h);n=n.concat(d)}})}),n.length>0){n.forEach(a=>{const o=J.createOutline(a.geometry,this.outlineMaterial);o.applyMatrix4(a.matrixWorld),this.outlineRoot.add(o),o.updateWorldMatrix(!0,!1)});const r=n.map(a=>a.id);this.loadedModels.forEach(a=>{const o=a.object.id;J.revertAppliedMaterialToObjectById(this.scene,o,r)}),this.transparentObjectIds=r,this.flyToObjects(n)}else P.warn("[Viewer] No object found with uniqueIds: "+t.map(r=>r.id));this.isBrowserMode()||this.animate()}increaseJobCount(){++this.jobCount}decreaseJobCount(){--this.jobCount}computeBoundingBox(){const t=new p.Box3;return this.loadedModels.forEach(e=>{e.bbox&&!e.bbox.isEmpty()&&t.union(e.bbox)}),this.bbox=t,t}getContext(){return this.renderer?.getContext()}getCameraDirection(){const t=new p.Vector3;return this.camera?.getWorldDirection(t),{x:t.x,y:t.y,z:t.z}}setFov(t){this.camera&&(this.camera.fov=t,this.camera.updateProjectionMatrix())}}const bl="1.0.0",wl="VERSION",vl=()=>window.localStorage.getItem(wl),Ml=()=>{window.localStorage.setItem(wl,bl)},Nu=()=>vl()!==bl?(Ml(),!0):!1;Object.defineProperty(exports,"Mesh",{enumerable:!0,get:()=>L.Mesh});exports.BaseDxfCompareHelper=ml;exports.BaseViewer=Mn;exports.BimTilesModel=Lr;exports.BimTilesRenderer=el;exports.BimTilesViewer=zu;exports.BinaryReader=vs;exports.BoxSelectHelper=xn;exports.ByBlock=gs;exports.ByLayer=Br;exports.CSS2DObjectUtils=Rh;exports.CameraProjection=bt;exports.CancelablePromise=kh;exports.CanvasRender=bs;exports.ColorUtils=Li;exports.CommonUtils=j;exports.CompareDrawable=wt;exports.Container=Rr;exports.ControlsMode=lt;exports.CoordinateUtils=Oe;exports.DecimalPrecisionRange=Co;exports.DefaultCameraFar=ln;exports.DefaultCameraFov=Oo;exports.DefaultCameraNear=on;exports.DefaultLanguage=So;exports.DefaultOpacity=Ar;exports.DefaultViewer3dConfig=su;exports.DeviceUtils=Be;exports.Drawable=Nt;exports.DrawableList=ws;exports.DxfChangeType=Ve;exports.DxfCompare=ot;exports.DxfCompareHelper=Bu;exports.DxfCompareMarkupManager=vr;exports.DxfLoader=X;exports.DxfParser=Ho;exports.DxfRenderOrder=ye;exports.DxfUtils=Tt;exports.EdgeUtils=_o;exports.Event=Ht;exports.ExportUtils=yr;exports.FontManager=xt;exports.FpsUtils=Gh;exports.GenerateMeshBvhWorker=cl;exports.GeometryUtils=H;exports.GroundPlaneRenderOrder=pl;exports.HighlightColor=Pr;exports.HighlightColorRgba=zh;exports.IconfontClass=Vh;exports.IconfontClass2=jh;exports.InputManager=fl;exports.InstantiateHelper=du;exports.LayerForHitableObjects=Eo;exports.LayerForSelectableObjects=Ut;exports.LayerForSnapableObjects=je;exports.Line=fc;exports.LinePatternShaders=Vo;exports.LoadingHelper=Vt;exports.MaterialUtils=be;exports.MathUtils=z;exports.MatrixAutoUpdate=et;exports.MergeUtils=fe;exports.MeshBvhHelper=zr;exports.MobileTouchHelperDrawable=_u;exports.Model=vn;exports.Model2d=Ri;exports.Model3d=kr;exports.NestedCompareTypes=os;exports.OSnapHelper=Tu;exports.OSnapIconSize=Qh;exports.OSnapMarkerType=Et;exports.OSnapType=hl;exports.ObjectPixelSizeHelper=gu;exports.ObjectUtils=J;exports.Offset=ku;exports.OrbitControls=sl;exports.OutlineColorRgba=an;exports.PickMarkupHelper=Cu;exports.PlanControls=nl;exports.Plugin=Vu;exports.Points=gh;exports.PolygonUtils=$h;exports.ProgressBar=Fr;exports.RafHelper=ol;exports.SVGObjectUtils=ed;exports.SceneUtils=_t;exports.SectionUtils=zt;exports.ShaderChunk=Bh;exports.SimplifyUtils=Jh;exports.SnapDrawable=_e;exports.Spinner=tl;exports.TextSearchHelper=Mr;exports.TextureUtils=ms;exports.ThresholdAngleForEdge=Ir;exports.UnitConversionByMeter=xr;exports.UnitLabels=Io;exports.UnitScaleConversion=md;exports.UnitScaleToMeter=wr;exports.Units=Ke;exports.Viewer2d=Vr;exports.Viewer3d=Du;exports.Viewer3dLite=Uu;exports.Viewer3dUtils=sd;exports.ViewerEvent=le;exports.ViewerMode=xl;exports.ViewerName=$e;exports.Views=ko;exports.ZoomToRectHelper=ul;exports.bspline=Lo;exports.checkIsNewVersion=Nu;exports.cn=Ao;exports.createHatchPatternShaderMaterial=jo;exports.decodeDxfTextCharacterCodes=Ro;exports.decodeDxfTextMbcsCharacterCodes=zo;exports.decodeDxfTextUnicodeCodePoints=Fo;exports.en=Po;exports.getLengthValueByUnit=id;exports.getUnitStr=br;exports.getVersionFromLocalStorage=vl;exports.i18n=We;exports.log=P;exports.parseDxfMTextContent=ls;exports.parseDxfTextContent=cn;exports.round10=Do;exports.setIcon=Lh;exports.setLogLevel=To;exports.setVersionToLocalStorage=Ml;exports.showPrecisionValue=Fh;
1533
+ `,ao=typeof self<"u"&&self.Blob&&new Blob(["(self.URL || self.webkitURL).revokeObjectURL(self.location.href);",ll],{type:"text/javascript;charset=utf-8"});function mu(c){let t;try{if(t=ao&&(self.URL||self.webkitURL).createObjectURL(ao),!t)throw"";const e=new Worker(t,{name:c?.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;charset=utf-8,"+encodeURIComponent(ll),{name:c?.name})}}class cl{constructor(){g(this,"running");g(this,"worker");this.running=!1,this.worker=new mu,this.worker.onerror=t=>{throw t.message?new Error(`[GenerateMeshBVHWorker] Could not create Web Worker with error "${t.message}"`):new Error("[GenerateMeshBVHWorker] Could not create Web Worker.")}}isRunning(){return this.running}generate(t,e={}){if(this.running){P.warn("[GenerateMeshBVHWorker] Already running job.");return}if(!this.worker){P.warn("[GenerateMeshBVHWorker] Worker has been disposed.");return}const{worker:i}=this;this.running=!0;const s=new Map;t.forEach(r=>{s.set(r.id,r)});let n=0;return new Promise((r,a)=>{const o=()=>{++n===s.size&&(this.running=!1,i.onmessage=null,r())};i.onerror=l=>{P.warn("[GenerateMeshBVHWorker] "+l.message),a(new Error("[GenerateMeshBVHWorker] "+l.message)),this.running=!1},i.onmessage=l=>{this.running=!1;const{data:h}=l;if(h.error)P.warn(h.error),o();else if(h.serialized){const{serialized:d,position:u,id:f}=h,m=s.get(f),b=ps.deserialize(d,m,{setIndex:!1}),y=Object.assign({setBoundingBox:!0},e);if(y.transferred&&(m.attributes.position.array=u),m.index)e.saveOriginalIndex&&!m.userData.originalIndex&&(m.userData.originalIndex=m.index.array),P.debug("before update, index:",m.index.array),m.index.array=d.index;else{const S=new L.BufferAttribute(d.index,1,!1);m.setIndex(S)}m.index&&(P.debug("after update, index:",m.index.array),m.index.needsUpdate=!0),y.setBoundingBox&&!m.boundingBox&&(m.boundingBox=b.getBoundingBox(new L.Box3)),m.boundsTree=b,o()}else e.onProgress&&e.onProgress(h.progress)};for(const[l,h]of s){const d=h.index?h.index.array:void 0,u=h.attributes.position,f=u.array;if(u.isInterleavedBufferAttribute||d&&d.isInterleavedBufferAttribute){P.warn("[GenerateMeshBVHWorker] InterleavedBufferAttribute are not supported for the geometry attributes."),o();continue}const m=[];e.transferred&&(m.push(f),d&&(m.push(d),e.saveOriginalIndex&&(h.userData.originalIndex=d.slice()))),i.postMessage({id:l,index:d,position:f,options:Object.assign(Object.assign({},e),{onProgress:null,includedProgressCallback:!!e.onProgress,groups:[...h.groups]})},m.length>0?m.map(b=>b.buffer):[])}})}dispose(){this.worker.terminate(),this.worker=void 0}}class zr{constructor(t){g(this,"running");g(this,"workers");this.running=!1,this.workers=[];let e=1;t?e=t:window.navigator&&(e=Math.max(e,window.navigator.hardwareConcurrency-1));for(let i=0;i<e;i++)this.workers[i]=new cl}isRunning(){return this.running}async generate(t,e={}){if(this.running){P.warn("[BVHHelper] Already running job.");return}if(this.workers.length===0){P.warn("[BVHHelper] Worker has been disposed.");return}return this.running=!0,new Promise(i=>{const s=this.workers.length,n=t.length,r=[],a=Math.floor(n/s),o=n%s;let l=0,h=0;for(let d=0;d<s;d++){const u=this.workers[d];if(d<o?(l=d*a+d,h=l+a+1):(l=d*a+o,h=l+a),l=Math.min(l,n),h=Math.min(h,n),l>=h)break;P.debug("startIndex: "+l+" endIndex: "+h),r.push(u.generate(t.slice(l,h),e))}Promise.allSettled(r).then(()=>{this.running=!1,i()})})}dispose(){for(let t=0;t<this.workers.length;t++)this.workers[t].dispose();this.workers=[]}static createMeshBvhSync(t,e={}){const i=new Set;t.forEach(s=>{s.traverse(n=>{const r=n;if(r.isMesh&&r.geometry&&fe.isMergedMesh(r)&&!(r instanceof p.InstancedMesh)){if(i.has(r.geometry.id))return;r.geometry.index&&e.saveOriginalIndex&&(r.geometry.userData.originalIndex=r.geometry.index.array.slice()),r.geometry.boundsTree=new ps(r.geometry,e),i.add(r.geometry.id)}})})}static createMeshBvhAsync(t,e={}){const i=new Set,s=[];t.forEach(r=>{r.traverse(a=>{const o=a;if(o.isMesh&&o.geometry&&fe.isMergedMesh(o)&&!(o instanceof p.InstancedMesh)){if(i.has(o.geometry.id))return;s.push(o.geometry),i.add(o.geometry.id)}})});const n=new zr;return n.generate(s,e).then(()=>{n.dispose()})}}class gu{constructor(t,e,i,s,n){g(this,"object");g(this,"camera");g(this,"targetPixelHeight",100);g(this,"canvasHeight",800);this.camera=t,this.object=i,this.targetPixelHeight=s,this.canvasHeight=n,this.adjustSize(),e.addEventListener("update",()=>{this.adjustSize()})}adjustSize(){const t=new p.Box3;if(this.object.updateMatrix(),t.expandByObject(this.object),!t)return;const e=t.max.x-t.min.x,i=this.camera.position.distanceTo(this.object.position),s=yu(e,i,this.canvasHeight);if(Math.abs(s-this.targetPixelHeight)<5)return;let r=this.object.scale.x;r*=this.targetPixelHeight/s,this.object.scale.set(r,r,r),this.object.updateMatrix()}}const yu=(c,t,e=800,i=45)=>{const s=i*(Math.PI/180),n=2*Math.tan(s/2)*t,r=c/n;return e*r},Js=new p.Vector2,Qs=new p.Vector2,en=new p.Vector2,oo=new p.Vector2,xu=new p.Vector2,bu=new p.Vector2,xe=class xe extends Nt{constructor(e){super(j.guid());g(this,"needsFrustumCulled");g(this,"renderOrder");g(this,"snapType");g(this,"osnapInfo");g(this,"drawSnapFunctions");g(this,"snapLineVisible");this.needsFrustumCulled=!1,this.renderOrder=1e3,this.snapType=Et.TripleCross,this.snapLineVisible=!1,this.snapType=e,this.drawSnapFunctions={TripleCross:this.drawTripleCorss.bind(this),Square:this.drawSquare.bind(this),Triangle:this.drawTriangle.bind(this),CircleWithCross:this.drawCircleWithCross.bind(this),Cross:this.drawCross.bind(this),Perpendicular:this.drawPerpendicular.bind(this)}}setSnapLineVisible(e){this.snapLineVisible=e}draw(e,i){this.osnapInfo&&(this.snapLineVisible&&this.drawSnapLine(e,i),e.save(),e.fillStyle=xe.FILL_COLOR_NONE,e.strokeStyle=xe.lineColor,e.lineWidth=xe.lineWidth,e.beginPath(),this.drawSnapFunctions[this.snapType](e,i),e.closePath(),e.fill(),e.stroke(),e.restore())}drawDebug(e,i){}drawSelect(e,i){}isPointInPath(e){return!1}drawSnapLine(e,i){e.save(),e.strokeStyle=xe.SNAP_LINE_COLOR,e.lineWidth=xe.lineWidth;const s=this.osnapInfo.line;if(!s)return;const n=this.transToScreenCoord(s.start,i),r=this.transToScreenCoord(s.end,i);e.moveTo(n.x,n.y),e.lineTo(r.x,r.y),e.stroke(),e.restore()}drawTripleCorss(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/1.6,r=Js.set(s.x,s.y-n),a=Qs.set(s.x-.87*n,s.y+n/1.4),o=en.set(s.x+.87*n,s.y+n/1.4);e.moveTo(s.x,s.y),e.lineTo(r.x,r.y),e.moveTo(s.x,s.y),e.lineTo(a.x,a.y),e.moveTo(s.x,s.y),e.lineTo(o.x,o.y)}drawSquare(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize,r=xe.iconSize;e.rect(s.x-n/2,s.y-r/2,n,r)}drawTriangle(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/1.6,r=Js.set(s.x,s.y-n),a=Qs.set(s.x-.87*n,s.y+n/2),o=en.set(s.x+.87*n,s.y+n/2);e.moveTo(r.x,r.y),e.lineTo(a.x,a.y),e.lineTo(o.x,o.y)}drawCircleWithCross(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/2;e.arc(s.x,s.y,n,0,Math.PI*2),e.moveTo(s.x-n/1.8,s.y),e.lineTo(s.x+n/1.8,s.y),e.moveTo(s.x,s.y-n/1.8),e.lineTo(s.x,s.y+n/1.8)}drawCross(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/2,r=Js.set(s.x-n,s.y-n),a=Qs.set(s.x+n,s.y+n),o=en.set(s.x+n,s.y-n),l=oo.set(s.x-n,s.y+n);e.moveTo(r.x,r.y),e.lineTo(a.x,a.y),e.moveTo(o.x,o.y),e.lineTo(l.x,l.y)}drawPerpendicular(e,i){const s=this.transToScreenCoord(this.osnapInfo.point,i),n=xe.iconSize/2,r=Js.set(s.x,s.y),a=Qs.set(s.x-n,s.y),o=en.set(s.x,s.y+n),l=oo.set(s.x-n,s.y-n),h=xu.set(s.x-n,s.y+n),d=bu.set(s.x+n,s.y+n);e.moveTo(a.x,a.y),e.lineTo(r.x,r.y),e.lineTo(o.x,o.y),e.moveTo(l.x,l.y),e.lineTo(h.x,h.y),e.lineTo(d.x,d.y),e.lineTo(l.x,l.y)}update(e){this.osnapInfo=e}getClassType(){return"SnapDrawable"}};g(xe,"lineColor","rgba(255, 119, 0, 1)"),g(xe,"FILL_COLOR_NONE","rgba(0, 0, 0, 0)"),g(xe,"SNAP_LINE_COLOR","rgba(255, 240, 0, 0.3)"),g(xe,"lineWidth",2),g(xe,"iconSize",14);let _e=xe;bs._registerDrawableClass(_e);var hl=(c=>(c[c.None=0]="None",c[c.Vertex=1]="Vertex",c[c.MiddlePoint=2]="MiddlePoint",c[c.Edge=4]="Edge",c[c.Face=8]="Face",c[c.FootOfPerpendicular=16]="FootOfPerpendicular",c[c.Intersection=32]="Intersection",c[c.CircleCenter=64]="CircleCenter",c))(hl||{});const wu=1e-5,oe=new p.Vector3,Ee=new p.Vector3,Di=new p.Vector3,cs=new p.Vector3,ti=new p.Matrix4,hs=new p.Line3;function vu(c,t){let e=Number.MAX_VALUE,i=0;for(let s=0;s<c.vertices.length;s++){const n=t.distanceTo(c.vertices[s]);n<e&&(i=s,e=n)}return{vertex:c.vertices[i],distance:e}}function Mu(c){if(!(c.object instanceof p.Mesh)||!c.face)return;const t=c.object,e=t.geometry.attributes.position;let i=t.geometry.index;if(e.count<3)return;const s=fe.getBatchByFaceIndex(t,c.faceIndex);t.geometry.boundsTree&&(i=new p.BufferAttribute(t.geometry.userData.originalIndex,1,!1)),ti.identity(),t instanceof p.InstancedMesh&&c.instanceId!==void 0&&t.getMatrixAt(c.instanceId,ti),ti.premultiply(t.matrixWorld);const n=t.geometry.drawRange;let r,a=e.array;if(i){let f=Math.max(0,n.start),m=Math.min(i.count,n.start+n.count);if(r=i.array,s){f=Math.max(f,s.indexStart),m=Math.min(m,s.indexStart+s.indexCount),r=i.array.slice(f,m),a=e.array.slice(s.positionStart*3,(s.positionStart+s.positionCount)*3);for(let b=0;b<r.length;b++)r[b]=r[b]-s.positionStart}else(f!==0||m!==i.count)&&(r=i.array.slice(f,m))}else{let f=Math.max(0,n.start),m=Math.min(e.count,n.start+n.count);s?(f=Math.max(f,s.positionStart),m=Math.min(m,s.positionStart+s.positionCount),a=e.array.slice(s.positionStart*3,(s.positionStart+s.positionCount)*3)):(f!==0||m!==e.count)&&(a=e.array.slice(f*3,m*3));const b=a.length/3;r=b>65535?new Uint32Array(b):new Uint16Array(b);for(let y=0,S=b;y<S;y++)r[y]=y}const o=_o.buildEdge(a,r,20);let l=Number.MAX_VALUE,h=0;for(let f=0;f<o.length;f+=2){const m=o[f],b=o[f+1];oe.set(a[m*3],a[m*3+1],a[m*3+2]),oe.applyMatrix4(ti),Ee.set(a[b*3],a[b*3+1],a[b*3+2]),Ee.applyMatrix4(ti),hs.set(oe,Ee),hs.closestPointToPoint(c.point,!0,Di);const y=c.point.distanceTo(Di);y<l&&(h=f,l=y,cs.copy(Di))}const d=o[h],u=o[h+1];return oe.set(a[d*3],a[d*3+1],a[d*3+2]),oe.applyMatrix4(ti),Ee.set(a[u*3],a[u*3+1],a[u*3+2]),Ee.applyMatrix4(ti),{vertices:[oe.clone(),Ee.clone()],vertex:cs.clone(),distance:l}}class Tu{constructor(t){g(this,"drawableList",new ws("snap"));g(this,"overlayRender");g(this,"markers",{});g(this,"activeOSnapType",0);g(this,"snapToleranceInWorldCoord",1);g(this,"intersectionLimit",10);g(this,"osnapTypePriorities",{1:0,2:1,64:2,32:3,16:4,4:5,8:6,0:100});g(this,"enabledOSnapTypes",127);this.overlayRender=t,this.overlayRender?.addDrawableList(this.drawableList),this.initOSnapMarkers()}initOSnapMarkers(){const t=new _e(Et.TripleCross),e=new _e(Et.Square),i=new _e(Et.Triangle),s=new _e(Et.CircleWithCross),n=new _e(Et.Cross),r=new _e(Et.Perpendicular);this.markers[1]=e,this.markers[2]=i,this.markers[4]=t,this.markers[32]=n,this.markers[64]=s,this.markers[16]=r,Object.values(this.markers).forEach(a=>{a.visible=!1,this.drawableList.addDrawable(a)})}isOSnapTypeEnabled(t){return!!(this.enabledOSnapTypes&t)}setOSnapTypeEnabled(t,e){if(e)this.enabledOSnapTypes|=t;else{const i=~t;this.enabledOSnapTypes&=i}}setSnapTolerance(t){this.snapToleranceInWorldCoord=t}getSnapTolerance(){return this.snapToleranceInWorldCoord}setIntersectionLimit(t){this.intersectionLimit=t}getIntersectionLimit(){return this.intersectionLimit}getMarkerLineColor(){return Li.colorStr2Rgba(_e.lineColor)}setMarkerLineColor(t){_e.lineColor=Li.rgba2Color(t)}getMarkerLineWidth(){return _e.lineWidth}setMarkerLineWidth(t){_e.lineWidth=t}getMarkerIconSize(){return _e.iconSize}setMarkerIconSize(t){_e.iconSize=t}getMarker(t){return this.markers[t]}setAllSnapLinesVisible(t){Object.values(this.markers).forEach(e=>{e.setSnapLineVisible(t)})}deactivate(){this.activeOSnapType&&(this.markers[this.activeOSnapType].visible=!1,this.overlayRender?.render()),this.activeOSnapType=0}destroy(){}handleSnap(t,e,i){if(!t||t.length<1){this.deactivate();return}P.debug("[OSnap] intersections before handleSnap:",t);const s=[];let n=!1,r;for(const o of t)o.object instanceof p.Mesh?(!r&&(r=o.point),!n&&o.object.name!=="groundPlane"&&(s.push(o),n=!0)):s.push(o);if(!e&&r){r.setZ(0);for(const l of s)l.point.z=0,l.distance=l.point.distanceTo(r);const o=l=>l instanceof p.Points?0:l instanceof p.LineSegments?2:l instanceof p.Line?1:3;s.sort((l,h)=>{const d=o(l.object),u=o(h.object);return d!==u?d-u:l.distance-h.distance})}return r||(P.warn("[OSnap] Potential to produce erroneous snap results"),r=s[0].point),P.debug("[OSnap] intersections:",s),P.debug("[OSnap] mousePosition:",r),this.getSnapPointAndUpdateMarker(r,s,e,i)?.clone()||r}getSnapPointAndUpdateMarker(t,e,i,s){if(!e.length){this.activateMarker(0);return}const n=this.getSnapInfo(t,e,i,s);if(!n||n.type===0){this.activateMarker(0);return}return this.activateMarker(n.type,n),n.point}activateMarker(t,e){this.activeOSnapType&&(this.markers[this.activeOSnapType].visible=!1),this.activeOSnapType=t;const i=this.markers[t];i&&e&&(i.update(e),i.visible=!0),this.overlayRender?.render()}getFootOfPerpendicular(t,e,i=wu){const{start:s,end:n}=e,r=s.x-n.x,a=s.y-n.y,o=s.z-n.z;if(s.distanceTo(n)<i)return s.clone();let l=(t.x-s.x)*(s.x-n.x)+(t.y-s.y)*(s.y-n.y)+(t.z-s.z)*(s.z-n.z);return l=l/(r*r+a*a+o*o),new p.Vector3(s.x+l*r,s.y+l*a,s.z+l*o)}getSnapInfo(t,e,i,s){const n=this.snapToleranceInWorldCoord*2;P.debug("[OSnap] snap radius:",n);const r=[],a={line:void 0};let o=this.osnapTypePriorities[0];for(let l=0;l<e.length&&l<this.intersectionLimit;++l){const h=e[l],d=h.object;let u;d instanceof p.Mesh?u=this.getOsnapInfoListFromMesh(t,h,n,o):d instanceof p.Line?u=this.getOsnapInfoListFromLine(t,h,i,n,a,o,s):d instanceof p.Points&&(u=this.getOsnapInfoListFromPoint(t,h,i,n,o)),u&&(o=this.osnapTypePriorities[u.type],r.push(u))}if(r.length!==0)return r.sort((l,h)=>{const d=this.osnapTypePriorities[l.type],u=this.osnapTypePriorities[h.type];return d!==u?d-u:l.distance-h.distance}),r[0]}getOsnapInfoListFromMesh(t,e,i,s){if(s<this.osnapTypePriorities[1])return;const n=Date.now(),r=Mu(e);if(!r){P.warn("[OSnap] Failed to get edge !");return}const a=Date.now();P.debug("[OSnap] getEdgeSnappingInfo took "+(a-n)/1e3+"s "),P.debug("[OSnap] edge:",r);const o=vu(r,t);if(P.debug("[OSnap] vertex:",o),o.distance<=i&&this.isOSnapTypeEnabled(1))return{distance:o.distance,type:1,point:o.vertex};if(r.distance<=i){if(this.isOSnapTypeEnabled(2)&&s<this.osnapTypePriorities[2])return;oe.copy(r.vertices[0]),oe.add(r.vertices[1]),oe.divideScalar(2);const l=oe.distanceTo(t);return l<=i&&this.isOSnapTypeEnabled(2)?{distance:l,type:2,point:oe.clone()}:!this.isOSnapTypeEnabled(4)||s<this.osnapTypePriorities[4]?void 0:{distance:r.distance,type:4,point:r.vertex,line:{start:r.vertices[0],end:r.vertices[1]}}}else P.debug("[OSnap] Face")}getOsnapInfoFromSegment(t,e,i,s,n,r,a){const o={start:e,end:i};if(a&&r>=this.osnapTypePriorities[16]&&this.isOSnapTypeEnabled(16)){const f=this.getFootOfPerpendicular(a,o,s),m=t.distanceTo(f);if(m<=s)return{distance:z.floorNumber(m,7),type:16,point:f.clone()}}if(r<this.osnapTypePriorities[1])return;hs.set(e,i),hs.closestPointToPoint(t,!0,Di);const l=t.distanceTo(Di);if(l>s)return;const h=t.distanceTo(e),d=t.distanceTo(i);if(Math.min(h,d)<=s&&this.isOSnapTypeEnabled(1)){let f=h,m=e;return d<h&&(f=d,m=i),{distance:z.floorNumber(f,7),type:1,point:m.clone()}}if(r<this.osnapTypePriorities[2])return;hs.getCenter(cs);const u=t.distanceTo(cs);if(u<s&&this.isOSnapTypeEnabled(2))return{point:cs.clone(),distance:z.floorNumber(u,7),type:2};if(!(r<this.osnapTypePriorities[4])){if(n.line&&this.isOSnapTypeEnabled(32)){const f=H.getLineSegmentsIntersectingPoint(n.line,o);if(!f)return;const m=t.distanceTo(f)/2;return m<s?(n.line=void 0,{point:f.clone(),distance:z.floorNumber(m,7),type:32}):void 0}if(this.isOSnapTypeEnabled(4))return n.line={start:e.clone(),end:i.clone()},{point:Di.clone(),distance:z.floorNumber(l,7),type:4,line:{start:e.clone(),end:i.clone()}}}}getOsnapInfoListFromLine(t,e,i,s,n,r,a){const o=[],l=e.object,h=l instanceof p.LineSegments?2:1,d=l.geometry.index,u=l.geometry.attributes.position,f=l.geometry.drawRange,m=fe.getBatchByLineIndex(l,e.index);if(d){let b=Math.max(0,f.start),y=Math.min(d.count,f.start+f.count);m&&(b=Math.max(b,m.indexStart),y=Math.min(y,m.indexStart+m.indexCount));for(let S=b,w=y;S<w-1;S+=h){const x=d.getX(S),E=d.getX(S+1);oe.fromBufferAttribute(u,x),Ee.fromBufferAttribute(u,E),oe.applyMatrix4(l.matrixWorld),Ee.applyMatrix4(l.matrixWorld),!i&&(oe.setZ(0),Ee.setZ(0));const M=this.getOsnapInfoFromSegment(t,oe,Ee,s,n,r,a);M&&(r=this.osnapTypePriorities[M.type],o.push(M))}}else{let b=Math.max(0,f.start),y=Math.min(u.count,f.start+f.count);m&&(b=Math.max(b,m.positionStart),y=Math.min(y,m.positionStart+m.positionCount));for(let S=b,w=y;S<w-1;S+=h){oe.fromBufferAttribute(u,S),Ee.fromBufferAttribute(u,S+1),oe.applyMatrix4(l.matrixWorld),Ee.applyMatrix4(l.matrixWorld),!i&&(oe.setZ(0),Ee.setZ(0));const x=this.getOsnapInfoFromSegment(t,oe,Ee,s,n,r,a);x&&(r=this.osnapTypePriorities[x.type],o.push(x))}}if(o.length!==0)return o.sort((b,y)=>{const S=this.osnapTypePriorities[b.type],w=this.osnapTypePriorities[y.type];return S!==w?S-w:b.distance-y.distance}),o[0]}getOsnapInfoListFromPoint(t,e,i,s,n){if(n<this.osnapTypePriorities[1])return;const r=e.object,a=r.geometry.getAttribute("position");oe.fromBufferAttribute(a,e.index),oe.applyMatrix4(r.matrixWorld),Ee.copy(t),!i&&(oe.setZ(0),Ee.setZ(0));const o=Ee.distanceTo(oe);if(o>s)return;const l={distance:o,point:oe.clone(),type:1};if(r.userData.type==="CircleCenter"){if(!this.isOSnapTypeEnabled(64))return;l.type=64}else if(P.debug("[OSnap] Other types of vertices !"),!this.isOSnapTypeEnabled(1))return;return l}getIntersectsIncludeOutline(t,e){const i=t.slice(),s=[];for(let r=0;r<t.length&&r<this.intersectionLimit;r++){const a=t[r].object;if(a.updateWorldMatrix(!0,!1),a instanceof p.Mesh&&!J.hasOutline(a,!1)){const o=J.createOutline(a.geometry);o.visible=!1,a.add(o),o.updateWorldMatrix(!0,!1),s.push(o)}}let n=[];return s.length>0&&(n=e.intersectObjects(s)||[],P.debug("[OSnap] Intersected with newly created edges: ",n),n.length>0&&i.push(...n)),i.sort((r,a)=>r.distance-a.distance),i}}class dl{constructor(t,e,i){g(this,"node");g(this,"parentNode");g(this,"target");g(this,"childNode");g(this,"follow",t=>{this.node.style.left=t.offsetX+15+"px",this.node.style.top=t.offsetY-30+"px"});g(this,"show",()=>this.node.hasAttribute("hidden")&&this.node.removeAttribute("hidden"));g(this,"hide",()=>!this.node.hasAttribute("hidden")&&this.node.setAttribute("hidden",""));g(this,"destroy",()=>{this.target?this.target.removeEventListener("mousemove",this.follow):document.removeEventListener("mousemove",this.follow),this.parentNode.removeChild(this.node)});this.node=document.createElement("div"),this.node.id=t,e&&this.node.append(e),this.childNode=document.createElement("div"),this.target=i?.target,this.parentNode=i?.parentNode||document.body,i?.followPointer&&(this.node.classList.add("follow-tooltip"),this.target?this.target.addEventListener("mousemove",this.follow):document.addEventListener("mousemove",this.follow)),this.parentNode.appendChild(this.node),!i?.showOnCreate&&this.node.setAttribute("hidden","")}setContent(t){this.node.textContent&&(this.node.textContent=null);for(let e=0;e<this.node.children.length;++e){const i=this.node.children[e];this.node.removeChild(i)}this.node.append(t),this.node.appendChild(this.childNode)}updateChildContent(t){this.childNode.textContent&&(this.childNode.textContent=null);for(let e=0;e<this.node.children.length;++e){const i=this.node.children[e];this.node.removeChild(i)}this.childNode.append(t)}}class Cu{constructor(t){g(this,"viewer");g(this,"active",!1);g(this,"tooltip");g(this,"resolve");g(this,"reject");g(this,"isResolvedOrRejected",!1);g(this,"mouseClicked",t=>{const e=t;if(e.markupData){const i=e.markupData.id,s=this.viewer.getOverlayRender().getDrawableById(i);if(s){let n=s.getBounds();n=n.clone().expandByScalar(20*this.viewer.getPixelSizeInWorldCoord());const r=Oe.world2NormalizedScreen(n.min,this.camera,this.viewerContainer),a=Oe.world2NormalizedScreen(n.max,this.camera,this.viewerContainer),o=new p.Box2(new p.Vector2(Math.min(r.x,a.x),Math.min(r.y,a.y)),new p.Vector2(Math.max(r.x,a.x),Math.max(r.y,a.y)));o.min.x=Math.max(o.min.x,0)*this.viewerContainer.clientWidth,o.min.y=Math.max(o.min.y,0)*this.viewerContainer.clientHeight,o.max.x=Math.min(o.max.x,1)*this.viewerContainer.clientWidth,o.max.y=Math.min(o.max.y,1)*this.viewerContainer.clientHeight,this.resolve&&(this.resolve(o),this.isResolvedOrRejected=!0),this.deactivate();const l=this.viewer;typeof l.clearSelection=="function"&&l.clearSelection()}}});g(this,"keydown",t=>{t.code==="Escape"&&this.deactivate()});this.viewer=t}get viewerContainer(){return this.viewer.viewerContainer}get camera(){return this.viewer.camera}isActive(){return this.active}activate(){if(this.isActive()){this.reject&&(this.deactivate(),this.reject("PickMarkupHelper is already actived!"),this.isResolvedOrRejected=!0);return}this.active=!0,this.viewer.addEventListener(le.MouseClick,this.mouseClicked),this.viewer.getInputManager()?.addEventListener("keydown",this.keydown),this.tooltip=new dl("pick-markup-tooltip",We.t("Tooltip.pickMarkup"),{followPointer:!0,showOnCreate:!0,parentNode:this.viewer.widgetContainer,target:this.viewerContainer});const t=document.getElementById("pick-markup-tooltip");t&&(t.style.pointerEvents="none");const e=We.t("Tooltip.pickMarkup");e&&this.tooltip&&this.tooltip?.setContent(e),this.viewer.dispatchEvent(le.PickMarkupActivate)}deactivate(){this.active=!1,this.viewer.removeEventListener(le.MouseClick,this.mouseClicked),this.viewer.getInputManager()?.removeEventListener("keydown",this.keydown),this.tooltip?.hide(),this.tooltip?.destroy(),this.tooltip=void 0,this.viewer.dispatchEvent(le.PickMarkupDeactivate),this.resolve&&!this.isResolvedOrRejected&&(this.resolve(void 0),this.isResolvedOrRejected=!0)}async pick(){return new Promise((t,e)=>{this.resolve=t,this.reject=e,this.activate()})}destroy(){this.deactivate(),!this.isResolvedOrRejected&&this.reject&&this.reject("PickMarkupHelper is not done for some reason!")}}const Bi=class Bi{constructor(t){g(this,"viewer");g(this,"input");g(this,"mouseDown",!1);g(this,"mouseMove",!1);g(this,"mouseDownPositionX",-1);g(this,"mouseDownPositionY",-1);g(this,"tempKey");g(this,"tempTouch");g(this,"tempEnableRotate",!1);g(this,"rectDom");g(this,"tooltip");g(this,"active",!1);g(this,"resolve");g(this,"reject");g(this,"isResolvedOrRejected",!1);g(this,"mousedown",t=>{if(t.button===0){this.mouseDown=!0;const e=new p.Vector2(t.x,t.y);this.mouseDownPositionX=e.x,this.mouseDownPositionY=e.y,this.tooltip?.hide(),this.tooltip?.destroy(),this.tooltip=void 0}});g(this,"mousemove",t=>{if(!this.mouseDown)return;const e=new p.Vector2(t.x,t.y);if(this.mouseDownPositionX>=0&&this.mouseDownPositionY>=0&&(Math.abs(e.x-this.mouseDownPositionX)>=5||Math.abs(e.y-this.mouseDownPositionY)>=5)){this.mouseMove=!0;const s=new p.Vector2(Math.min(this.mouseDownPositionX,e.x),Math.min(this.mouseDownPositionY,e.y)),n=new p.Vector2(Math.max(this.mouseDownPositionX,e.x),Math.max(this.mouseDownPositionY,e.y));this.drawRect(s,n)}});g(this,"mouseup",t=>{if(this.mouseDown&&this.mouseMove){const e=new p.Vector2(t.x,t.y),i=new p.Vector2(Math.min(this.mouseDownPositionX,e.x),Math.min(this.mouseDownPositionY,e.y)),s=new p.Vector2(Math.max(this.mouseDownPositionX,e.x),Math.max(this.mouseDownPositionY,e.y)),n=new p.Box2(i,s);this.resolve&&(this.resolve(n),this.isResolvedOrRejected=!0),this.deactivate(),this.setRectDomVisible(!1)}this.mouseDown=!1,this.mouseMove=!1,this.mouseDownPositionX=-1,this.mouseDownPositionY=-1});g(this,"keydown",t=>{t.code==="Escape"&&this.deactivate()});this.viewer=t,this.input=t.getInputManager()}get viewerContainer(){return this.viewer.viewerContainer}isActive(){return this.active}activate(){if(this.isActive()){this.reject&&(this.deactivate(),this.reject("BoxSelectHelper is already actived!"),this.isResolvedOrRejected=!0);return}this.active=!0,this.input.addEventListener("pointerdown",this.mousedown),this.input.addEventListener("pointermove",this.mousemove),this.input.addEventListener("pointerup",this.mouseup),this.input.addEventListener("keydown",this.keydown),this.viewer.getCameraManager().enableMouseLeft(!1),this.tooltip=new dl("box-select-tooltip",We.t("Tooltip.boxSelect"),{followPointer:!0,showOnCreate:!0,parentNode:this.viewer.widgetContainer,target:this.viewerContainer});const t=document.getElementById("box-select-tooltip");t&&(t.style.pointerEvents="none");const e=We.t("Tooltip.boxSelect");e&&this.tooltip&&this.tooltip?.setContent(e),this.viewer.dispatchEvent(le.BoxSelectActivate)}deactivate(){this.active=!1,this.input.removeEventListener("pointerdown",this.mousedown),this.input.removeEventListener("pointermove",this.mousemove),this.input.removeEventListener("pointerup",this.mouseup),this.input.removeEventListener("keydown",this.keydown),this.tooltip?.hide(),this.tooltip?.destroy(),this.tooltip=void 0,this.viewer.getCameraManager().enableMouseLeft(!0),this.viewer.dispatchEvent(le.BoxSelectDeactivate),this.resolve&&!this.isResolvedOrRejected&&(this.resolve(void 0),this.isResolvedOrRejected=!0)}drawRect(t,e){!this.rectDom&&(this.rectDom=document.createElement("div"),this.rectDom.style.cssText=`position: absolute;border: ${Bi.BORDER_WIDTH} solid ${Bi.BORDER_COLOR};`,this.viewerContainer.appendChild(this.rectDom)),this.setRectDomVisible(!0),this.rectDom.style.left=t.x+"px",this.rectDom.style.top=t.y+"px";const i=Math.abs(e.x-t.x),s=Math.abs(e.y-t.y);this.rectDom.style.width=i+"px",this.rectDom.style.height=s+"px"}setRectDomVisible(t){this.rectDom&&(this.rectDom.style.display=t?"inline-block":"none")}async select(){return new Promise((t,e)=>{this.resolve=t,this.reject=e,this.activate()})}destroy(){this.deactivate(),this.rectDom?.remove(),this.rectDom=void 0,!this.isResolvedOrRejected&&this.reject&&this.reject("BoxSelectHelper is not done for some reason!")}};g(Bi,"BORDER_COLOR","#fff000"),g(Bi,"BORDER_WIDTH","2px");let xn=Bi;class ul{constructor(t){g(this,"viewer");g(this,"boxSelectHelper");g(this,"active",!1);this.viewer=t,this.boxSelectHelper=new xn(t)}get viewerContainer(){return this.viewer.viewerContainer}get camera(){return this.viewer.camera}get raycaster(){return this.viewer.getRaycaster()}isActive(){return this.active}activate(){this.active=!0,this.boxSelectHelper?.select().then(t=>{t&&this.handleZoomToRect(t.min,t.max)})}deactivate(){this.active=!1,this.boxSelectHelper?.deactivate()}pickPositionByScreenPoint(t){return this.viewer.pickObject(t)?.point}handleZoomToRect(t,e){const i=this.pickPositionByScreenPoint(t),s=this.pickPositionByScreenPoint(e);if(i&&s){const n=new p.Vector3(Math.min(i.x,s.x),Math.min(i.y,s.y),Math.min(i.z,s.z)),r=new p.Vector3(Math.max(i.x,s.x),Math.max(i.y,s.y),Math.max(i.z,s.z)),a=new p.Box3(n,r);this.viewer.zoomToBBox(a)}}destroy(){this.boxSelectHelper?.destroy(),this.boxSelectHelper=void 0}}function lo(c){return c?c.replace(/%%[dD]/g,"°").replace(/%%[cC]/g,"⌀").replace(/%%[pP]/g,"±").replace(/%%(U|O)/gi,"").replace(/\\P/g," ").replace(/\\[A-Za-z][^;\\]*;/g,"").replace(/[{}]/g,"").replace(/\\\\/g,"\\").replace(/\\[uU]\+([0-9a-fA-F]{4})/g,(t,e)=>String.fromCodePoint(parseInt(e,16))).trim():""}const tn=new p.Box3,Su=new p.Vector3;function Eu(c,t){return c.trim().toLowerCase()===t?2e6:0}function Ou(c,t){const e=c.toLowerCase(),i=e.indexOf(t);if(i>=0)return(e===t?2e6:1e6)+(1e3-i)-Math.min(e.length,500);let s=0,n=-1,r=-1,a=0;for(let l=0;l<t.length;l++){const h=t[l];let d=-1;for(;s<e.length;s++)if(e[s]===h){d=s;break}if(d<0)return 0;n<0?n=d:r>=0&&d-r>1&&(a+=d-r-1),r=d,s=d+1}const o=5e5-a*50-n*5-Math.min(e.length,500);return o>0?o:1}class Mr{constructor(t){g(this,"viewer");g(this,"overlayRender");g(this,"drawableList");g(this,"indexedModelObject");g(this,"index",[]);this.viewer=t,this.overlayRender=this.viewer.getOverlayRender()}getMasterModel(){return this.viewer.loadedModels.find(t=>this.viewer.masterModelId===t.modelId)}invalidateIndex(){this.index=[],this.indexedModelObject=void 0}buildIndex(){const t=this.getMasterModel();if(!t){this.index=[],this.indexedModelObject=void 0;return}const e=t.getModelObject();if(e===this.indexedModelObject&&this.index.length>0)return;this.indexedModelObject=e,this.index=[];const i=new p.Matrix4,s=new p.Vector3,n=new Map;e.updateWorldMatrix(!0,!0);const r=(a,o,l,h,d)=>{if(a&&n.has(a)){n.get(a).box.union(d);return}n.set(a||o+h,{text:o,layer:l,layoutName:h,box:d.clone()})};e.traverse(a=>{const o=a.userData;if(o){if(typeof o.textContent=="string"&&o.textContent.length){const l=lo(o.textContent);if(!l||(tn.makeEmpty(),tn.setFromObject(a),tn.isEmpty()))return;r(o.handle||"",l,o.layer||"0",this.findLayoutName(a),tn);return}if(Array.isArray(o.batches)){const l=a.geometry?.getAttribute?.("position");if(!l)return;i.copy(a.matrixWorld);for(const h of o.batches){const d=h?.userData?.textContent;if(typeof d!="string"||!d.length)continue;const u=lo(d);if(!u)continue;const f=new p.Box3,m=h.positionStart||0,b=h.positionCount||0;for(let y=m;y<m+b;y++)s.fromBufferAttribute(l,y).applyMatrix4(i),f.expandByPoint(s);f.isEmpty()||r(h.userData.handle||"",u,h.userData.layer||"0",this.findLayoutName(a),f)}}}}),n.forEach((a,o)=>{this.index.push({handle:o,layer:a.layer,layoutName:a.layoutName,text:a.text,box:a.box})})}findLayoutName(t){let e=t;for(;e;){if(e.userData?.isLayoutLevelObject===!0)return e.name||"Model";e=e.parent}return"Model"}search(t,e){const i=(t||"").trim().toLowerCase();if(!i)return[];this.buildIndex();const s=e?.mode??"fuzzy",n=e?.layer?.trim().toLowerCase(),r=e?.maxResults??200,a=[];for(const o of this.index){if(n&&o.layer.toLowerCase()!==n)continue;const l=s==="exact"?Eu(o.text,i):Ou(o.text,i);l>0&&a.push({item:o,score:l})}return a.sort((o,l)=>l.score-o.score),a.slice(0,r).map(o=>o.item)}focus(t){if(!t)return;this.viewer.activateLayout(t.layoutName),this.highlight(t);const e=t.box.clone();this.viewer.zoomToBBox(e.expandByScalar(Math.max(e.getSize(Su).length()*.5,1)))}highlight(t){this.overlayRender&&(!this.drawableList&&(this.drawableList=new ws("text-search"),this.overlayRender.addDrawableList(this.drawableList)),this.clearHighlight(),this.drawableList.addDrawable(new wt(j.guid(),[t.box.clone()],[1,.55,0,1],[1,.55,0,.15])),this.viewer.enableRender())}clearHighlight(){this.drawableList?.clear(),this.viewer.enableRender()}invalidate(){this.indexedModelObject=void 0,this.index=[]}destroy(){this.clearHighlight(),this.overlayRender=void 0,this.drawableList=void 0,this.index=[],this.indexedModelObject=void 0}}class _u extends Nt{constructor(e){super("MobileHelper");g(this,"position");g(this,"needsFrustumCulled");g(this,"renderOrder");this.needsFrustumCulled=!1,this.renderOrder=1e3,this.position=e}setPosition(e){this.position=e}isPointInPath(e,i){return!1}draw(e,i){this.drawInnerCircle(e),this.drawOuterRing(e),this.drawSnapTriangle(e)}drawInnerCircle(e){const{x:i,y:s}=this.position;e.save(),e.fillStyle="rgba(137, 137, 138, 0.8)",e.beginPath(),e.arc(i,s,25,0,Math.PI*2),e.closePath(),e.fill(),e.restore()}drawOuterRing(e){const{x:i,y:s}=this.position;e.save(),e.strokeStyle="rgba(17, 17, 19, 0.8)",e.lineWidth=10,e.beginPath(),e.arc(i,s,30,0,Math.PI*2),e.closePath(),e.stroke(),e.restore(),e.save(),e.strokeStyle="rgba(173, 173, 174, 0.8)",e.lineWidth=3,e.beginPath(),e.arc(i,s,35,0,Math.PI*2),e.closePath(),e.stroke(),e.restore()}drawSnapTriangle(e){const{x:i,y:s}=this.position;e.save(),e.fillStyle="rgba(17, 17, 19, 0.8)",e.strokeStyle="rgba(137, 137, 138, 0.8)",e.lineWidth=2,e.beginPath(),e.moveTo(i-35,s-35),e.lineTo(i-35+12,s-35),e.lineTo(i-35,s-35+12),e.closePath(),e.fill(),e.stroke(),e.restore()}translate(e,i){this.position.add(new p.Vector2(e,i))}getTouchPoint(){return{x:this.position.x-35,y:this.position.y-35}}isIntersect(e){return this.position.x-35<e.x&&this.position.y-35<e.y&&this.position.x+35>e.x&&this.position.y+35>e.y}drawSelect(e,i){}getClassType(){return"MobileTouchHelperDrawable"}}var Je=(c=>(c[c.Left=0]="Left",c[c.Middle=1]="Middle",c[c.Right=2]="Right",c[c.Back=3]="Back",c[c.Forward=4]="Forward",c))(Je||{});class fl extends Ht{constructor(e){super();g(this,"element");g(this,"enabled");g(this,"keyboardEnabled");g(this,"mouseDownPositionX");g(this,"mouseDownPositionY");g(this,"lastLeftPointerUpTime");g(this,"pointers");g(this,"handleClick");g(this,"handlePointerDown");g(this,"handlePointerMove");g(this,"handlePointerUp");g(this,"handlePointerCancel");g(this,"handleMouseWheel");g(this,"handleContextMenu");g(this,"handlePointerEnter");g(this,"handlePointerLeave");g(this,"handleResize");g(this,"handleKeydown");g(this,"handleKeyup");g(this,"style");this.enabled=!0,this.keyboardEnabled=!0,this.mouseDownPositionX=0,this.mouseDownPositionY=0,this.lastLeftPointerUpTime=0,this.pointers=[],this.handleClick=i=>{if(!this.enabled)return;const s=this.getBaseEvent(i);this.dispatchEvent("click",s)},this.handlePointerDown=i=>{if(!this.enabled)return;this.stop(i);const s=this.getBaseEvent(i);this.isDoubleClick(s)?(this.lastLeftPointerUpTime=0,this.mouseDownPositionX=-1,this.mouseDownPositionY=-1,this.dispatchEvent("dblclick",s)):(this.mouseDownPositionX=s.x,this.mouseDownPositionY=s.y),this.dispatchEvent("pointerdown",s),i.pointerType==="touch"?(this.pointers.push(s),s.pointers=this.pointers,this.dispatchEvent("touchstart",s)):this.dispatchEvent("mousedown",s)},this.handlePointerMove=i=>{if(!this.enabled)return;this.stop(i);const s=this.getBaseEvent(i);this.isCloseToLastPosition(s)||(this.dispatchEvent("pointermove",s),i.pointerType==="touch"?(this.updatePointers(s),s.pointers=this.pointers,this.dispatchEvent("touchmove",s)):this.dispatchEvent("mousemove",s))},this.handlePointerUp=i=>{if(!this.enabled)return;this.stop(i);const s=this.getBaseEvent(i);s.button===0&&(this.lastLeftPointerUpTime=s.timestamp),this.dispatchEvent("pointerup",s),i.pointerType==="touch"?(this.removePointers(s),s.pointers=this.pointers,this.dispatchEvent("touchend",s)):this.dispatchEvent("mouseup",s)},this.handlePointerCancel=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("pointercancel",this.getBaseEvent(i)))},this.handleMouseWheel=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("wheel",this.getBaseEvent(i)))},this.handleContextMenu=i=>{if(this.enabled)return this.stop(i),this.dispatchEvent("contextmenu",this.getBaseEvent(i)),!1},this.handlePointerEnter=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("pointerenter",this.getBaseEvent(i)))},this.handlePointerLeave=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("pointerleave",this.getBaseEvent(i)))},this.handleResize=i=>{this.enabled&&(this.stop(i),this.dispatchEvent("resize",this.getBaseEvent(i)))},this.handleKeydown=i=>{!this.enabled||!this.keyboardEnabled||this.dispatchEvent("keydown",this.getBaseEvent(i))},this.handleKeyup=i=>{!this.enabled||!this.keyboardEnabled||this.dispatchEvent("keyup",this.getBaseEvent(i))},this.style={},this.element=e,this.bindEvents()}getEnabled(){return this.enabled}setEnabled(e){this.enabled=e}getkKeyboardEnabled(){return this.keyboardEnabled}setkKeyboardEnabled(e){this.keyboardEnabled=e}setCursor(e){this.element.style&&(this.element.style.cursor=e||"default")}bindEvents(){this.element.style.touchAction="none",this.element.style.userSelect="none",this.element.style.webkitUserSelect="none",this.element.addEventListener("click",this.handleClick),this.element.addEventListener("pointerdown",this.handlePointerDown),this.element.addEventListener("pointermove",this.handlePointerMove),this.element.addEventListener("pointerup",this.handlePointerUp),this.element.addEventListener("pointercancel",this.handlePointerCancel),this.element.addEventListener("pointerenter",this.handlePointerEnter),this.element.addEventListener("pointerleave",this.handlePointerLeave),this.element.addEventListener("contextmenu",this.handleContextMenu),this.element.addEventListener("wheel",this.handleMouseWheel,{passive:!1}),window.addEventListener("resize",this.handleResize),window.addEventListener("keydown",this.handleKeydown),window.addEventListener("keyup",this.handleKeyup)}unBindEvents(){this.element.removeEventListener("pointerdown",this.handlePointerDown),this.element.removeEventListener("pointermove",this.handlePointerMove),this.element.removeEventListener("pointerup",this.handlePointerUp),this.element.removeEventListener("pointerenter",this.handlePointerEnter),this.element.removeEventListener("pointerleave",this.handlePointerLeave),this.element.removeEventListener("contextmenu",this.handleContextMenu),this.element.removeEventListener("wheel",this.handleMouseWheel),window.removeEventListener("resize",this.handleResize),window.removeEventListener("keydown",this.handleKeydown),window.removeEventListener("keyup",this.handleKeyup),this.element.style.touchAction="",this.element.style.userSelect="",this.element.style.webkitUserSelect=""}getBaseEvent(e){const i=e,s={x:0,y:0,pageX:0,pageY:0,clientX:0,clientY:0,deltaX:0,deltaY:0,movementX:0,movementY:0,deltaMode:0,pointerId:0,timestamp:0,buttons:0,pointerType:"mouse",altKey:!1,ctrlKey:!1,shiftKey:!1,metaKey:!1,originalEvent:i};if(s.timestamp=i.timeStamp,sn(i,"clientX"))if(s.altKey=i.altKey,s.ctrlKey=i.ctrlKey,s.shiftKey=i.shiftKey,s.clientX=i.clientX,s.clientY=i.clientY,s.button=i.button,sn(i,"pointerId")){s.pointerType=i.pointerType,s.buttons=i.buttons,s.pageX=i.pageX,s.pageY=i.pageY,s.pointerId=i.pointerId;const n=Oe.getScreenCoordinateByEvent(i,this.element);s.x=n.x,s.y=n.y,s.movementX=i.movementX,s.movementY=i.movementY}else sn(i,"deltaX")&&(s.deltaMode=i.deltaMode,s.deltaX=i.deltaX,s.deltaY=i.deltaY);else sn(i,"code")&&(s.altKey=i.altKey,s.ctrlKey=i.ctrlKey,s.shiftKey=i.shiftKey,s.metaKey=i.metaKey,s.code=i.code);return s}stop(e){e.preventDefault()}updatePointers(e){for(let i=0;i<this.pointers.length;i++)if(e.pointerId==this.pointers[i].pointerId){this.pointers[i]=e;break}}removePointers(e){for(let i=0;i<this.pointers.length;i++)if(this.pointers[i].pointerId==e.pointerId){this.pointers.splice(i,1);break}}getBoundingClientRect(){return this.element.getBoundingClientRect()}isCloseToLastPosition(e){return this.mouseDownPositionX===-1||this.mouseDownPositionY===-1?!1:Math.abs(e.x-this.mouseDownPositionX)<5&&Math.abs(e.y-this.mouseDownPositionY)<5}isDoubleClick(e){const s=e.timestamp-this.lastLeftPointerUpTime;return!!(e.button===0&&s<300&&this.isCloseToLastPosition(e))}}function sn(c,t){return c[t]!==void 0}class Pu{constructor(t){g(this,"CLEAR_COLOR");g(this,"CLEAR_COLOR_ALPHA");g(this,"EMPTY_MODEL_ID");g(this,"viewer");g(this,"raycaster");g(this,"pickingTexture");this.CLEAR_COLOR=new p.Color().setRGB(1,1,1),this.CLEAR_COLOR_ALPHA=1,this.EMPTY_MODEL_ID=255,this.viewer=t,this.raycaster=new p.Raycaster,this.pickingTexture=new p.WebGLRenderTarget(1,1)}get scene(){return this.viewer.scene}get camera(){return this.viewer.camera}get renderer(){return this.viewer.renderer}get overlayRender(){return this.viewer.getOverlayRender()}get viewerContainer(){return this.viewer.viewerContainer}getRaycaster(){return this.raycaster}pickObjectsByNdc(t,e,i){return!e||e.length===0?[]:(this.raycaster.setFromCamera(t,this.camera),this.setLayerChannels(i),this.raycaster.intersectObjects(e,!0)||[])}pickObject(t,e,i,s){const n=this.pickObjects(t,e,i,s);if(n.length!==0)return n[0]}pickObjects(t,e,i,s=0){const n=Oe.screen2Ndc(t,this.camera,this.viewerContainer);if(s>0){const r=[],a=new Map,o=Oe.screen2Ndc(t,this.camera,this.viewerContainer),l=Oe.screen2Ndc({x:t.x+s,y:t.y},this.camera,this.viewerContainer),h=new p.Vector3(o.x,o.y,0).unproject(this.camera),d=new p.Vector3(l.x,l.y,0).unproject(this.camera),u=h.distanceTo(d),f=this.raycaster.params.Line.threshold;this.raycaster.params.Line.threshold=u,this.setLayerChannels(i);const m=8;for(let y=0;y<m;y++){const S=y/m*Math.PI*2,w=Math.cos(S)*s,x=Math.sin(S)*s,E={x:t.x+w,y:t.y+x},M=Oe.screen2Ndc(E,this.camera,this.viewerContainer);this.raycaster.setFromCamera(M,this.camera),this.raycaster.layers.enableAll();const O=this.raycaster.intersectObjects(e,!0)||[];for(const T of O)T.object&&!a.has(T.object.uuid)&&(a.set(T.object.uuid,T),r.push(T))}this.raycaster.setFromCamera(o,this.camera);const b=this.raycaster.intersectObjects(e,!0)||[];for(const y of b)y.object&&!a.has(y.object.uuid)&&(a.set(y.object.uuid,y),r.push(y));if(this.raycaster.params.Line.threshold=f,r.length>1){const y=this.raycaster.ray.origin.clone();r.sort((S,w)=>{const x=S.point||S.object.getWorldPosition(new p.Vector3),E=w.point||w.object.getWorldPosition(new p.Vector3);return x.distanceTo(y)-E.distanceTo(y)})}return r}return this.pickObjectsByNdc(n,e,i)}pickDrawable(t){return this.overlayRender.getDrawablesByPosition(t)}pick(t,e){const i=this.pickBuffer(t,e),s=[i[0],i[1],i[2],i[3]],n=Z1(s),r=K1(s);if(n!==this.EMPTY_MODEL_ID)return P.info("[PickMgr] Picked: tilesetId("+n+"), userId("+r+")"),{tilesetId:n,userId:r}}setLayerChannels(t){t&&t.length>0?(this.raycaster.layers.disableAll(),t.forEach(e=>{this.raycaster.layers.enable(e)})):this.raycaster.layers.enableAll()}pickBuffer(t,e,i=1,s=1){const{pickingTexture:n,renderer:r,camera:a}=this;n.setSize(i,s);const o=r.getPixelRatio(),l=r.getContext().drawingBufferWidth,h=r.getContext().drawingBufferHeight,d=t.x*o|0,u=t.y*o|0;a.setViewOffset(l,h,d,u,i,s),r.setRenderTarget(n);const f=new p.Color;r.getClearColor(f);const m=r.getClearAlpha();r.setClearColor(this.CLEAR_COLOR,this.CLEAR_COLOR_ALPHA),r.render(e,a);const b=new Uint8Array(4*i*s);return r.readRenderTargetPixels(n,0,0,i,s,b),r.setRenderTarget(null),a.clearViewOffset(),r.setClearColor(f,m),b}}const co=new p.Vector3;class Au{constructor(t){g(this,"viewer");g(this,"scene");g(this,"renderer");g(this,"pmremGenerator");g(this,"lights");g(this,"modelGroup");this.viewer=t;const e=new p.Scene;e.matrixAutoUpdate=et,e.matrixWorldAutoUpdate=et,this.scene=e,this.modelGroup=new p.Group,this.modelGroup.name="models",this.scene.add(this.modelGroup);const{width:i,height:s,viewerContainer:n}=t.container;let r;try{r=new p.WebGLRenderer({antialias:!0,preserveDrawingBuffer:!0})}catch{try{r=new p.WebGLRenderer,P.warn("WebGL context created with fallback settings (antialias disabled).")}catch(o){throw this.showWebGLUnavailable(n),new Error("WebGLUnavailable: failed to create WebGL context. "+o.message)}}r.setPixelRatio(window.devicePixelRatio),r.setSize(i,s),r.outputColorSpace=p.SRGBColorSpace,r.toneMappingExposure=1,r.localClippingEnabled=!0,r.shadowMap.enabled=!1,r.shadowMap.type=p.PCFSoftShadowMap,r.shadowMap.autoUpdate=!1,r.domElement.style.outlineWidth="0",n?.appendChild(r.domElement),this.renderer=r,j.printGpuInfo(r.getContext())}showWebGLUnavailable(t){if(!t)return;const e=document.createElement("div");e.style.cssText=["position:absolute","left:0","top:0","width:100%","height:100%","display:flex","align-items:center","justify-content:center","text-align:center","padding:0 24px","box-sizing:border-box","background:rgba(255,255,255,0.95)","color:#333","font-size:14px","line-height:1.8","z-index:9999"].join(";"),e.textContent=We.t("WebGL.NotAvailable"),t.appendChild(e)}initLights(){const t=new p.Group;t.name="lights";const e=1.5,i=16777215,s=new p.DirectionalLight(i,e);s.name="sun",s.castShadow=!0,s.position.set(-2,2,4),s.shadow.autoUpdate=!1,s.shadow.mapSize.width=1024,s.shadow.mapSize.height=1024;const n=new p.AmbientLight(i);n.name="ambient";const r=new p.HemisphereLight(i,14540253,.2);r.name="hemisphere",r.position.set(0,300,0);const a=new p.Group;a.name="lightHelpers",a.visible=!1;const o=new p.DirectionalLightHelper(s),l=new p.CameraHelper(s.shadow.camera);return a.add(o),a.add(l),t.add(s),t.add(s.target),t.add(n),t.add(r),t.add(a),this.scene.add(t),this.lights=t,t}initPMREMGenerator(){this.pmremGenerator=new p.PMREMGenerator(this.renderer),this.pmremGenerator.compileEquirectangularShader()}get maxFragmentUniforms(){return this.renderer.capabilities.maxFragmentUniforms-20}addModel(t){this.modelGroup.add(t.getModelObject())}removeModel(t){this.modelGroup.remove(t.getModelObject())}enableShadow(t){this.renderer.shadowMap.enabled=t,this.directionalLight.castShadow=t,t&&(this.tryAdjustDirectionalLight(),this.updateDirectionalLightShadow()),this.modelGroup.traverse(e=>{e.isMesh&&(e.castShadow=t,e.receiveShadow=t)})}enableClipping(t){this.renderer.localClippingEnabled=t}setClipPlanes(t){this.renderer.clippingPlanes=t}enableLights(t){let e=this.lights;e||(e=this.initLights()),e.visible=t}debugLights(t){!this.lights||!this.lightHelpers||(this.lightHelpers.visible=t)}setBackground(t){this.scene.background=t}get directionalLight(){return this.lights?.getObjectByName("sun")}get ambientLight(){return this.lights?.getObjectByName("ambient")}get hemisphereLight(){return this.lights?.getObjectByName("hemisphere")}get lightHelpers(){return this.lights?.getObjectByName("lightHelpers")}get directionalLightHelper(){let t;for(let e=0;this.lightHelpers&&e<this.lightHelpers?.children.length;++e){const i=this.lightHelpers.children[e];if(i instanceof p.DirectionalLightHelper){t=i;break}}return t}get cameraHelper(){let t;for(let e=0;this.lightHelpers&&e<this.lightHelpers?.children.length;++e){const i=this.lightHelpers.children[e];i instanceof p.CameraHelper&&(t=i)}return t}async setEnvironmentFromData(t){this.pmremGenerator||this.initPMREMGenerator();const e=await ms.createEnvTextureFromDataArray(this.pmremGenerator,t);this.scene.environment=e}async setEnvironment(t){this.pmremGenerator||this.initPMREMGenerator();const e=await ms.createEnvTexture(this.pmremGenerator,t);this.scene.environment?.dispose(),this.scene.environment=e}resize(){const{width:t,height:e}=this.viewer.container;this.renderer.setSize(t,e)}getRaycastableObjects(){const t=[];return this.modelGroup.traverse(e=>{t.push(e)}),t}tryAdjustDirectionalLight(){const t=this.directionalLight;if(!t)return;const e=this.viewer.getBBox(),i=new p.Sphere;e.getBoundingSphere(i);const s=i.center,n=i.radius,r=t.shadow.camera;r.zoom=1,r.top=n,r.bottom=-n,r.right=n,r.left=-n,r.near=.1,r.far=2*n,r.updateProjectionMatrix();const a=new p.Vector3(-1,-.5,1);a.normalize().multiplyScalar(n),t.position.copy(s).addScaledVector(a,-1),t.target.position.copy(s),P.debug("[Scene] directionalLight.position",t.position),P.debug("[Scene] directionalLight.target.position",t.target.position),this.updateDirectionalLight(),this.viewer.enableRender()}updateDirectionalLight(){const t=this.directionalLight;if(t&&(t.updateMatrixWorld(),t.target.updateMatrixWorld(),this.directionalLightHelper&&(this.directionalLightHelper.update(),this.scene?.matrixAutoUpdate||this.directionalLightHelper.updateWorldMatrix(!1,!0)),t.shadow.needsUpdate=!0,t.shadow.camera.updateProjectionMatrix(),this.cameraHelper&&(this.cameraHelper.update(),!this.scene?.matrixAutoUpdate))){const e=t.shadow.camera;e.position.setFromMatrixPosition(t.matrixWorld),co.setFromMatrixPosition(t.target.matrixWorld),e.lookAt(co),e.updateMatrixWorld(),this.cameraHelper.updateWorldMatrix(!1,!0)}}updateDirectionalLightShadow(){this.directionalLight&&(this.directionalLight.shadow.needsUpdate=!0)}showDirectionalLightHelper(t){this.directionalLightHelper&&(this.directionalLightHelper.visible=t),this.cameraHelper&&(this.cameraHelper.visible=t)}destroy(){this.lightHelpers?.clear(),this.lightHelpers?.removeFromParent(),this.lightHelpers?.traverse(t=>{t.dispose?.call(t)}),this.lights?.clear(),this.lights?.removeFromParent(),this.lights?.traverse(t=>{t.dispose?.call(t)}),this.lights=void 0,this.pmremGenerator?.dispose(),this.renderer.domElement.remove(),this.renderer.clear(),this.renderer.dispose(),this.renderer.forceContextLoss(),this.scene.clear()}}class Iu{constructor(t){g(this,"history");g(this,"step");g(this,"maxCount");g(this,"isBatchCommand");g(this,"batchCommands");this.history=[],this.step=0,this.maxCount=50,this.isBatchCommand=!1,this.batchCommands=[],this.maxCount=t||this.maxCount}addCommand(t){this.isBatchCommand?this.batchCommands.push(t):(this.history.length===this.maxCount&&this.history.shift(),this.step!==this.history.length&&this.history.splice(this.step),this.history.push(t),this.step++)}startTransaction(){this.isBatchCommand=!0}endTransaction(){this.history.length===this.maxCount&&this.history.shift(),this.step!==this.history.length&&this.history.splice(this.step),this.batchCommands.length>0&&(this.history.push(this.batchCommands.slice()),this.step++),this.isBatchCommand=!1,this.batchCommands=[]}undo(){if(this.canUndo())return!1;this.step--;const t=this.history[this.step];return t&&(Array.isArray(t)?t.forEach(e=>e.undo()):t.undo()),!0}redo(){if(this.canRedo())return!1;this.step++;const t=this.history[this.step-1];return t&&(Array.isArray(t)?t.forEach(e=>e.redo()):t.redo()),!0}getCommands(){return this.history}canUndo(){return this.step<=0}canRedo(){return this.step>=this.history.length}clear(){this.history=[],this.step=0}destroy(){this.clear(),this.maxCount=0}}class Mn extends Ht{constructor(e){super();g(this,"name");g(this,"viewerCfg");g(this,"clock");g(this,"targetMaxFps");g(this,"timeStamp");g(this,"renderEnabled");g(this,"requestAnimationFrameHandle");g(this,"container");g(this,"plugins");g(this,"loadedModels");g(this,"raf");g(this,"timeoutSymbol");g(this,"homeView");g(this,"inputManager");g(this,"cameraManager");g(this,"sceneManager");g(this,"fontManager");g(this,"pickManager");g(this,"undoManager");g(this,"overlayRender");g(this,"css2dRenderer");g(this,"spinner");g(this,"progressBar");g(this,"loaderHelper");g(this,"zoomToRectHelper");g(this,"_enableSelection");g(this,"enableRender");this.name=$e.BaseViewer,this.clock=new p.Clock,this.targetMaxFps=60,this.timeStamp=0,this.renderEnabled=!0,this.plugins=[],this.loadedModels=[],this.raf=new ol,this._enableSelection=!0,this.enableRender=(i=1e3)=>{this.renderEnabled=!0,this.raf&&(this.timeoutSymbol&&this.raf.clearTimeout(this.timeoutSymbol),this.timeoutSymbol=this.raf.setTimeout(()=>{this.renderEnabled=!1},i))},this.viewerCfg=e,this.initLogLevel(),this.initLocalization(),this.container=new Rr(e.containerId),e.enableProgressBar&&(this.progressBar=new Fr(this.container)),this.spinner=new tl(this.container),this.sceneManager=new Au(this),this.pickManager=new Pu(this),this.overlayRender=new bs(this),this.css2dRenderer=this.initCSS2DRenderer(),this.inputManager=new fl(this.viewerContainer),this.cameraManager=new ou(this),this.loaderHelper=new Vt,this.undoManager=new Iu,this.resize(),this.clock.start(),this.animate()}initLogLevel(){const e=this.viewerCfg.logLevel;e&&To(e)}initLocalization(){const e=this.viewerCfg.language||So;We.changeLanguage(e)}get viewerContainer(){return this.container.viewerContainer}get widgetContainer(){return this.container.widgetContainer}getUndoManager(){return this.undoManager}getInputManager(){return this.inputManager}getCssRender(){return this.css2dRenderer}getCameraManager(){return this.cameraManager}getOverlayRender(){return this.overlayRender}getSceneManager(){return this.sceneManager}get renderer(){return this.sceneManager.renderer}get camera(){return this.cameraManager.camera}get scene(){return this.sceneManager.scene}getRaycaster(){return this.pickManager.getRaycaster()}getViewerConfig(){return this.viewerCfg}getSpinner(){return this.spinner}getFontManager(){return this.fontManager}initCSS2DRenderer(){const e=new yo.CSS2DRenderer,{width:i,height:s}=this.viewerContainer.getBoundingClientRect();return e.setSize(i,s),e.domElement.style.height="0",e.domElement.style.width="0",e.domElement.style.position="absolute",e.domElement.style.top="0",e.domElement.style.left="0",e.domElement.style.overflow="visible",e.domElement.classList.add("css2d-renderer"),this.viewerContainer?.appendChild(e.domElement),e}animate(){const e=Date.now()-this.timeStamp,i=1/this.targetMaxFps;if(e<i){this.requestAnimationFrameHandle=requestAnimationFrame(this.animate.bind(this));return}const s=this.cameraManager.update(this.clock.getDelta());this.container.needResize&&(this.resize(),this.renderEnabled=!0),(this.renderEnabled||s)&&(this.dispatchEvent(le.BeforeRender),this.renderer.render(this.scene,this.camera),this.css2dRenderer.render(this.scene,this.camera),this.dispatchEvent(le.AfterRender),this.renderEnabled=!1),this.requestAnimationFrameHandle=requestAnimationFrame(this.animate.bind(this)),this.timeStamp=Date.now(),this.dispatchEvent(le.OnAnimate)}resize(){this.sceneManager.resize(),this.cameraManager.updateAspect();const{clientWidth:e,clientHeight:i}=this.viewerContainer;this.css2dRenderer.setSize(e,i),this.overlayRender.setSize(e,i)}setDracoDecoderPath(e){Vt.setDracoDecoderPath(e)}addModel(e){const i=e.getModelObject();i.name=e.modelId,this.sceneManager.addModel(e),i.matrixAutoUpdate=et,i.updateMatrix(),i.updateMatrixWorld(!0),this.loadedModels.push(e),this.enableRender(0)}async setFont(e){!this.fontManager&&(this.fontManager=new xt),await this.fontManager.loadFonts(e)}is3d(){return!1}getPixelSizeInWorldCoord(){const e=this.camera,{clientWidth:i,clientHeight:s}=this.viewerContainer;let n=1;if(e.type==="OrthographicCamera"){const r=e;n=Math.max(r.right-r.left,r.top-r.bottom)/r.zoom/Math.max(i,s)}else if(e.type==="PerspectiveCamera"){const r=e,a=new p.Vector3;e.getWorldPosition(a);const o=this.cameraManager.getTarget();a&&o&&(n=2*(a.distanceTo(o)*Math.tan(r.fov/2*(Math.PI/180)))/s)}return n}zoomToRect(){!this.zoomToRectHelper&&(this.zoomToRectHelper=new ul(this)),this.zoomToRectHelper.activate()}deactivateZoomRect(){this.zoomToRectHelper?.deactivate()}getUniqueModelId(e){let i=e;const s=n=>!!this.loadedModels.find(r=>r.modelId===n);if(s(i)){let n=1;for(;s(i+"_"+n);)n++;i=i+"_"+n,P.warn("[Viewer] Model '"+i+"' is loaded more than once!")}return i}getBBox(){const e=new p.Box3;return this.loadedModels.forEach(i=>{e.union(i.getBBox())}),e}flyToObject(e){this.cameraManager.flyToObject(e)}flyToObjects(e){const i=new p.Box3;e.forEach(n=>{const r=new p.Box3().setFromObject(n);i.union(r)});const s=new p.Sphere;i.getBoundingSphere(s),this.cameraManager.fitToSphere(s)}flyTo(e,i,s=!0){const n=this.camera;if(e.equals(i)){P.error("[Viewer] camera position and lookAt cannot be the same!");return}else if(!j.isVectorValid(e)||!j.isVectorValid(i)){P.error("[Viewer] invalid position or lookAt!");return}const r=e.distanceTo(i);r<n.near?(e=e.clone().sub(i).normalize().multiplyScalar(n.near*1.1),P.warn("[Viewer] camera could be too close to see the object!")):r>n.far&&(e=e.clone().sub(i).normalize().multiplyScalar(n.far*.9),P.warn("[Viewer] camera could be too far to see the object!")),this.cameraManager.flyTo(e,i,s)}flyToDirection(e){const i=this.getBBox(),s=i.getSize(new p.Vector3);let n=Math.max(s.x,s.y,s.z)/2;n===0&&(n=1);const r=this.cameraManager.getDistanceToFitSphere(n),a=new p.Vector3;i.getCenter(a);const o=a.clone().add(e.clone().multiplyScalar(r));this.flyTo(o,a)}goToHomeView(){if(this.homeView)this.cameraManager.flyToViewpoint(this.homeView);else{const e=new p.Vector3(1,.5,1);this.flyToDirection(e)}}viewFitAll(){const e=this.getBBox(),i=new p.Sphere;e.getBoundingSphere(i),this.cameraManager.fitToSphere(i)}zoomToBBox(e){this.cameraManager.flyToBox(e)}pickObject(e,i,s){let n=this.pickManager.pickObject(e,this.getRaycastableObjects(),i,s);return this.renderer&&this.renderer.clippingPlanes.length>0&&this.renderer?.clippingPlanes?.every(a=>{n&&a.distanceToPoint(n.point)>0})&&(n=void 0),n}pickObjects(e,i){let s=this.pickManager.pickObjects(e,this.getRaycastableObjects(),i);return s&&this.renderer.clippingPlanes.length>0&&(s=s.filter(n=>this.renderer.clippingPlanes.every(r=>r.distanceToPoint(n.point)>0))),s}getRaycastableObjects(){return this.sceneManager.getRaycastableObjects()}setBackgroundColor(e,i,s){if(!this.scene.background&&(this.scene.background=new p.Color(e,i,s)),this.scene.background instanceof p.Color){const n=new p.Color;n.setRGB(e,i,s,this.renderer.outputColorSpace),this.scene.background.copy(n)}this.enableRender()}setGlobalClipPlanes(e){}getCameraProjection(){return this.cameraManager.getProjection()}setCameraProjection(e){this.cameraManager.setProjection(e)}enableControl(e){this.cameraManager.enableControl(e)}enableRotate(e){this.cameraManager.enableRotate=e}enableZoom(e){this.cameraManager.enableZoom(e)}enablePan(e){this.cameraManager.enablePan(e)}getHomeView(){return this.homeView}setHomeView(e){this.homeView=e}getCameraConfig(){return this.cameraManager.getCameraConfig()}setCameraConfig(e){return this.cameraManager.setCameraConfig(e)}getCameraDirection(){return this.cameraManager.getCameraDirection()}getRenderInfo(){const e=this.renderer.info;return{drawCalls:e.render.calls,lines:e.render.lines,points:e.render.points,triangles:e.render.triangles,geometries:e.memory.geometries,textures:e.memory.textures,materials:e.programs?.length||0}}removeModel(e){const i=this.loadedModels.findIndex(n=>n.modelId===e);if(i===-1)return;const s=this.loadedModels.splice(i,1)[0];return this.sceneManager.removeModel(s),J.disposeObject(s.getModelObject()),this.enableRender(),s}destroy(){this.requestAnimationFrameHandle&&cancelAnimationFrame(this.requestAnimationFrameHandle),this.loaderHelper.abortDxfLoading(),this.css2dRenderer.domElement.remove(),this.container.destroy(),this.sceneManager.destroy(),this.cameraManager.destroy(),this.overlayRender.destroy(),this.spinner.destroy(),this.progressBar?.destroy(),this.undoManager.destroy()}addPlugin(e){if(this.plugins.find(s=>s.id===e.id)){P.warn("[Viewer] Plugin already exist: "+e.id);return}this.plugins.push(e),P.debug("[Viewer] Added plugin: "+e.id)}removePlugin(e){for(let i=0,s=this.plugins.length;i<s;i++)if(this.plugins[i]===e){this.plugins.splice(i,1);return}}clearPlugins(){this.plugins=[]}findPlugin(e){return this.plugins.find(i=>i.id===e)}}const pl=-1e3,Mi=new p.Vector3,ho=new p.Matrix4,uo=new p.Frustum,nr=new p.Box3,fo=new p.Matrix4;class Vr extends Mn{constructor(e){super(e);g(this,"name");g(this,"loadedModels");g(this,"masterModelId");g(this,"activeLayoutName");g(this,"dxfLayoutBar");g(this,"layoutInfos");g(this,"units");g(this,"enableHideVisuallySmallObjects");g(this,"sortedHidableObjects");g(this,"lastCameraZoom");g(this,"groundPlane");g(this,"raycastableObjects");g(this,"selectedObject");g(this,"loadingDxfCount");g(this,"textSearchHelper");g(this,"clickHighlightList");g(this,"_enableClickHighlight",!1);g(this,"requestHeaders");g(this,"_printCaptureMode",!1);this.name=$e.Viewer2d,this.loadedModels=[],this.masterModelId="",this.activeLayoutName="",this.layoutInfos={},this.units=void 0,this.enableHideVisuallySmallObjects=e.enableHideVisuallySmallObjects===!0,this.sortedHidableObjects={},this.lastCameraZoom=1/0,this.loadingDxfCount=0,e.enableLayoutBar&&(this.dxfLayoutBar=new tu(this)),this.cameraManager.setProjection(bt.Orthographic),this.cameraManager.setNavigationMode(lt.Plan);const i=new p.Vector3(0,0,100),s=new p.Vector3(0,0,0);this.cameraManager.setCameraConfig({eye:i,look:s}),this.resize(),this.setupDefaultEvents(),this.setDefaultBackground(),this.addEventListener(le.BeforeRender,()=>{this.updateRaycasterThreshold(),this.updateCameraZoomUniform(this.camera.zoom),this.updateHidableObjectsVisibility()})}get camera(){return this.cameraManager.camera}setupDefaultEvents(){let e=!1,i=!1;this.inputManager.addEventListener("pointerdown",s=>{i=!1,e=!0,s.button===Je.Middle&&this.inputManager?.setCursor("move")}),this.inputManager.addEventListener("pointermove",()=>{e&&(i=!0,this.inputManager?.setCursor("move"))}),this.inputManager.addEventListener("pointerup",s=>{if(e=!1,this.inputManager?.setCursor("default"),i){i=!1;return}const n=new p.Vector2(s.x,s.y),r=this.getWorldPositionByMousePick(n),a=this.pickManager.pickObjects(n,this.getRaycastableObjects(),void 0,3);let o;for(const d of a){const u=this.resolveEntityFromPick(d);if(u){u.hit=d,o=u;break}}const l=o?.userData;if(this._enableClickHighlight&&o){const d=this.getEntityBoundingBox(o);d&&this.highlightEntityBox(d)}else this.clearClickHighlight();const h={event:s,position:n,worldPosition:r,pooo:r,entity:l?o?.object:void 0,object:l?o?.object:void 0,point:l?o?.hit?.point:void 0,userData:l,handle:l?.handle};this.dispatchEvent(le.MouseClick,h)})}resolveEntityFromPick(e){if(!e)return;const i=e.object,s=i.userData?.batches;if(s&&s.length>0){const r=i.geometry,a=i.isMesh===!0,o=e.index;let l;a&&typeof e.faceIndex=="number"&&(l=r?.index?r.index.getX(e.faceIndex*3):e.faceIndex*3);const h=s.find(d=>{const u=typeof o=="number"&&o>=d.indexStart&&o<d.indexStart+(d.indexCount||1),f=typeof o=="number"&&o>=d.positionStart&&o<d.positionStart+d.positionCount||typeof l=="number"&&l>=d.positionStart&&l<d.positionStart+d.positionCount;return u||f});if(h?.userData)return{userData:h.userData,batch:h,object:i}}let n=i;for(;n;){if(n.userData?.handle)return{userData:n.userData,object:n};n=n.parent??void 0}}getEntityBoundingBox(e){const i=e.object,s=i.geometry?.getAttribute?.("position");if(e.batch&&s){const r=new p.Box3,a=e.batch.positionStart||0,o=e.batch.positionCount||0;if(o>0){i.updateWorldMatrix(!0,!1),fo.copy(i.matrixWorld);for(let l=a;l<a+o&&l<s.count;l++)Mi.fromBufferAttribute(s,l).applyMatrix4(fo),r.expandByPoint(Mi);if(!r.isEmpty())return r}}const n=new p.Box3;return n.setFromObject(i),n.isEmpty()?void 0:n}highlightEntityBox(e){const i=this.getOverlayRender();i&&(!this.clickHighlightList&&(this.clickHighlightList=new ws("entity-click-highlight"),i.addDrawableList(this.clickHighlightList)),this.clickHighlightList.clear(),this.clickHighlightList.addDrawable(new wt(j.guid(),[e.clone()],[.031,.906,.867,1],[.031,.906,.867,.15])),this.enableRender())}get enableClickHighlight(){return this._enableClickHighlight}set enableClickHighlight(e){this._enableClickHighlight=e,e||this.clearClickHighlight()}clearClickHighlight(){this.clickHighlightList?.clear(),this.enableRender()}setRequestHeaders(e){this.requestHeaders=e}handleMouseClick(e){if(!this.enableSelection)return;const i=new p.Vector2(e.x,e.y),s=this.getWorldPositionByMousePick(i);if(!s)return;const n=this.overlayRender.getDrawablesByPosition(s)[0];if(n){this.selectedObject===n?(this.selectedObject.selected=!1,this.selectedObject=void 0):(this.selectedObject&&this.clearSelection(),this.selectedObject=n,this.selectedObject.selected=!0),this.enableRender();return}const r=this.pickObject(i,[Ut]);if(r){const a=r?.object;this.selectedObject===a?(this.setObjectUnHighlight(this.selectedObject),this.selectedObject=void 0):(this.selectedObject&&this.clearSelection(),this.selectedObject=a,this.setObjectHighlight(this.selectedObject)),this.enableRender();return}this.clearSelection(),this.enableRender()}setDefaultBackground(){this.setBackgroundColor(.0295,.0212,.0152)}async loadModel(e,i,s){this.loaderHelper.abortDxfLoading();const n=this.getUniqueModelId(e.modelId||e.src);this.spinner.increaseJobCount(),this.loaderHelper.setFont(this.fontManager),this.masterModelId||(this.masterModelId=n);const r=n,a=We.t("ProgressBar.Loading"),o=d=>{this.progressBar?.updateProgress(r,a,d),i?.(new ProgressEvent("LoadProgress",{loaded:d,total:100}))},l=(d,u,f)=>{let m=d.loaded*100/d.total;m=m*(f-u)/100+u,this.progressBar?.updateProgress(r,a,m),i?.(new ProgressEvent("LoadProgress",{loaded:m,total:100}))},h=d=>l(d,0,90);this.progressBar?.addProgressItem(r),o(0);try{this.loadingDxfCount++;const d=this.viewerCfg,u=await this.loaderHelper.loadDxfData(e.src,e.modelId,h,void 0,{ignorePaperSpace:e.ignorePaperSpace,enableLocalCache:d.enableLocalCache,enableMerge:e.merge,encoding:e.encoding,overrideColor:e.overrideColor,requestHeaders:e.headers??this.requestHeaders}).finally(()=>{this.loadingDxfCount--,this.loadingDxfCount===0&&this.fontManager?.releaseFontData()}),f=u.threejsObject;if(s&&s({threejsObject:f,llbMesh:u.llbMesh}),e.matrix&&e.matrix.length===16){const b=new p.Matrix4;b.elements=e.matrix,f.applyMatrix4(b)}const m=new Ri({modelId:n,dxfData:u});this.addModel(m),o(100),this.progressBar?.delayRemoveProgressItem(r),this.dispatchEvent(le.ModelLoad)}catch(d){throw this.progressBar?.removeProgressItem(r),P.error("[Viewer2d] Failed to load model '"+e.src+"'",d),d}finally{this.spinner.decreaseJobCount()}}removeModel(e){const i=super.removeModel(e);return i&&this.textSearchHelper?.invalidateIndex(),i&&this.loadedModels.length===0&&(this.masterModelId="",this.activeLayoutName="",this.layoutInfos={},this.units=void 0),i}addModel(e){super.addModel(e);const i=e.modelId;if(e.dxfData){this.masterModelId===i?this.activateLayout(X.MODEL_LAYOUT_NAME):this.handleOverlayDxf(i);const s=e.getBBox(),n=new p.Vector3;s.getCenter(n),this.cameraManager.adjustCameraByBBox(s);const r=this.getDxfUnits(e);this.masterModelId===i&&(this.units=r)}else{const s=e.getModelObject();this.activeLayoutName=X.MODEL_LAYOUT_NAME;const n=new p.Box3().setFromObject(s);this.layoutInfos[this.activeLayoutName]={homeViewExtent:n,extent:n},s.matrixAutoUpdate=et,this.scene.add(s);const r=n.max.z;r>this.camera.position.z&&(this.camera.position.z=r,this.camera.updateProjectionMatrix()),this.flyToObject(s)}this.updateGroundPlane()}getDxfUnits(e){return!e&&this.loadedModels.length>0&&(e=this.loadedModels.find(i=>this.masterModelId===i.modelId)),e?e.getUnits():Ke.Unitless}handleOverlayDxf(e){const i=this.loadedModels.find(n=>e===n.modelId);if(!i){P.warn("[Viewer] Can't find model for modelId '"+e+"'!");return}i.switchTransformMs(X.MODEL_LAYOUT_NAME),i.getLayoutLevelObject(X.MODEL_LAYOUT_NAME)?.traverse(n=>{i.addSpatialFilterSection(n,i.dxfData)}),i.showLayoutObjects(X.MODEL_LAYOUT_NAME)}setObjectHighlight(e){this.loadedModels.forEach(i=>i.highlightObject(e)),this.enableRender()}setObjectUnHighlight(e){this.loadedModels.forEach(i=>i.unHighlightObject(e)),this.enableRender()}clearHighlight(){this.loadedModels.forEach(e=>e.clearHighlight()),this.enableRender()}clearSelection(){this.selectedObject instanceof p.Object3D&&this.setObjectUnHighlight(this.selectedObject),this.selectedObject instanceof Nt&&(this.selectedObject.selected=!1),this.selectedObject=void 0,this.clickHighlightList?.clear()}get enableSelection(){return this._enableSelection}set enableSelection(e){e||this.clearSelection(),this._enableSelection=e}updateGroundPlane(){const e=this.getActiveLayoutInfo();if(!e.homeViewExtent)return;const i=e.homeViewExtent.clone(),s=[],n=(o,l,h)=>{s.push(new p.Vector3(o,l,h))},r=i.getSize(new p.Vector3),a=i.getCenter(new p.Vector3);if(n(-r.x/2,-r.y/2,0),n(r.x/2,-r.y/2,0),n(r.x/2,r.y/2,0),n(-r.x/2,r.y/2,0),this.groundPlane)this.groundPlane.position.set(a.x,a.y,-r.z),this.groundPlane.geometry.setFromPoints(s),this.groundPlane.geometry.computeBoundingSphere(),this.groundPlane.geometry.computeBoundingBox();else{const o=new p.BufferGeometry;o.setFromPoints(s),o.setIndex([0,3,2,0,2,1]);const l=new p.MeshBasicMaterial({color:"#888",side:p.DoubleSide});this.groundPlane=new p.Mesh(o,l),this.groundPlane.visible=!1,this.groundPlane.position.set(a.x,a.y,-r.z),this.groundPlane.scale.set(1e5,1e5,1),this.groundPlane.name="groundPlane",this.groundPlane.renderOrder=pl,this.groundPlane.layers.enableAll(),J.disableLayerChannels(this.groundPlane,[Ut]),this.scene.add(this.groundPlane)}this.groundPlane.updateMatrix(),this.groundPlane.updateMatrixWorld(!0)}getRaycastableObjects(){const e=[],i=Date.now();if(this.activeLayoutName===X.MODEL_LAYOUT_NAME){if(this.raycastableObjects)return this.raycastableObjects;if(this.renderer?.renderLists){const s=this.renderer?.renderLists.get(this.scene,0);s&&(s.opaque.forEach(n=>{n.object&&n.object.geometry&&e.push(n.object)}),s.transparent.forEach(n=>{n.object&&n.object.geometry&&e.push(n.object)}))}ho.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse),uo.setFromProjectionMatrix(ho);for(const s of this.loadedModels){const n=s.getModelObject(),r=n.children.find(a=>a.name===this.activeLayoutName);r&&r.children.find(o=>o.name===X.SNAP_GROUP_NAME)?.traverse(o=>{if(J.isLeafObject(o)){if(nr.makeEmpty(),nr.expandByObject(o),!uo.intersectsBox(nr))return;e.push(o)}})}this.groundPlane&&e.push(this.groundPlane),P.debug("[Viewer] getRaycastableObjectsByMouse() from modelSpace"),this.raycastableObjects=e}else{const s=new WeakSet,n=this.getLayoutByName(this.activeLayoutName);n&&n.directAssociatedLeafObjectSet?.forEach(o=>{o.visible&&!s.has(o)&&(e.push(o),s.add(o))});const r=this.getViewportByPoint(this.pickManager.getRaycaster().ray.origin);r&&r.associatedLeafObjectSet?(r.associatedLeafObjectSet?.forEach(a=>{!s.has(a)&&(a.visible||a.userData.isSnapObject)&&(e.push(a),s.add(a))}),P.debug("[Viewer] getRaycastableObjectsByMouse() from inside of viewport:",r.viewportId)):P.debug("[Viewer] getRaycastableObjectsByMouse() from out of viewport"),this.groundPlane&&e.push(this.groundPlane)}return P.debug("[Viewer] getRaycastableObjectsByMouse() took "+(Date.now()-i)/1e3+" s"),e}getViewportByPoint(e){if(this.activeLayoutName.length===0||this.activeLayoutName===X.MODEL_LAYOUT_NAME)return;const i=this.getLayoutByName(this.activeLayoutName);if(!i)return;const s=a=>e.x<a.min.x||e.x>a.max.x||e.y<a.min.y||e.y>a.max.y,n=this.loadedModels.find(a=>this.masterModelId===a.modelId);if(!n)return;const r=n.getFilteredViewports(i);for(let a=0,o=r.length;a<o;a++){const l=r[a];if(!s(l.psBBox))return l}}getWorldPositionByMousePick(e){const i=[];this.groundPlane&&i.push(this.groundPlane);for(const n of this.loadedModels){const r=n.getModelObject();r&&(i.push(r),r.traverse(a=>{(a.isMesh||a.isLine)&&i.push(a)}))}return this.pickManager.pickObject(e,i)?.point}activateLayout(e=X.MODEL_LAYOUT_NAME){if(this.activeLayoutName===e||!this.masterModelId)return;const i=this.loadedModels.find(d=>this.masterModelId===d.modelId);if(!i)return;const s=i.getLayoutByName(e);if(!s)return;const n=this.getActiveLayoutInfo();if(this.groundPlane){const d=this.getCurrentViewExtent(),u=this.camera.position.z;n.lastViewExtent=new p.Box3(new p.Vector3(d.min.x,d.min.y,0),new p.Vector3(d.max.x,d.max.y,u))}const r=d=>!!this.layoutInfos[d]?.lastViewExtent,a=r(e);i?.activateLayout(e,a),this.activeLayoutName=e;const o=i.getFilteredViewports(s);if(P.debug("[Viewer] Active layout:",e,", viewports:",o),!a){const d=this.camera.position.z;let u=0;o.forEach(m=>{const b=m?.msToPsMatrix?.elements[14];b&&b>u&&(u=b)});const f=this.cameraManager.getPosition();if(u>f.z+d){const m=Math.ceil(u+d);f.z=m,P.info("[Viewer] Changing camera's z value from "+f.z+" to "+m),this.cameraManager.setCameraPosition(f)}}const l=this.getActiveLayoutInfo();if(l.lastViewExtent)this.zoomToBBox(l.lastViewExtent);else{l.extent=this.getBBox();let d=this.getLayoutExtentEx(s);if(d){const b=d.max.x-d.min.x,y=d.max.y-d.min.y;(b<1e-16||y<1e-16||b>1e16||y>1e16)&&(P.warn("[Viewer] Got wired bbox, max: "+d.max.toArray()+", min: "+d.min.toArray()+", going to use the calculated one..."),d=l.extent)}else P.warn("[Viewer] Failed to get layout extent, going to use the calculated one..."),d=l.extent;const u=l.extent;if(d&&!u.isEmpty()){const f=d.max.x-d.min.x,m=d.max.y-d.min.y,b=u.max.x-u.min.x,y=u.max.y-u.min.y;b>0&&y>0&&b<=f*.5&&y<=m*.5?d=u.clone():d.intersectsBox(u)?d.union(u):(P.warn("[Viewer] Layout extent from header is far from actual geometry, using computed bbox instead."),d=u.clone())}l.homeViewExtent=d,this.zoomToBBox(d)}const h=i.getLayoutLevelObject(e);h&&this.setLayoutHidableObjectArray(h),this.enableRender()}getLayoutExtentEx(e){const i=this.loadedModels.find(s=>this.masterModelId===s.modelId);if(i)return e.layoutName===X.MODEL_LAYOUT_NAME?i.getModelSpaceExtent():i.getLayoutExtent(e)}getActiveLayoutInfo(){return this.getLayoutInfo(this.activeLayoutName)}getLayoutByName(e){let i;const s=this.loadedModels.find(r=>this.masterModelId===r.modelId);if(!s)return;const n=s.getLayouts();for(const r of n)if(r.layoutName===e){i=r;break}return i}getEntityCount(){let e=0;return this.loadedModels.forEach(i=>{e+=i.loadedEntityCount}),e}getLayoutNames(){const e=[];return(this.loadedModels.find(n=>this.masterModelId===n.modelId)?.getLayouts()||[]).forEach(n=>{e.push(n.layoutName)}),e}getLayoutInfo(e){return this.layoutInfos[e]||(this.layoutInfos[e]={}),this.layoutInfos[e]}goToHomeView(){const e=this.getActiveLayoutInfo();e.homeViewExtent?this.zoomToBBox(e.homeViewExtent):P.error("[Viewer] Failed to find extent for "+this.activeLayoutName)}zoomToBBox(e){const i=e.getCenter(Mi),s=e.max.x-e.min.x,n=e.max.y-e.min.y,r=this.camera.right-this.camera.left,a=this.camera.top-this.camera.bottom;let o=Math.min(r/s,a/n);o/=1.1,this.cameraManager.cameraControls.moveTo(i.x,i.y,i.z),this.cameraManager.cameraControls.zoomTo(o)}getCurrentViewExtent(){const e=this.getHitResultByNdcCoordinate(new p.Vector2(-1,-1)),i=this.getHitResultByNdcCoordinate(new p.Vector2(1,1));return new p.Box2(e,i)}getHitResultByNdcCoordinate(e){const i=[];this.groundPlane&&i.push(this.groundPlane);const s=this.pickManager.pickObjectsByNdc(e,i);if(s.length>0){const n=s[0].point;return new p.Vector2(n.x,n.y)}}getHitResult(e){const i=this.viewerContainer,s=Oe.getScreenCoordinateByEvent(e,i),n=Oe.screen2Ndc(s,this.camera,i);return this.getHitResultByNdcCoordinate(n)}getActiveLayoutName(){return this.activeLayoutName}searchText(e,i){return!this.textSearchHelper&&(this.textSearchHelper=new Mr(this)),this.textSearchHelper.search(e,i)}focusText(e){!this.textSearchHelper&&(this.textSearchHelper=new Mr(this)),this.textSearchHelper.focus(e)}clearTextHighlight(){this.textSearchHelper?.clearHighlight()}zoomIn(e=.01){this.cameraManager.cameraControls.zoom(e)}zoomOut(e=.01){this.cameraManager.cameraControls.zoom(-e)}async print(e={}){const{area:i="view",paperSize:s="A4",orientation:n="auto",invertColors:r=!1,fitToPage:a=!0,margins:o=10,title:l="图纸"}=e;if(!this.loadedModels.length){P.warn("[Viewer] print: no model loaded.");return}const h=this.capturePrintImage(i,r),d=new Image;await new Promise((f,m)=>{d.onload=()=>f(),d.onerror=()=>m(new Error("Failed to load captured print image.")),d.src=h});const u=n==="auto"?d.width>=d.height?"landscape":"portrait":n;this.printImageInIframe({dataUrl:h,width:d.width,height:d.height,paperSize:s,orientation:u,invertColors:r,fitToPage:a,margins:o,title:l})}capturePrintImage(e,i){const s=this.cameraManager.cameraControls,n=this.renderer,r=s.getPosition(new p.Vector3),a=s.getTarget(new p.Vector3),o=this.camera.zoom,l=n.getPixelRatio();let h;e==="extents"&&(h=this.getActiveLayoutInfo().homeViewExtent??this.getBBox(),this.zoomToBBox(h)),this._printCaptureMode=!0;const d=this.sortedHidableObjects[this.activeLayoutName],u=[];if(d)for(const O of d)O.object.userData?.layerVisible!==!1&&(u.push({object:O.object,visible:O.object.visible}),O.object.visible=!0);const{clientWidth:f,clientHeight:m}=this.viewerContainer,b=Math.min(n.capabilities.maxTextureSize||4096,8192),y=Math.min(4,b/Math.max(f,m));y>l&&n.setPixelRatio(y),this.cameraManager.update(0),this.dispatchEvent(le.BeforeRender),n.render(this.scene,this.camera),this.dispatchEvent(le.AfterRender);const S=n.domElement,w=this.overlayRender.getCanvas(),x=document.createElement("canvas");x.width=S.width,x.height=S.height;const E=x.getContext("2d");if(E.drawImage(S,0,0),w&&w.width>0&&w.height>0&&E.drawImage(w,0,0,x.width,x.height),i){const O=new p.Color(1973806);this.scene.background instanceof p.Color?O.copy(this.scene.background):n.getClearColor(O),O.convertLinearToSRGB(),this.invertForPrint(x,Math.max(1,Math.round(y/2)),{r:O.r*255,g:O.g*255,b:O.b*255})}let M=x.toDataURL("image/png");if(h&&this.camera.type==="OrthographicCamera"){const O=this.cropCanvasToBox(x,h);O&&(M=O)}this._printCaptureMode=!1;for(const{object:O,visible:T}of u)O.visible=T;return n.setPixelRatio(l),s.zoomTo(o),s.setLookAt(r.x,r.y,r.z,a.x,a.y,a.z),this.cameraManager.update(0),this.enableRender(),M}invertForPrint(e,i,s){const n=e.getContext("2d",{willReadFrequently:!0});if(!n)return;const r=e.width,a=e.height,o=n.getImageData(0,0,r,a),l=o.data,h=r*a,d=45,u=.72,f=new Float32Array(h);for(let T=0,v=0;T<h;T++,v+=4){const C=l[v],_=l[v+1],A=l[v+2],I=C-s.r,B=_-s.g,k=A-s.b;if(Math.sqrt(I*I+B*B+k*k)<d){l[v]=255,l[v+1]=255,l[v+2]=255,f[T]=255;continue}const D=C/255,F=_/255,ie=A/255,se=Math.max(D,F,ie),Fe=Math.min(D,F,ie),ht=(se+Fe)/2,Te=se-Fe,Vi=Te===0?0:Te/(1-Math.abs(2*ht-1));let tt=0;Te!==0&&(se===D?tt=(F-ie)/Te%6:se===F?tt=(ie-D)/Te+2:tt=(D-F)/Te+4,tt/=6,tt<0&&(tt+=1));const Tn=Math.min(.55,(1-ht)*u),ke=(1-Math.abs(2*Tn-1))*Vi,At=ke*(1-Math.abs(tt*6%2-1)),ji=Tn-ke/2;let Gt=0,qt=0,Wt=0;const Yt=Math.floor(tt*6)%6;Yt===0?(Gt=ke,qt=At):Yt===1?(Gt=At,qt=ke):Yt===2?(qt=ke,Wt=At):Yt===3?(qt=At,Wt=ke):Yt===4?(Gt=At,Wt=ke):(Gt=ke,Wt=At),l[v]=(Gt+ji)*255,l[v+1]=(qt+ji)*255,l[v+2]=(Wt+ji)*255,f[T]=.299*l[v]+.587*l[v+1]+.114*l[v+2]}const m=Math.max(1,i),b=new Float32Array(h),y=new Uint8ClampedArray(h),S=new Uint8ClampedArray(h),w=new Uint8ClampedArray(h);for(let T=0;T<a;T++){const v=T*r;for(let C=0;C<r;C++){let _=255,A=v+C;const I=Math.max(0,C-m),B=Math.min(r-1,C+m);for(let k=I;k<=B;k++){const D=f[v+k];D<_&&(_=D,A=v+k)}b[v+C]=_,y[v+C]=l[A*4],S[v+C]=l[A*4+1],w[v+C]=l[A*4+2]}}const x=new Float32Array(h),E=new Uint8ClampedArray(h),M=new Uint8ClampedArray(h),O=new Uint8ClampedArray(h);for(let T=0;T<r;T++)for(let v=0;v<a;v++){let C=255,_=v*r+T;const A=Math.max(0,v-m),I=Math.min(a-1,v+m);for(let k=A;k<=I;k++){const D=b[k*r+T];D<C&&(C=D,_=k*r+T)}const B=v*r+T;x[B]=C,E[B]=y[_],M[B]=S[_],O[B]=w[_]}for(let T=0,v=0;T<h;T++,v+=4)f[T]>250&&x[T]<250&&(l[v]=E[T],l[v+1]=M[T],l[v+2]=O[T]);n.putImageData(o,0,0)}cropCanvasToBox(e,i){const s=this.camera,n=s.zoom||1,r=s.position.x,a=s.position.y,o=r+s.left/n,l=r+s.right/n,h=a+s.bottom/n,d=a+s.top/n,u=l-o,f=d-h;if(u<=0||f<=0)return;const m=v=>(v-o)/u*e.width,b=v=>(d-v)/f*e.height,y=Math.max(u,f)*.01,S=Math.max(0,Math.floor(m(i.min.x-y))),w=Math.min(e.width,Math.ceil(m(i.max.x+y))),x=Math.max(0,Math.floor(b(i.max.y+y))),E=Math.min(e.height,Math.ceil(b(i.min.y-y))),M=w-S,O=E-x;if(M<16||O<16)return;const T=document.createElement("canvas");return T.width=M,T.height=O,T.getContext("2d").drawImage(e,S,x,M,O,0,0,M,O),T.toDataURL("image/png")}printImageInIframe(e){const{dataUrl:i,width:s,height:n,paperSize:r,orientation:a,invertColors:o,fitToPage:l,margins:h,title:d}=e,u={A4:[210,297],A3:[297,420],A2:[420,594],A1:[594,841],A0:[841,1189],Letter:[215.9,279.4]};let[f,m]=u[r]??u.A4;a==="landscape"&&([f,m]=[m,f]);const b=document.createElement("iframe");b.setAttribute("aria-hidden","true");const y=96/25.4;b.style.cssText=`position:fixed;left:-20000px;top:0;border:0;visibility:hidden;width:${Math.ceil(f*y)}px;height:${Math.ceil(m*y)}px;`;const S=v=>v.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),w=l?"max-width:100%;max-height:100%;width:auto;height:auto;":"width:100%;height:auto;",x=`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${S(d)}</title><style>@page{size:${r} ${a};margin:${h}mm;}html,body{margin:0;padding:0;background:#fff;}body{display:flex;align-items:center;justify-content:center;width:${f-2*h}mm;height:${m-2*h}mm;overflow:hidden;}img{display:block;${w}}</style></head><body><img src="${i}" alt="${S(d)}"></body></html>`;document.body.appendChild(b);const E=()=>{b.contentWindow?.removeEventListener("afterprint",E),setTimeout(()=>b.remove(),100)},M=b.contentDocument;M.open(),M.write(x),M.close();const O=M.querySelector("img"),T=()=>{const v=b.contentWindow;v.addEventListener("afterprint",E),v.focus(),v.print(),setTimeout(E,6e4)};O.complete?T():(O.onload=T,O.onerror=E)}getLayers(){const e=[];if(this.masterModelId){const i=this.loadedModels.find(n=>this.masterModelId===n.modelId),s=i?.layers;s&&e.push({modelId:this.masterModelId,layers:s})}for(const i of this.loadedModels){const s=i.modelId;if(s===this.masterModelId)continue;const n=i.layers;n&&e.push({modelId:s,layers:n})}return e}setModelVisibility(e,i){const s=this.loadedModels.find(n=>e===n.modelId);if(!s)throw new Error("Failed to find model by modelId '"+e+"'!");s.setVisible(i),this.enableRender()}setLayerVisibility(e,i,s){const n=this.camera;s=s||this.masterModelId;const r=this.loadedModels.find(a=>s===a.modelId);if(!r)throw new Error("Failed to find layer by modelId '"+s+"'!");r.setLayerVisible(e,i,this.enableHideVisuallySmallObjects,n.zoom),this.raycastableObjects=void 0,this.enableRender()}setLayerOpacity(e,i,s){s=s||this.masterModelId;const n=this.loadedModels.find(r=>s===r.modelId);if(!n)throw new Error("Failed to find layer by modelId '"+s+"'!");n.setLayerOpacity(e,i),this.enableRender()}setLayerColor(e,i,s){s=s||this.masterModelId;const n=this.loadedModels.find(r=>s===r.modelId);if(!n)throw new Error("Failed to find layer by modelId '"+s+"'!");this.clearSelection(),n.setLayerColor(e,i),this.enableRender()}resetLayerColor(e,i){i=i||this.masterModelId;const s=this.loadedModels.find(n=>i===n.modelId);if(!s)throw new Error("Failed to find model by modelId '"+i+"'!");this.clearSelection(),s.resetLayerColor(e),this.enableRender()}getVisiblePixelSize(e){const i=p.MathUtils.smoothstep(e,1e4,3e4)*6.5+.5;return P.debug("[Viewer] visiblePixelSize:",i),i}setLayoutHidableObjectArray(e){const i=this.camera;if(!this.enableHideVisuallySmallObjects||!i)return;const s=Date.now(),n=e.name;this.sortedHidableObjects[n]||(this.sortedHidableObjects[n]=[]);const r=this.sortedHidableObjects[n];this.cameraManager.update(0);const a=i.zoom;this.lastCameraZoom=a;let o=1;e.traverse(h=>{if(h.userData.isSnapObject||!J.isLeafObject(h))return;const d=h.geometry;d.boundingBox||d.computeBoundingBox();const u=d.boundingBox.clone();if(!u||!j.isBoxValid(u))return;u.applyMatrix4(h.matrixWorld),u.getSize(Mi);const f=Math.max(Mi.x,Mi.y),m=o/f;m<1/0?r.push({visibleMinZoom:m,object:h}):h instanceof p.Points?r.push({visibleMinZoom:o,object:h}):P.warn("[Viewer] The size of bbox is 0 ! ",h)}),o=this.getVisiblePixelSize(r.length);let l=0;r.forEach(h=>{const d=h.visibleMinZoom*o;h.visibleMinZoom=d,h.object.userData.visibleMinZoom=d,d>a&&(h.object.visible=!1,l++)}),r.sort((h,d)=>h.visibleMinZoom-d.visibleMinZoom),P.debug("[Viewer] setLayoutHidableObjectArray took: "+(Date.now()-s)/1e3+"s, "+l+" objects changed to hidden")}updateRaycasterThreshold(){const e=this.getPixelSizeInWorldCoord()*3,i=this.getRaycaster().params;i.Line?i.Line.threshold=e:i.Line={threshold:e},i.Points?i.Points.threshold=e:i.Points={threshold:e}}updateHidableObjectsVisibility(){const e=this.camera,i=Date.now();this.cameraManager.update(0);const s=e.zoom;if(Math.abs(s-this.lastCameraZoom)<1e-5)return;if(this.updateRaycasterThreshold(),this.updateCameraZoomUniform(s),this.raycastableObjects=void 0,this._printCaptureMode){this.lastCameraZoom=s;return}if(!this.sortedHidableObjects[this.activeLayoutName])return;const n=this.sortedHidableObjects[this.activeLayoutName];if(n.length===0)return;const r=s>this.lastCameraZoom,a=Math.min(s,this.lastCameraZoom),o=Math.max(s,this.lastCameraZoom),l=[];let h=0;for(let d=0;d<n.length;++d)if(n[d].object.userData.layerVisible!==!1){if(n[d].visibleMinZoom<a){l.push(n[d].object);continue}else if(n[d].visibleMinZoom>o)break;n[d].object.visible=r,r&&l.push(n[d].object),h++}this.lastCameraZoom=s,P.debug("[Viewer] updateHidableObjectsVisibility took: "+(Date.now()-i)/1e3+"s, "+h+"(out of "+n.length+") objects changed to "+(r?"visible":"hidden"))}updateCameraZoomUniform(e){X.CameraZoomUniform.value=e*this.container.height/50}}class ml{constructor(t){g(this,"viewer");g(this,"fontManager");g(this,"loader");g(this,"loadingManager");g(this,"changes");g(this,"container");g(this,"spinner");g(this,"jobCount");g(this,"loadingProgressBar");this.jobCount=0,this.viewer=new Vr(t);const e=document.getElementById(t.containerId);this.container=e?.parentElement||document.body;const i=new Rr(t.containerId);this.loadingProgressBar=new Fr(i);const s={ignorePaperSpace:!0};this.loader=new X(this.loadingManager,s),this.initSpinner()}initSpinner(){const t=document.createElement("div");t.classList.add("x-spinner"),t.appendChild(document.createElement("span")),t.appendChild(document.createElement("span")),t.appendChild(document.createElement("span")),t.appendChild(document.createElement("span")),this.container.appendChild(t),this.spinner=t,this.setSpinnerVisibility(this.jobCount>0)}async setFont(t){const e=Date.now();!this.fontManager&&(this.fontManager=new xt),await this.fontManager.loadFonts(t),P.info("[DxfCompareHelper] Font file(s) load time in "+(Date.now()-e)/1e3+"s")}async compare(t,e,i,s){const{src:n,modelId:r}=t,{src:a}=e;this.viewer.masterModelId=r||n;const o=Date.now();this.increaseJobCount();try{if(!this.fontManager)throw"[DxfCompareHelper] Should set font first!";this.loader.setFont(this.fontManager),await this.fontManager.getFontFromIndexeddb();const l=n+a,h=We.t("ProgressBar.Comparing"),d=B=>{this.loadingProgressBar?.updateProgress(l,h,B),s&&s(new ProgressEvent("CompareProgress",{loaded:B,total:100}))},u=(B,k,D)=>{let F=B.loaded*100/B.total;F=F*(D-k)/100+k,this.loadingProgressBar?.updateProgress(l,h,F),s&&s(new ProgressEvent("CompareProgress",{loaded:F,total:100}))},f=B=>u(B,0,15),m=B=>u(B,15,30),b=B=>u(B,30,60),y=B=>u(B,60,95);j.printMemory("Before comparing"),this.loadingProgressBar?.addProgressItem(l),d(0);let S=Date.now();const w=this.loader.parse(n,f),x=this.loader.parse(a,m),[E,M]=await Promise.allSettled([w,x]);if(E.status==="rejected")throw"[DxfCompareHelper] Failed to parse "+n;if(M.status==="rejected")throw"[DxfCompareHelper] Failed to parse "+a;if(P.info("[DxfCompareHelper] loadFiles in "+(Date.now()-S)/1e3+"s"),this.loader.isAborted())throw"[DxfCompareHelper] compare loadFile aborted";const O=E.value,T=M.value;S=Date.now();const v=await new ot(O,T,i).compare(b);if(P.info("[DxfCompareHelper] Compared in "+(Date.now()-S)/1e3+"s"),P.debug("[DxfCompareHelper] Compared results:",v),this.loader.isAborted())throw"[DxfCompareHelper] compare change aborted";j.printMemory("After getting the comparison results"),S=Date.now(),await this.loader.loadEntitiesForCompare(O,T,v,!0,y),j.printMemory("After Creating threejs objects based on comparison result"),this.fontManager?.releaseFontData(),this.changes=v,P.info("[DxfCompareHelper] Creates threejs objects based on comparison result in "+(Date.now()-S)/1e3+"s");const C=O,_=T;if(!Object.keys(v).length&&P.info("[DxfCompareHelper] No change found"),C.threejsObject?.children.length===0&&_.threejsObject?.children.length===0){const B="[DxfCompareHelper] Nothing was loaded from "+n+" and "+a;throw P.warn(B),B}const A=C.threejsObject,I=_.threejsObject;A.name=n,I.name=a,S=Date.now(),this.viewer.addModel(new Ri({modelId:t.modelId||t.src,dxfData:C})),this.viewer.flyToObject(A),j.printMemory("After adding first loaded Model to scene"),d(95),this.viewer.addModel(new Ri({modelId:e.modelId||e.src,dxfData:_})),j.printMemory("After adding second loaded Model to scene"),P.info("[DxfCompareHelper] Added compared objects to scene in "+(Date.now()-S)/1e3+"s"),P.info("[DxfCompareHelper] The comparison between "+n+"' and '"+a+"' is completed in "+(Date.now()-o)/1e3+"s !"),d(100),this.loadingProgressBar?.delayRemoveProgressItem(l)}catch(l){throw this.loadingProgressBar?.removeProgressItem(n+a),l}finally{this.decreaseJobCount()}}getChanges(){return this.changes}zoomToChange(t){if(this.changes){const e=this.changes[t];if(!e)return;const i=e.box;i&&this.viewer.zoomToBBox(i.clone().expandByScalar(1.2))}}setSpinnerVisibility(t){this.spinner&&(t?this.spinner.classList.remove("hidden"):this.spinner.classList.add("hidden"))}increaseJobCount(){this.setSpinnerVisibility(++this.jobCount>0)}decreaseJobCount(){this.setSpinnerVisibility(--this.jobCount>0)}}class Bu extends ml{constructor(e,i){super(e);g(this,"viewer2");g(this,"syncCamera");g(this,"markupManager1");g(this,"markupManager2");g(this,"syncCameraControls");this.syncCamera=!1,this.syncCameraControls=(s,n,r)=>{const a=new p.Vector3,o=new p.Vector3,l=new p.Vector3;s.getPosition(o),s.getTarget(l),s.getFocalOffset(a),n.setLookAt(o.x,o.y,o.z,l.x,l.y,l.z),n.zoomTo(r),n.dispatchEvent({type:"control"})},this.viewer2=new Vr(i),this.initSyncCameraEvent()}initSyncCameraEvent(){const e=this.viewer.getCameraManager().cameraControls,i=this.viewer2.getCameraManager().cameraControls;let s=!1;e.addEventListener("control",()=>{s=!1}),e.addEventListener("update",()=>{!this.syncCamera||s||this.syncCameraControls(e,i,this.viewer.camera.zoom)}),i.addEventListener("control",()=>{s=!0}),i.addEventListener("update",()=>{!this.syncCamera||!s||this.syncCameraControls(i,e,this.viewer2.camera.zoom)})}enableSyncCamera(e){if(this.syncCamera=e,e){const i=this.viewer.getCameraManager().cameraControls,s=this.viewer2.getCameraManager().cameraControls;this.syncCameraControls(i,s,this.viewer.camera.zoom)}}async compare(e,i,s,n){const{src:r,modelId:a}=e,{src:o,modelId:l}=i;this.viewer.masterModelId=a||r,this.viewer2.masterModelId=l||o;const h=Date.now();this.increaseJobCount();try{if(!this.fontManager)throw"[DxfCompareHelper] Should set font first!";this.loader.setFont(this.fontManager),await this.fontManager.getFontFromIndexeddb();const d=r+o,u=We.t("ProgressBar.Comparing"),f=D=>{this.loadingProgressBar?.updateProgress(d,u,D),n&&n(new ProgressEvent("CompareProgress",{loaded:D,total:100}))},m=(D,F,ie)=>{let se=D.loaded*100/D.total;se=se*(ie-F)/100+F,this.loadingProgressBar?.updateProgress(d,u,se),n&&n(new ProgressEvent("CompareProgress",{loaded:se,total:100}))},b=D=>m(D,0,15),y=D=>m(D,15,30),S=D=>m(D,30,60),w=D=>m(D,60,95);j.printMemory("Before comparing"),this.loadingProgressBar?.addProgressItem(d),f(0);let x=Date.now();const E=this.loader.parse(r,b),M=this.loader.parse(o,y),[O,T]=await Promise.allSettled([E,M]);if(O.status==="rejected")throw"[DxfCompareHelper] Failed to parse "+r;if(T.status==="rejected")throw"[DxfCompareHelper] Failed to parse "+o;if(P.info("[DxfCompareHelper] loadFiles in "+(Date.now()-x)/1e3+"s"),this.loader.isAborted())throw"[DxfCompareHelper] compare loadFile aborted";const v=O.value,C=T.value;x=Date.now();const _=await new ot(v,C,s).compare(S);if(P.info("[DxfCompareHelper] Compared in "+(Date.now()-x)/1e3+"s"),P.debug("Compared results:",_),this.loader.isAborted())throw"[DxfCompareHelper] compare change aborted";j.printMemory("After getting the comparison results"),x=Date.now(),await this.loader.loadEntitiesForCompare(v,C,_,!1,w),j.printMemory("After Creating threejs objects based on comparison result"),this.fontManager?.releaseFontData(),this.changes=_,P.info("[DxfCompareHelper] Creates threejs objects based on comparison result in "+(Date.now()-x)/1e3+"s");const A=v,I=C;if(!Object.keys(_).length&&P.info("[DxfCompareHelper] No change found"),A.threejsObject?.children.length===0&&I.threejsObject?.children.length===0){const D="[DxfCompareHelper] Nothing was loaded from "+r+" and "+o;throw P.warn(D),D}const B=A.threejsObject,k=I.threejsObject;B.name=r,k.name=o,x=Date.now(),this.viewer.addModel(new Ri({modelId:e.modelId||e.src,dxfData:A})),j.printMemory("After adding first loaded Model to scene"),f(95),this.viewer2.addModel(new Ri({modelId:i.modelId||i.src,dxfData:I})),j.printMemory("After adding second loaded Model to scene"),this.drawCompareBoxes(),P.info("[DxfCompareHelper] Added compared objects to scene in "+(Date.now()-x)/1e3+"s"),P.info("[DxfCompareHelper] The comparison between "+r+"' and '"+o+"' is completed in "+(Date.now()-h)/1e3+"s !"),f(100),this.loadingProgressBar?.delayRemoveProgressItem(d)}catch(d){throw this.loadingProgressBar?.removeProgressItem(r+o),d}finally{this.decreaseJobCount()}}drawCompareBoxes(){this.changes&&(this.markupManager1??(this.markupManager1=new vr(this.viewer)),this.markupManager2??(this.markupManager2=new vr(this.viewer2)),requestAnimationFrame(()=>{this.markupManager1?.drawCompareDrawable(this.changes),this.markupManager2?.drawCompareDrawable(this.changes),this.viewer.enableRender(),this.viewer2.enableRender()}))}zoomToChange(e){if(this.changes){const i=this.changes[e];if(!i)return;const s=i.box;s&&(this.viewer.zoomToBBox(s.clone().expandByScalar(1.2)),this.viewer2.zoomToBBox(s.clone().expandByScalar(1.2)))}}}class Pi{constructor(t,e){g(this,"current");g(this,"next");g(this,"inNormal");g(this,"outNormal");this.current=t,this.next=e,this.inNormal=this.inwardsNormal(),this.outNormal=this.outwardsNormal()}outwardsNormal(){const t=this.inwardsNormal();return[-t[0],-t[1]]}inwardsNormal(){const t=this.next[0]-this.current[0],e=this.next[1]-this.current[1],i=Math.sqrt(t*t+e*e);if(i===0)throw new Error("Vertices overlap");return[-e/i,t/i]}offset(t,e){return Pi.offsetEdge(this.current,this.next,t,e)}inverseOffset(t,e){return Pi.offsetEdge(this.next,this.current,t,e)}inverse(){return new Pi(this.next,this.current)}static offsetEdge(t,e,i,s){return new Pi([t[0]+i,t[1]+s],[e[0]+i,e[1]+s])}}const ss=Array.isArray,po=(c,t)=>c[0]===t[0]&&c[1]===t[1],rr=c=>Array.isArray(c)&&c.length,gl=(c,t=0,e=!1)=>{let i,s;if(rr(c)&&typeof c[0][0]=="number"){let n=0;const r=c;for(i=0,s=r.length;i<s;i++){const a=r[i],o=r[(i+1)%s];n+=a[0]*o[1],n-=o[0]*a[1]}(!e&&n>0||e&&n<0)&&r.reverse()}else for(i=0,s=c.length;i<s;i++)gl(c[i],t+1,i>0);if(t===0&&rr(c)&&rr(c[0])&&typeof c[0][0][0]=="number"){const n=c[0].slice(0,1)[0];c[0].pop(),c[0].push([n[0],n[1]])}return c};class ku{constructor(t,e=5){g(this,"vertices");g(this,"edges");g(this,"arcSegments");g(this,"distance");if(this.distance=0,this.arcSegments=e,!ss(t))throw new Error("Offset requires at least one coodinate to work with");this.edges=[],ss(t)&&typeof t[0]=="number"?this.vertices=t:(this.vertices=gl(t),this.processContour(this.vertices,this.edges))}processContour(t,e){let i,s;if(ss(t[0])&&typeof t[0][0]=="number")for(t=t,e=e,s=t.length,po(t[0],t[s-1])&&(s-=1),i=0;i<s;i++)e.push(new Pi(t[i],t[(i+1)%s]));else for(t=t,e=e,i=0,s=t.length;i<s;i++)e.push([]),this.processContour(t[i],e[e.length-1])}setArcSegments(t){return this.arcSegments=t,this}createArc(t,e,i,s,n,r,a){const o=Math.PI*2;let l=Math.atan2(s[1]-e[1],s[0]-e[0]),h=Math.atan2(n[1]-e[1],n[0]-e[0]);r%2===0&&(r-=1),l<0&&(l+=o),h<0&&(h+=o);let d=l>h?l-h:l+o-h;const u=(a?-d:o-d)/r;t.push(s);for(let f=1;f<r;++f)d=l+u*f,t.push([e[0]+Math.cos(d)*i,e[1]+Math.sin(d)*i]);return t.push(n),t}setDistance(t){return this.distance=t,this}ensureLastPoint(t){return po(t[0],t[t.length-1])||t.push([t[0][0],t[0][1]]),t}offset(t){return this.setDistance(t),this.distance===0?this.vertices:this.distance>0?this.margin(this.distance):this.padding(-this.distance)}offsetSegment(t,e,i,s){const n=[i.offset(i.inNormal[0]*s,i.inNormal[1]*s),i.inverseOffset(i.outNormal[0]*s,i.outNormal[1]*s)],r=[];for(let a=0,o=2;a<o;a++){const l=n[a],h=n[(a+o-1)%o];this.createArc(r,a===0?t:e,s,h.next,l.current,this.arcSegments,!0)}return r}margin(t){if(this.setDistance(t),typeof this.vertices[0]=="number")return this.offsetPoint(this.distance);if(t===0)return this.vertices;let e=this.offsetLines(this.distance);return e=Ui.union(this.vertices,e),e}padding(t){if(this.setDistance(t),this.distance===0)return this.vertices;if(this.vertices.length===2&&typeof this.vertices[0]=="number")return this.vertices;const e=this.offsetLines(this.distance);return Ui.difference(this.vertices,e)}offsetLine(t){return t===0?this.vertices:this.offsetLines(t)}offsetLines(t){if(t<0)throw new Error("Cannot apply negative margin to the line");this.setDistance(t);let e=[];if(ss(this.vertices[0])&&typeof this.vertices[0][0]!="number"){const i=[];for(let s=0,n=this.edges.length;s<n;s++){const r=this.offsetContour(this.vertices[s],this.edges[s]);r.length>0&&i.push(r)}i.length>0&&(e=i.length===1?i[0]:Ui.union(i[0],...i.slice(1)))}else e=this.vertices.length===1?this.offsetPoint(t):this.offsetContour(this.vertices,this.edges);return e}offsetContour(t,e){let i=[],s=0,n=0;if(ss(t[0])&&typeof t[0][0]=="number"){for(s=0,n=t.length-1;s<n;s++){const r=this.ensureLastPoint(this.offsetSegment(t[s],t[s+1],e[s],this.distance)),a=[r];i.push(a)}i.length>0&&(i=i.length===1?[i[0]]:Ui.union(i[0],i.slice(1)))}else{const r=[];for(s=0,n=e.length;s<n;s++){const a=this.offsetContour(t[s],e[s]);a.length>0&&r.push(a)}r.length>0&&(i=r.length===1?r[0]:Ui.union(r[0],...r.slice(1)))}return i}offsetPoint(t){this.setDistance(t);let e=this.arcSegments*2;const i=[],s=this.vertices,n=this.distance;let r=0;e%2===0&&e++;for(let a=0;a<e;a++)r+=2*Math.PI/e,i.push([s[0]+n*Math.cos(r),s[1]+n*Math.sin(r)]);return[[this.ensureLastPoint(i)]]}}class yl{constructor(t){g(this,"viewer");g(this,"composerEnabled");g(this,"composer");g(this,"renderPass");g(this,"effectFxaaPass");g(this,"saoPass");g(this,"ssaoPass");g(this,"outlinePass");g(this,"ssaaRenderPass");g(this,"bloomPass");g(this,"unrealBloomPass");g(this,"vertexNormalsHelpers");this.composerEnabled=!0,this.viewer=t,this.composer=new ec.EffectComposer(this.viewer.renderer),this.viewer.addEventListener(le.AfterRender,()=>this.render())}get enabled(){return this.composerEnabled}set enabled(t){this.composerEnabled=t}get renderPassEnabled(){return!!this.renderPass?.enabled}set renderPassEnabled(t){const e=this.viewer.scene,i=this.viewer.camera,{width:s,height:n}=this.viewer.container;if(this.composer){if(t&&!this.renderPass){const r=new tc.RenderPass(e,i);r.setSize(s,n),this.composer.addPass(r),this.renderPass=r}this.renderPass&&(this.renderPass.enabled=t),this.viewer.enableRender()}}get fxaaPassEnabled(){return!!this.effectFxaaPass?.enabled}set fxaaPassEnabled(t){if(!this.composer)return;const{width:e,height:i}=this.viewer.container;if(t&&!this.effectFxaaPass){const s=new ic.ShaderPass(cc.FXAAShader);s.uniforms.resolution.value.set(1/e,1/i),s.renderToScreen=!0,s.setSize(e,i),this.composer.addPass(s),this.effectFxaaPass=s}this.effectFxaaPass&&(this.effectFxaaPass.enabled=t),this.viewer.enableRender()}get saoPassEnabled(){return!!this.saoPass?.enabled}set saoPassEnabled(t){const{width:e,height:i}=this.viewer.container,s=this.viewer.scene,n=this.viewer.camera;if(this.composer){if(t&&!this.saoPass){const r=new sc.SAOPass(s,n,new p.Vector2(1/e,1/i));r.setSize(e,i),r.params.output=0,r.params.saoBias=.5,r.params.saoIntensity=3e-4,r.params.saoScale=8,r.params.saoKernelRadius=40,r.params.saoMinResolution=0,this.composer.addPass(r),this.saoPass=r}this.saoPass&&(this.saoPass.enabled=t),this.viewer.enableRender()}}get ssaoPassEnabled(){return!!this.ssaoPass?.enabled}set ssaoPassEnabled(t){const e=this.viewer.scene,i=this.viewer.camera,{width:s,height:n}=this.viewer.container;if(this.composer){if(t&&!this.ssaoPass){const r=new nc.SSAOPass(e,i,s,n);r.kernelRadius=16,r.minDistance=1e-4,r.maxDistance=.3,this.composer.addPass(r),this.ssaoPass=r}this.ssaoPass&&(this.ssaoPass.enabled=t),this.viewer.enableRender()}}get outlinePassEnabled(){return!!this.outlinePass?.enabled}set outlinePassEnabled(t){const e=this.viewer.scene,i=this.viewer.camera,{width:s,height:n}=this.viewer.container;if(this.composer){if(t&&!this.outlinePass){const r=new rc.OutlinePass(new p.Vector2(s,n),e,i);r.edgeStrength=3,r.edgeGlow=0,r.edgeThickness=2,r.pulsePeriod=0,r.visibleEdgeColor.set(16711680),r.hiddenEdgeColor.set(16752768),this.composer.addPass(r),this.outlinePass=r}this.outlinePass&&(this.outlinePass.enabled=t),this.viewer.enableRender()}}get ssaaPassEnabled(){return!!this.ssaaRenderPass?.enabled}set ssaaPassEnabled(t){const e=this.viewer.scene,i=this.viewer.camera;if(this.composer){if(t&&!this.ssaaRenderPass){const s=new ac.SSAARenderPass(e,i,16777215,0);this.composer.addPass(s),this.ssaaRenderPass=s,this.ssaaRenderPass=s}this.ssaaRenderPass&&(this.ssaaRenderPass.enabled=t),this.viewer.enableRender()}}get bloomPassEnabled(){return!!this.bloomPass?.enabled}set bloomPassEnabled(t){if(this.composer){if(t&&!this.bloomPass){const e=new oc.BloomPass(1,25,4);e.renderToScreen=!0,this.composer.addPass(e),this.bloomPass=e}this.bloomPass&&(this.bloomPass.enabled=t),this.viewer.enableRender()}}get unrealBloomPassEnabled(){return!!this.unrealBloomPass?.enabled}set unrealBloomPassEnabled(t){const{width:e,height:i}=this.viewer.container;if(this.composer){if(t&&!this.unrealBloomPass){const s=new lc.UnrealBloomPass(new p.Vector2(e,i),1,0,0);s.threshold=0,s.strength=.5,s.radius=0,this.composer.addPass(s),this.unrealBloomPass=s}this.unrealBloomPass&&(this.unrealBloomPass.enabled=t),this.viewer.enableRender()}}setOutlinePassSelectObjects(t){this.outlinePass&&(this.outlinePass.selectedObjects=t)}enableModelEdges(t){const e=this.viewer.loadedModels;for(let i=0;i<e.length;++i){const s=e[i];if(s instanceof kr)if(t&&!s.edges){const n=s.getModelObject();n&&(P.debug("[Viewer] Generating outlines for model '"+n.id+"'"),s.enableOutline(t))}else s.edges&&s.edges.forEach(n=>n.visible=t);else s instanceof Lr&&P.warn("[BimTiles] enableModelEdges() is not implemented for bimtiles yet.")}this.viewer.enableRender()}showVertexNormals(t,e=.1){t?(!this.vertexNormalsHelpers&&(this.vertexNormalsHelpers=new p.Group),this.viewer.scene.traverseVisible(i=>{const s=["SKYBOX","GROUND_GRID","GROUND_GRASS","BIM_VIEWER_BOX_HELPER"];if(i instanceof p.Mesh&&!s.includes(i.name)){if(!i.geometry.attributes.normal)return;const r=new hc.VertexNormalsHelper(i,e,16711680);this.vertexNormalsHelpers?.add(r)}}),this.viewer.scene.add(this.vertexNormalsHelpers)):this.vertexNormalsHelpers&&(this.viewer.scene.remove(this.vertexNormalsHelpers),this.vertexNormalsHelpers=void 0)}render(){!this.composer||!this.enabled||this.composer.render()}destroy(){this.renderPass&&(this.composer?.removePass(this.renderPass),this.renderPass.dispose(),this.renderPass=void 0),this.effectFxaaPass&&(this.composer?.removePass(this.effectFxaaPass),this.effectFxaaPass.dispose(),this.effectFxaaPass=void 0),this.saoPass&&(this.composer?.removePass(this.saoPass),this.saoPass.dispose(),this.saoPass=void 0),this.ssaoPass&&(this.composer?.removePass(this.ssaoPass),this.ssaoPass.dispose(),this.ssaoPass=void 0),this.outlinePass&&(this.composer?.removePass(this.outlinePass),this.outlinePass.dispose(),this.outlinePass=void 0),this.ssaaRenderPass&&(this.composer?.removePass(this.ssaaRenderPass),this.ssaaRenderPass.dispose(),this.ssaaRenderPass=void 0),this.bloomPass&&(this.composer?.removePass(this.bloomPass),this.bloomPass.dispose(),this.bloomPass=void 0),this.unrealBloomPass&&(this.composer?.removePass(this.unrealBloomPass),this.unrealBloomPass.dispose(),this.unrealBloomPass=void 0),this.composer&&(this.composer?.dispose(),this.composer=void 0)}}class Du extends Mn{constructor(e,i){super(e);g(this,"name");g(this,"loadedModels");g(this,"distanceCullingFactor");g(this,"selectedObject");g(this,"effect");if(this.name=$e.Viewer3d,this.loadedModels=[],this.distanceCullingFactor=150,this.effect=new yl(this),this.sceneManager.enableLights(!0),i)this.setHomeView(i),this.cameraManager.flyToViewpoint(i);else{const s=new p.Vector3(100,50,100),n=new p.Vector3(0,0,0),r={eye:s,look:n};this.cameraManager.flyToViewpoint(r)}this.cameraManager.setProjection(bt.Perspective),this.cameraManager.setNavigationMode(lt.Orbit),this.setupDefaultEvents(),this.setDefaultBackground()}setupDefaultEvents(){let e=!1,i,s=0,n=0,r=0;const a=300,o=u=>n===-1||r===-1?!1:Math.abs(u.x-n)<5&&Math.abs(u.y-r)<5,l=u=>{const f=u.timestamp-s;return!!(u.button===Je.Left&&f<a&&o(u))};let h,d=!1;this.inputManager.addEventListener("pointerdown",u=>{e=!1,i=u.button;const f=new p.Vector2(u.x,u.y);h=this.pickObject(f),d=h?.object===this.selectedObject,u.button===Je.Left&&this.handleAnchorPoint(h)}),this.inputManager.addEventListener("pointermove",u=>{i!==void 0&&(e=!o(u),i===Je.Left&&this.cameraManager.enableRotate&&this.cameraManager.setOrbitPointVisible(!0))}),this.inputManager.addEventListener("pointerup",u=>{if(i=void 0,this.cameraManager.setOrbitPointVisible(!1),e){e=!1;return}u.button===Je.Left?l(u)?(h?.object?this.flyToObject(h.object):this.viewFitAll(),s=0,n=-1,r=-1):(this.selectedObject&&(this.selectedObject instanceof Nt?this.selectedObject.selected=!1:this.clearHighlight(),this.selectedObject=void 0),s=u.timestamp,n=u.x,r=u.y,h?.object&&!d&&this.handleClickObject(h.object)):(u.button,Je.Right)})}setDefaultBackground(){this.sceneManager.renderer.setClearColor(11119017,1),this.sceneManager.setBackground(null),this.sceneManager.setEnvironmentFromData()}handleAnchorPoint(e){const i=new p.Vector3;this.selectedObject?new p.Box3().setFromObject(this.selectedObject).getCenter(i):e&&e.point?i.copy(e.point):this.getBBox().getCenter(i),this.cameraManager.setOrbitPoint(i),this.cameraManager.update(0)}handleClickObject(e){if(!this.enableSelection)return;const i=r=>!r.userData.modelId&&r.parent?i(r.parent):r.userData.modelId,s=i(e);this.loadedModels.find(r=>r.modelId===s)?.highlightObject(e),this.selectedObject=e,this.enableRender()}is3d(){return!0}async loadLocalModel(e,i,s,n){return this.loadModelInternal(i,n,!0,e,s)}async loadModel(e,i){return this.loadModelInternal(e,i)}async loadModelInternal(e,i,s,n,r){this.spinner.increaseJobCount();const a=e.modelId||e.src,o=We.t("ProgressBar.Loading"),l=f=>{this.progressBar?.updateProgress(a,o,f),i?.(new ProgressEvent("LoadProgress",{loaded:f,total:100}))};let h=!1;const d=(f,m,b)=>{let y=f.loaded*100/f.total;y=y*(b-m)/100+m,y>b&&(h||(P.warn("[Progress] Invalid ProgressEvent:",f),h=!0),y=b),this.progressBar?.updateProgress(a,o,y),i?.(new ProgressEvent("LoadProgress",{loaded:y,total:100}))},u=f=>d(f,0,50);this.progressBar?.addProgressItem(a),l(0);try{let f;if(s?(this.loaderHelper.setLoadManager(r),f=await this.loaderHelper.loadLocalModel(n,e.src,i)):f=await this.loaderHelper.loadModel(e.src,e.fileFormat,u),e.matrix&&e.matrix.length===16){const x=new p.Matrix4;x.elements=e.matrix,f.applyMatrix4(x)}const m=this.getUniqueModelId(e.modelId||e.src),b=new kr({modelId:m,object:f});this.addModel(b),l(90);const y=b.getBBox();this.loadedModels.length===1&&setTimeout(()=>this.goToHomeView(),0);const w=new p.Vector3;y.getCenter(w),this.cameraManager.setOrbitPoint(w),l(100),this.progressBar?.delayRemoveProgressItem(a),this.dispatchEvent(le.ModelLoad)}catch(f){throw this.progressBar?.removeProgressItem(a),P.error("[Viewer3d] Failed to load model '"+e.src+"'",f),f}finally{this.spinner.decreaseJobCount()}}setDistanceCullingFactor(e){this.distanceCullingFactor=e}getDistanceCullingFactor(){return this.distanceCullingFactor}setObjectOpacity(e,i){this.loadedModels.forEach(s=>s.setObjectOpacity(e,i)),this.enableRender()}setOtherObjectsOpacity(e,i){this.loadedModels.forEach(s=>{s.setOpacity(i),s.clearObjectOpacity(e)}),this.enableRender()}clearObjectOpacity(e){this.loadedModels.forEach(i=>i.clearObjectOpacity(e)),this.enableRender()}setModelOpacity(e){this.loadedModels.find(s=>s.modelId===e)?.setOpacity(),this.enableRender()}clearModelOpacity(e){this.loadedModels.find(s=>s.modelId===e)?.clearOpacity(),this.enableRender()}setModelsOpacity(e){this.loadedModels.forEach(i=>i.setOpacity(e)),this.enableRender()}clearModelsOpacity(){this.loadedModels.forEach(e=>e.clearOpacity()),this.enableRender()}setObjectVisible(e,i){this.loadedModels.forEach(s=>s.setObjectVisible(e,i)),this.enableRender()}hideOtherObjects(e){this.loadedModels.forEach(i=>{i.setVisible(!1),i.setObjectVisible(e,!0)}),this.enableRender()}setModelVisible(e,i){this.loadedModels.find(n=>n.modelId===e)?.setVisible(i),this.enableRender()}setModelsVisible(e){this.loadedModels.forEach(i=>i.setVisible(e)),this.enableRender()}enableModelOutline(e,i){this.loadedModels.find(n=>n.modelId===e)?.enableOutline(i),this.enableRender()}enableModelsOutline(e){this.loadedModels.forEach(i=>i.enableOutline(e)),this.enableRender()}setObjectHighlight(e){this.loadedModels.forEach(i=>i.highlightObject(e)),this.enableRender()}clearHighlight(){this.loadedModels.forEach(e=>e.clearHighlight()),this.enableRender()}setDoubleSidedMaterials(){this.loadedModels.forEach(e=>e.setDoubleSidedMaterials()),this.enableRender()}revertDoubleSidedMaterials(){this.loadedModels.forEach(e=>e.revertDoubleSidedMaterials()),this.enableRender()}clearSelection(){this.selectedObject instanceof Nt&&(this.selectedObject.selected=!1),this.selectedObject=void 0,this.clearHighlight()}get enableSelection(){return this._enableSelection}set enableSelection(e){e||this.clearSelection(),this._enableSelection=e}hasVisibleObject(){for(const e of this.loadedModels)if(e.hasVisibleObject())return!0;return!1}hasInvisibleObject(){for(const e of this.loadedModels)if(e.hasInvisibleObject())return!0;return!1}enableSsao(e){this.effect.enabled=e,this.effect.renderPassEnabled=e,this.effect.ssaaPassEnabled=e,this.effect.ssaoPassEnabled=e}getSsaoEnabled(){return this.effect.enabled&&this.effect.ssaoPassEnabled}async setEnvironmentData(e){await this.sceneManager.setEnvironmentFromData(e),this.enableRender()}async setEnvironment(e){await this.sceneManager.setEnvironment(e),this.enableRender()}showVertexNormals(e,i=.1){this.effect.showVertexNormals(e,i)}getLights(){return{sun:this.sceneManager.directionalLight,ambient:this.sceneManager.ambientLight,hemisphere:this.sceneManager.hemisphereLight}}debugLights(e){this.sceneManager.debugLights(e)}setModelClipPlanes(e,i){this.loadedModels.find(n=>n.modelId===""+e)?.setClipPlanes(i),this.enableRender()}setGlobalClipPlanes(e){const i=e.length>0;this.sceneManager.enableClipping(i),this.sceneManager.setClipPlanes(e)}}function mo(c){return Object.assign(Object.assign({},{asset:"",version:"",datetime:"",root:"",modelSize:0,generateTool:""}),c)}function go(c){return Object.assign(Object.assign({},{elementCount:0,batchElementCount:0,instanceElementCount:0,batchCount:0,instanceCount:0,tileCount:0,userDataCount:0,materialCount:0,meshVertexCount:0,meshFaceCount:0,textureCount:0,texturePixels:0}),c)}function Lu(c){const t={transform:new p.Matrix4,boundingVolume:new p.Box3};return Object.assign(Object.assign({},t),c)}class Ru{constructor(t){g(this,"url");g(this,"metadata");g(this,"statistics");g(this,"view");this.url=t,this.metadata=mo(),this.statistics=go(),this.view=Lu()}async parse(){return await fetch(this.url).then(t=>t.ok?t.json():(P.error('[BimTiles] Failed to request "'+this.url+'", status '+t.status+" : "+t.statusText),Promise.reject(!1))).then(t=>(this.metadata=mo(t.metadata),this.statistics=go(t.statistics),t.view.transform&&t.view.transform.length===16&&this.view.transform.fromArray(t.view.transform),t.view.boundingVolume&&t.view.boundingVolume.length===6&&this.view.boundingVolume.setFromArray(t.view.boundingVolume),Promise.resolve(!0)))}getMetadata(){return this.metadata}getStatistics(){return this.statistics}getView(){return this.view}}let Fu=0;class zu extends Mn{constructor(e,i){super(e);g(this,"name");g(this,"pickUsageScene");g(this,"effect");g(this,"loadedModels");g(this,"selectedObject");g(this,"enableHoverEffect");if(this.name=$e.BimTilesViewer,this.loadedModels=[],this.enableHoverEffect=!1,this.effect=new yl(this),this.pickUsageScene=new p.Scene,this.sceneManager.enableLights(!0),i)this.setHomeView(i),this.cameraManager.flyToViewpoint(i);else{const s=new p.Vector3(100,50,100),n=new p.Vector3(0,0,0),r={eye:s,look:n};this.cameraManager.flyToViewpoint(r)}this.cameraManager.setProjection(bt.Perspective),this.cameraManager.setNavigationMode(lt.Orbit),this.setupDefaultEvents(),this.setDefaultBackground(),this.addEventListener(le.BeforeRender,()=>{this.update3dTiles()})}setupDefaultEvents(){let e=!1,i,s=0,n=0,r=0;const a=300,o=u=>n===-1||r===-1?!1:Math.abs(u.x-n)<5&&Math.abs(u.y-r)<5,l=u=>{const f=u.timestamp-s;return!!(u.button===Je.Left&&f<a&&o(u))};let h,d=!1;this.inputManager.addEventListener("pointerdown",u=>{e=!1,i=u.button,this.renderImmediately();const f=new p.Vector2(u.x,u.y);if(h=this.pickManager.pick(f,this.pickUsageScene),d=!!this.selectedObject&&h?.tilesetId===this.selectedObject?.tilesetId&&h?.userId===this.selectedObject?.userId,u.button===Je.Left){let m=this.pickUsageScene;if(h){const y=this.loadedModels.find(S=>S.modelId===""+h?.tilesetId);if(y){const S=y.getObjectByUserId(h.userId);S&&(m=S)}}const b=this.pickManager.pickObject(f,[m]);this.handleAnchorPoint(b)}}),this.inputManager.addEventListener("pointermove",u=>{if(i!==void 0)e=!o(u),i===Je.Left&&this.cameraManager.enableRotate&&this.cameraManager.setOrbitPointVisible(!0);else if(this.enableHoverEffect){const f=new p.Vector2(u.x,u.y),m=this.pickManager.pick(f,this.pickUsageScene),b=this.getHoveredObject();m?(!b||b.tilesetId!==m.tilesetId||b.userId!==m.userId)&&this.setObjectHoveredByUserId(m.tilesetId,m.userId,!0):b&&this.clearHovered()}this.handleMouseMove(u)}),this.inputManager.addEventListener("pointerup",u=>{if(i=void 0,this.cameraManager.setOrbitPointVisible(!1),e){e=!1;return}u.button===Je.Left?l(u)?(h?this.flyToUserId(h.tilesetId,h.userId):this.viewFitAll(),s=0,n=-1,r=-1):(this.selectedObject&&(this.clearHighlight(),this.selectedObject=void 0),s=u.timestamp,n=u.x,r=u.y,h&&!d&&this.handleClickObject(h)):(u.button,Je.Right)})}setDefaultBackground(){this.sceneManager.setBackground(new p.Color(11119017)),this.sceneManager.setEnvironmentFromData()}renderImmediately(){const{renderer:e,scene:i,camera:s}=this;!e||!i||!s||e.render(i,s)}handleAnchorPoint(e){const i=new p.Vector3;this.selectedObject?this.getBoxByUserId(this.selectedObject.tilesetId,this.selectedObject.userId)?.getCenter(i):e&&e.point?i.copy(e.point):this.getBBox().getCenter(i),this.cameraManager.setOrbitPoint(i),this.cameraManager.update(0)}handleClickObject(e){if(!this.enableSelection)return;const i=this.loadedModels.find(s=>s.modelId===""+e.tilesetId);i&&(i?.setObjectHighlightedByUserIds([e.userId],!0),this.selectedObject=e),this.enableRender()}is3d(){return!0}setModelOpacity(e,i){this.loadedModels.find(n=>n.modelId===e)?.setOpacity(i),this.enableRender()}clearModelOpacity(e){this.loadedModels.find(s=>s.modelId===e)?.clearOpacity(),this.enableRender()}setModelsOpacity(e){this.loadedModels.forEach(i=>i.setOpacity(e)),this.enableRender()}clearModelsOpacity(){this.loadedModels.forEach(e=>e.clearOpacity()),this.enableRender()}enableModelOutline(e,i){P.warn("Outline for bimtiles is not implemented yet.")}enableModelsOutline(e){P.warn("Outline for bimtiles is not implemented yet.")}setModelVisible(e,i){this.loadedModels.find(n=>n.modelId===e)?.setVisible(i),this.enableRender()}setModelsVisible(e){this.loadedModels.forEach(i=>i.setVisible(e)),this.enableRender()}clearHighlight(){this.loadedModels.forEach(e=>e.clearHighlight()),this.enableRender()}setDoubleSidedMaterials(){this.loadedModels.forEach(e=>e.setDoubleSidedMaterials()),this.enableRender()}revertDoubleSidedMaterials(){this.loadedModels.forEach(e=>e.revertDoubleSidedMaterials()),this.enableRender()}clearSelection(){this.selectedObject instanceof Nt&&(this.selectedObject.selected=!1),this.selectedObject=void 0,this.clearHighlight()}get enableSelection(){return this._enableSelection}set enableSelection(e){e||this.clearSelection(),this._enableSelection=e}flyToUserId(e,i){const s=this.getBoxByUserId(e,i);s&&this.cameraManager.flyToBox(s)}getBoxByUserId(e,i){const s=this.loadedModels.find(n=>n.modelId===""+e);if(s)return s.getBBoxByUserId(i)}handleMouseMove(e){}update3dTiles(){if(!this.camera)return;const e=this.loadedModels.filter(i=>!!i.tilesRenderer);e.length!==0&&(this.camera.updateMatrixWorld(),e.forEach(i=>{i.tilesRenderer.update()}))}async loadModel(e,i){if(e.src.length===0)return Promise.reject();const s=new Ru(e.src);if(!await s.parse())return Promise.reject();let r=e.src.replace(/\/[^\\/]*\/?$/,"/");r=new URL(r,window.location.href).toString(),this.spinner.increaseJobCount();try{const a=s.getView().boundingVolume.clone();a.applyMatrix4(s.getView().transform);const o=new Lr({modelId:""+Fu++,bbox:a},r,s),l=o.getTilesRenderer(),h=l.group;if(l.onBeforeParseTile=()=>{this.spinner.increaseJobCount()},l.onLoadModel=d=>{d.traverse(u=>{!et&&u.matrixAutoUpdate&&(u.matrixAutoUpdate=et,u.updateMatrix()),u.isMesh&&(u.castShadow=!0,u.receiveShadow=!0),u.geometry&&u.layers.enableAll()}),this.enableRender(),setTimeout(()=>this.spinner.decreaseJobCount(),100)},l.setCamera(this.camera),l.setResolutionFromRenderer(this.camera,this.renderer),l.update(),h){h.applyMatrix4(s.getView().transform),o.pickUsageGroup.applyMatrix4(s.getView().transform),this.pickUsageScene.add(o.pickUsageGroup),this.addModel(o),this.cameraManager.adjustCameraByBBox(a);const d=new p.Vector3;return a.getCenter(d),this.cameraManager.setOrbitPoint(d),this.loadedModels.length===1&&this.goToHomeView(),this.dispatchEvent(le.ModelLoad),Promise.resolve()}return Promise.reject()}finally{this.spinner.decreaseJobCount()}}setObjectHighlightedByUserIds(e,i,s){this.loadedModels.find(r=>r.modelId===""+e)?.setObjectHighlightedByUserIds(i,s),this.enableRender()}setObjectOpacityByUserIds(e,i,s){this.loadedModels.find(r=>r.modelId===""+e)?.setObjectOpacityByUserIds(i,s),this.enableRender()}setOtherObjectOpacityByUserIds(e,i,s){this.loadedModels.forEach(a=>{a.setOpacity(s)});const n=""+e;this.loadedModels.find(a=>a.modelId===n)?.clearObjectOpacityByUserIds(i),this.enableRender()}setObjectVisibleByUserIds(e,i,s){this.loadedModels.find(r=>r.modelId===""+e)?.setObjectVisibleByUserIds(i,s),this.enableRender()}setOtherObjectVisibleByUserIds(e,i,s){this.loadedModels.forEach(r=>{r.setVisible(s)}),this.loadedModels.find(r=>r.modelId===""+e)?.setObjectVisibleByUserIds(i,!s),this.enableRender()}setObjectHoveredByUserId(e,i,s){if(!this.enableHoverEffect)return;this.clearHovered(),this.loadedModels.find(r=>r.modelId===""+e)?.setObjectHoveredByUserId(i,s),this.enableRender()}getHoveredObject(){for(const e of this.loadedModels){const i=e.getHoveredObject();if(i)return i}}clearHovered(){this.loadedModels.forEach(e=>e.clearHovered()),this.enableRender()}hasVisibleObject(){for(const e of this.loadedModels)if(e.hasVisibleObject())return!0;return!1}hasInvisibleObject(){for(const e of this.loadedModels)if(e.hasInvisibleObject())return!0;return!1}setModelClipPlanes(e,i){this.loadedModels.find(n=>n.modelId===""+e)?.setClipPlanes(i),this.enableRender()}setGlobalClipPlanes(e){const i=e.length>0;this.sceneManager.enableClipping(!i),this.sceneManager.setClipPlanes(e)}showVertexNormals(e,i=.1){this.effect.showVertexNormals(e,i)}getLights(){return{sun:this.sceneManager.directionalLight,ambient:this.sceneManager.ambientLight,hemisphere:this.sceneManager.hemisphereLight}}debugLights(e){this.sceneManager.debugLights(e)}pickObjects(e,i){const s=this.pickManager.pick(e,this.pickUsageScene);let n=this.pickUsageScene;if(s){const a=this.loadedModels.find(o=>o.modelId===""+s?.tilesetId);if(a){const o=a.getObjectByUserId(s.userId);o&&(n=o)}}let r=this.pickManager.pickObjects(e,[n],i);return r&&this.renderer.clippingPlanes.length>0&&(r=r.filter(a=>this.renderer.clippingPlanes.every(function(o){return o.distanceToPoint(a.point)>0}))),r}getErrorTarget(){return this.loadedModels.length>0?this.loadedModels[0].getTilesRenderer().errorTarget:8}setErrorTarget(e){this.loadedModels.forEach(i=>{i.getTilesRenderer().errorTarget=e})}}class Vu extends Ht{constructor(e,i){if(!i.id)throw new Error("[Plugin] Missing plugin id!");super();g(this,"id");g(this,"viewer");this.id=i.id,this.viewer=e,e.addPlugin(this)}destroy(){this.viewer.removePlugin(this)}}$.install({THREE:p});class ju extends ${constructor(e,i){super(e,i);g(this,"minZoom");g(this,"draggingSmoothTime");g(this,"dollySpeedBackup");g(this,"azimuthRotateSpeedBackup");g(this,"polarRotateSpeedBackup");g(this,"truckSpeedBackup");g(this,"onKeyDown");g(this,"onKeyUp");g(this,"keyTruckSpeed");g(this,"keys");this.minZoom=0,this.draggingSmoothTime=0,this.keyTruckSpeed=7,this.keys={left:"ArrowLeft",up:"ArrowUp",right:"ArrowRight",bottom:"ArrowDown"},this.onKeyDown=s=>{if(this.enabled){switch(s.code){case this.keys.up:s.ctrlKey||s.metaKey||s.shiftKey?(this._rotateInternal(0,1),this._isUserControllingRotate=!0):(this._truckInternal(0,this.keyTruckSpeed,!1),this._isUserControllingTruck=!0);break;case this.keys.bottom:s.ctrlKey||s.metaKey||s.shiftKey?(this._rotateInternal(0,-1),this._isUserControllingRotate=!0):(this._truckInternal(0,-this.keyTruckSpeed,!1),this._isUserControllingTruck=!0);break;case this.keys.left:s.ctrlKey||s.metaKey||s.shiftKey?(this._rotateInternal(1,0),this._isUserControllingRotate=!0):(this._truckInternal(this.keyTruckSpeed,0,!1),this._isUserControllingTruck=!0);break;case this.keys.right:s.ctrlKey||s.metaKey||s.shiftKey?(this._rotateInternal(-1,0),this._isUserControllingRotate=!0):(this._truckInternal(-this.keyTruckSpeed,0,!1),this._isUserControllingTruck=!0);break}this.dispatchEvent({type:"control"})}},this.onKeyUp=s=>{this.dispatchEvent({type:"controlend"})},this._getClientRect(this._elementRect),this.dollySpeedBackup=this.dollySpeed,this.azimuthRotateSpeedBackup=this.azimuthRotateSpeed,this.polarRotateSpeedBackup=this.polarRotateSpeed,this.truckSpeedBackup=this.truckSpeed}get enableZoom(){return!!this.dollySpeed}set enableZoom(e){e?this.dollySpeed=this.dollySpeedBackup:(this.dollySpeedBackup=this.dollySpeed,this.dollySpeed=0)}get enableRotate(){return!!this.azimuthRotateSpeed||!!this.polarRotateSpeed}set enableRotate(e){e?(this.azimuthRotateSpeed=this.azimuthRotateSpeedBackup,this.polarRotateSpeed=this.polarRotateSpeedBackup):(this.azimuthRotateSpeedBackup=this.azimuthRotateSpeed,this.polarRotateSpeedBackup=this.polarRotateSpeed,this.azimuthRotateSpeed=0,this.polarRotateSpeed=0)}get enableTruck(){return!!this.truckSpeed}set enableTruck(e){e?this.truckSpeed=this.truckSpeedBackup:(this.truckSpeedBackup=this.truckSpeed,this.truckSpeed=0)}listenToKeyEvents(){this._domElement?.addEventListener("keydown",this.onKeyDown),this._domElement?.addEventListener("keyup",this.onKeyUp)}stopListenToKeyEvents(){this._domElement?.removeEventListener("keydown",this.onKeyDown),this._domElement?.removeEventListener("keyup",this.onKeyUp)}dispose(){super.dispose(),this.stopListenToKeyEvents()}}var xl=(c=>(c[c.Browser=0]="Browser",c[c.Browserless=1]="Browserless",c[c.Headless=2]="Headless",c))(xl||{});class Uu{constructor(t,e,i){g(this,"containerOrCanvas");g(this,"glContext");g(this,"camera");g(this,"scene");g(this,"renderer");g(this,"renderTarget");g(this,"controls");g(this,"selectedObject");g(this,"loadedModels");g(this,"pmremGenerator");g(this,"clock");g(this,"viewerMode");g(this,"raycaster");g(this,"savedMaterialsForOpacity");g(this,"jobCount");g(this,"bbox");g(this,"outlineMaterial");g(this,"outlineRoot");g(this,"transparentObjectIds");g(this,"requestAnimationFrameHandle");g(this,"applyOptionsAndAddToScene");g(this,"getMeshes");if(this.scene=this.initScene(),this.selectedObject=void 0,this.loadedModels=[],this.clock=new p.Clock,this.viewerMode=0,this.raycaster=new p.Raycaster,this.savedMaterialsForOpacity=[],this.jobCount=0,this.bbox=new p.Box3,this.outlineMaterial=new p.LineBasicMaterial({color:1118481}),this.outlineRoot=new p.Group,this.transparentObjectIds=[],this.applyOptionsAndAddToScene=async(s,n,r,a)=>{if(P.info("[Viewer] '"+s+"' is loaded, adding to scene..."),r.matrix&&r.matrix.length===16){const u=new p.Matrix4;u.elements=r.matrix,n.applyMatrix4(u)}n.traverse(u=>{u.geometry&&u.layers.enableAll(),u instanceof p.Light&&(u.visible=!1)});let o;r.edges&&(o=await J.createOutlines(n,void 0,a));let l=r.modelId||r.src;const h=u=>!!this.loadedModels.find(f=>f.modelId===u);if(h(l)){let u=1;for(;h(l+"_"+u);)u++;l=l+"_"+u,P.warn("[Viewer] Model '"+l+"' is loaded more than once!")}const d={modelId:l,object:n,edges:o};this.addModel(d)},this.getMeshes=s=>{const n=[];return s instanceof p.Mesh?n.push(s):s.traverseVisible(r=>{r instanceof p.Mesh&&n.push(r)}),n},this.containerOrCanvas=t,e&&(this.viewerMode=e),this.glContext=i,this.viewerMode===1&&!(!(t instanceof HTMLDivElement)&&i))throw new Error("[Viewer] Parameters don't match Browserless viewerMode !");this.increaseJobCount(),this.init(),this.decreaseJobCount(),P.info("[Viewer] Initialized"),this.animate()}init(){this.initRenderer(),this.initCamera(),this.initControls(),this.initLights(),this.initPointerEvents(),this.scene.add(this.outlineRoot)}initScene(){const t=new p.Scene;return t.background=new p.Color(7112861),t.matrixAutoUpdate=!0,t}isBrowserlessMode(){return this.viewerMode===1}isBrowserMode(){return this.viewerMode===0}initRenderer(){const t={antialias:!0,preserveDrawingBuffer:!0},e=this.isBrowserlessMode();e&&Object.assign(t,{canvas:this.containerOrCanvas,context:this.glContext});let i;try{i=new p.WebGLRenderer(t)}catch(s){if(e||!t.antialias)throw s;i=new p.WebGLRenderer({canvas:this.containerOrCanvas}),P.warn("WebGL context created with fallback settings (antialias disabled).")}if(e){const s=this.containerOrCanvas.width,n=this.containerOrCanvas.height;P.info("[Viewer] Render target size: "+s+" x "+n),this.renderTarget=new p.WebGLRenderTarget(s,n,{minFilter:p.LinearFilter,magFilter:p.NearestFilter,format:p.RGBAFormat,type:p.UnsignedByteType}),i.setRenderTarget(this.renderTarget)}else{const s=this.containerOrCanvas.clientWidth,n=this.containerOrCanvas.clientHeight;this.containerOrCanvas.append(i.domElement),i.setPixelRatio(window.devicePixelRatio),i.setSize(s,n)}i.outputColorSpace=p.SRGBColorSpace,i.toneMappingExposure=1,i.setClearColor(11119017,1),i.shadowMap.enabled=!0,i.shadowMap.type=p.PCFSoftShadowMap,this.renderer=i,e||(this.pmremGenerator=new p.PMREMGenerator(i),this.pmremGenerator.compileEquirectangularShader(),this.setEnvironmentFromDataArray())}initCamera(){if(!this.scene)return;const t=this.containerOrCanvas.clientWidth||this.containerOrCanvas.width||0,e=this.containerOrCanvas.clientHeight||this.containerOrCanvas.height||0;let i=1;t&&e&&(i=t/e),this.camera=new p.PerspectiveCamera(68,i,.05,1e4),this.camera.position.set(10,10,10),this.camera.lookAt(0,0,0),this.scene.add(this.camera)}initControls(){if(!this.renderer)return;const t=this.camera;if(!t)return;const e=new ju(t,this.renderer.domElement);e.smoothTime=.05,e.enabled=!0,e.keyTruckSpeed=10,e.keys={left:"KeyD",up:"KeyE",right:"KeyA",bottom:"KeyQ"},e.update(0),this.controls=e,e.addEventListener("update",()=>{!this.isBrowserMode()&&this.renderer&&this.renderer.render(this.scene,t)})}initLights(){if(!this.scene)return;const t=16777215,e=.3,i=new p.DirectionalLight(t,e);i.position.set(-2,2,4);const s=new p.AmbientLight(3158064),n=new p.HemisphereLight(t,14540253,3);n.position.set(0,300,0),this.scene.add(i),this.scene.add(s),this.scene.add(n)}initPointerEvents(){if(!this.renderer||!this.camera||!this.controls)return;let t=!1,e=!1,i=-1,s=-1;this.renderer.domElement.addEventListener("pointerdown",n=>{i=n.x,s=n.y,t=!1}),this.renderer.domElement.addEventListener("pointermove",n=>{i>=0&&s>=0&&(Math.abs(n.x-i)>5||Math.abs(n.y-s)>5)&&(t=!0)}),this.renderer.domElement.addEventListener("pointerup",()=>{e&&setTimeout(()=>{e=!1},200),i=-1,s=-1}),this.renderer.domElement.addEventListener("dblclick",n=>{e=!0,t||(this.handleMouseClick(n),this.flyToSelectedObject())})}animate(){this.isBrowserMode()&&requestAnimationFrame(this.animate.bind(this));const t=this.clock.getDelta();this.controls&&this.controls.update(t),this.scene&&this.camera&&this.renderer?.render(this.scene,this.camera)}destroy(){this.camera=void 0,this.scene&&this.scene.clear(),this.requestAnimationFrameHandle&&(cancelAnimationFrame(this.requestAnimationFrameHandle),this.requestAnimationFrameHandle=void 0),this.renderer&&(this.containerOrCanvas.removeChild(this.renderer.domElement),this.renderer.clear(),this.renderer.dispose(),this.renderer=void 0),this.controls&&(this.controls.dispose(),this.controls=void 0),this.renderTarget&&(this.renderTarget.dispose(),this.renderTarget=void 0),this.raycaster=void 0,this.selectedObject=void 0,this.savedMaterialsForOpacity=void 0,this.loadedModels=[]}async loadLocalModel(t,e,i){const n=await new Vt().loadLocalModel(t,e.src,i);return n?(await this.applyOptionsAndAddToScene(t,n,e),Promise.resolve()):Promise.reject()}async loadModel(t,e){this.increaseJobCount();const s=await new Vt().loadModel(t.src,t.fileFormat,e);return s?(await this.applyOptionsAndAddToScene(t.src,s,t),Promise.resolve()):Promise.reject()}parseGltf(t,e,i,s){this.increaseJobCount(),new Vt().parseGltf(t,e.src,n=>{this.applyOptionsAndAddToScene(e.src,n,e),i&&i(n)},n=>{s&&s(n)})}addModel(t){if(!this.scene||!this.renderer)return;this.increaseJobCount();const e=new p.Box3().setFromObject(t.object);t.bbox||(t.bbox=e),this.scene.add(t.object),this.loadedModels.push(t),this.computeBoundingBox(),this.loadedModels.length===1&&(this.tryAdjustCameraNearAndFar(),this.goToHomeView()),this.renderer.shadowMap.needsUpdate=!0,P.info("[Viewer] Added '"+t.modelId+"' to scene"),this.decreaseJobCount()}addOrRemoveObjectOpacity(t=!0,e=.3,i,s){if(this.savedMaterialsForOpacity||(this.savedMaterialsForOpacity=[]),!this.scene)return;const n=this.scene,r=[];this.loadedModels.forEach(a=>{const o=a.object.id;if(t){this.savedMaterialsForOpacity&&this.savedMaterialsForOpacity.length>0&&J.revertObjectOpacityById(n,o,this.savedMaterialsForOpacity);const l=J.setObjectOpacityById(n,o,e,i,s);r.push(...l)}else this.savedMaterialsForOpacity&&J.revertObjectOpacityById(n,o,this.savedMaterialsForOpacity)}),t?this.savedMaterialsForOpacity=r:this.savedMaterialsForOpacity=[]}hasTransparentObject(){return!!(this.savedMaterialsForOpacity&&this.savedMaterialsForOpacity.length>0)}getIntersections(t){if(!this.raycaster||!this.camera||!this.scene)return[];let e=new p.Vector2;t&&(e=Oe.getScreenCoordinateByEvent(t,this.containerOrCanvas));const i=Oe.screen2Ndc(e,this.camera,this.containerOrCanvas);this.raycaster.setFromCamera(i,this.camera);const s=[];return this.loadedModels.forEach(n=>{const r=n.object;r&&r.visible&&s.push(r)}),this.raycaster.intersectObjects(s,!0)||[]}handleMouseClick(t){this.raycaster&&this.raycaster.layers.set(Ut);const i=this.getIntersections(t).find(n=>{const r=n.object;return r.visible&&r instanceof p.Mesh});let s=i&&i.object||void 0;s&&this.selectedObject&&this.selectedObject.id===s.id&&(s=void 0),s?this.selectObject(s):this.clearSelection()}selectObject(t){if(this.selectedObject){const i=this.selectedObject.userData;if(i.originalMaterial){if(this.selectedObject.material){const s=this.selectedObject.material;Array.isArray(s)?s.forEach(n=>n.dispose()):s instanceof p.Material&&s.dispose()}this.selectedObject.material=i.originalMaterial,delete i.originalMaterial}this.selectedObject=void 0}if(!this.scene||!t)return;const e=be.clonedHighlightMaterials(t);e&&(this.selectedObject=t,this.selectedObject.userData.originalMaterial=this.selectedObject.material,this.selectedObject.material=e)}clearSelection(){this.selectObject()}flyToObjects(t){if(!t||t.length===0||!this.camera)return;const e=new p.Box3;t.forEach(n=>{const r=_t.getBoundingBox(n);e.union(r)});const i=new p.Sphere;e.getBoundingSphere(i),this.controls?.fitToSphere(i,!0)}flyToObject(t){this.flyToObjects([t])}flyToSelectedObject(){this.selectedObject&&this.flyToObject(this.selectedObject)}flyTo(t,e,i){const s=this.camera,n=this.controls;if(!s||!n)return;t=Array.isArray(t)?new p.Vector3(t[0],t[1],t[2]):t,e=Array.isArray(e)?new p.Vector3(e[0],e[1],e[2]):e;const r=t,a=e;P.info("[Viewer] flyTo: ",j.vectorToString(r)),n.setPosition(r.x,r.y,r.z),n.setTarget(a.x,a.y,a.z),this.isBrowserMode()||this.renderer?.render(this.scene,s),i&&i()}goToHomeView(){const t=new p.Sphere;this.bbox.getBoundingSphere(t),this.controls?.fitToSphere(t,!0)}setEnvironmentFromDataArray(t){ms.createEnvTextureFromDataArray(this.pmremGenerator,t).then(e=>{this.scene.environment=e,this.isBrowserMode()||this.animate()})}tryAdjustCameraNearAndFar(){const t=this.camera;if(!this.scene||!t)return;const e=this.bbox,i=t.near,s=t.far,n=e.max.x-e.min.x,r=e.max.y-e.min.y,a=e.max.z-e.min.z,o=Math.max(n,r,a),l=5,h=o/l,d=o*l;if(i>h||s<d){const u=f=>j.numberToString(f);P.info("[Viewer] BBox's longest side is: "+u(o)),i>h&&(P.warn("[Viewer] camera.near("+u(i)+") shouldn't bigger than "+u(h)+", will change it!"),t.near=h),s<d&&(P.warn("[Viewer] camera.far("+u(s)+") shouldn't smaller than "+u(d)+", will change it!"),t.far=d)}t.updateProjectionMatrix()}isolateObjects(t){const e=this.transparentObjectIds.length>0?void 0:this.transparentObjectIds,i=this.transparentObjectIds.length>0?this.transparentObjectIds:void 0,s=new p.MeshBasicMaterial({color:16777215,transparent:!0,opacity:.1});this.loadedModels.forEach(r=>{const a=r.object.id;J.applyMaterialToObjectById(this.scene,a,s,i,e)}),this.outlineRoot.clear();let n=[];if(t.forEach(r=>{const a=r.modelId;let l=this.loadedModels.find(h=>h.modelId===a)?.object;l||(P.warn("[Viewer] The ModelId of "+a+" has no corresponding model."),l=this.scene),l.traverse(h=>{if(jr.includes(r.id,jr.get(h.userData,"UniqueId"))){const d=this.getMeshes(h);n=n.concat(d)}})}),n.length>0){n.forEach(a=>{const o=J.createOutline(a.geometry,this.outlineMaterial);o.applyMatrix4(a.matrixWorld),this.outlineRoot.add(o),o.updateWorldMatrix(!0,!1)});const r=n.map(a=>a.id);this.loadedModels.forEach(a=>{const o=a.object.id;J.revertAppliedMaterialToObjectById(this.scene,o,r)}),this.transparentObjectIds=r,this.flyToObjects(n)}else P.warn("[Viewer] No object found with uniqueIds: "+t.map(r=>r.id));this.isBrowserMode()||this.animate()}increaseJobCount(){++this.jobCount}decreaseJobCount(){--this.jobCount}computeBoundingBox(){const t=new p.Box3;return this.loadedModels.forEach(e=>{e.bbox&&!e.bbox.isEmpty()&&t.union(e.bbox)}),this.bbox=t,t}getContext(){return this.renderer?.getContext()}getCameraDirection(){const t=new p.Vector3;return this.camera?.getWorldDirection(t),{x:t.x,y:t.y,z:t.z}}setFov(t){this.camera&&(this.camera.fov=t,this.camera.updateProjectionMatrix())}}const bl="1.0.0",wl="VERSION",vl=()=>window.localStorage.getItem(wl),Ml=()=>{window.localStorage.setItem(wl,bl)},Nu=()=>vl()!==bl?(Ml(),!0):!1;Object.defineProperty(exports,"Mesh",{enumerable:!0,get:()=>L.Mesh});exports.BaseDxfCompareHelper=ml;exports.BaseViewer=Mn;exports.BimTilesModel=Lr;exports.BimTilesRenderer=el;exports.BimTilesViewer=zu;exports.BinaryReader=vs;exports.BoxSelectHelper=xn;exports.ByBlock=gs;exports.ByLayer=Br;exports.CSS2DObjectUtils=Rh;exports.CameraProjection=bt;exports.CancelablePromise=kh;exports.CanvasRender=bs;exports.ColorUtils=Li;exports.CommonUtils=j;exports.CompareDrawable=wt;exports.Container=Rr;exports.ControlsMode=lt;exports.CoordinateUtils=Oe;exports.DecimalPrecisionRange=Co;exports.DefaultCameraFar=ln;exports.DefaultCameraFov=Oo;exports.DefaultCameraNear=on;exports.DefaultLanguage=So;exports.DefaultOpacity=Ar;exports.DefaultViewer3dConfig=su;exports.DeviceUtils=Be;exports.Drawable=Nt;exports.DrawableList=ws;exports.DxfChangeType=Ve;exports.DxfCompare=ot;exports.DxfCompareHelper=Bu;exports.DxfCompareMarkupManager=vr;exports.DxfLoader=X;exports.DxfParser=Ho;exports.DxfRenderOrder=ye;exports.DxfUtils=Tt;exports.EdgeUtils=_o;exports.Event=Ht;exports.ExportUtils=yr;exports.FontManager=xt;exports.FpsUtils=Gh;exports.GenerateMeshBvhWorker=cl;exports.GeometryUtils=H;exports.GroundPlaneRenderOrder=pl;exports.HighlightColor=Pr;exports.HighlightColorRgba=zh;exports.IconfontClass=Vh;exports.IconfontClass2=jh;exports.InputManager=fl;exports.InstantiateHelper=du;exports.LayerForHitableObjects=Eo;exports.LayerForSelectableObjects=Ut;exports.LayerForSnapableObjects=je;exports.Line=fc;exports.LinePatternShaders=Vo;exports.LoadingHelper=Vt;exports.MaterialUtils=be;exports.MathUtils=z;exports.MatrixAutoUpdate=et;exports.MergeUtils=fe;exports.MeshBvhHelper=zr;exports.MobileTouchHelperDrawable=_u;exports.Model=vn;exports.Model2d=Ri;exports.Model3d=kr;exports.NestedCompareTypes=os;exports.OSnapHelper=Tu;exports.OSnapIconSize=Qh;exports.OSnapMarkerType=Et;exports.OSnapType=hl;exports.ObjectPixelSizeHelper=gu;exports.ObjectUtils=J;exports.Offset=ku;exports.OrbitControls=sl;exports.OutlineColorRgba=an;exports.PickMarkupHelper=Cu;exports.PlanControls=nl;exports.Plugin=Vu;exports.Points=gh;exports.PolygonUtils=$h;exports.ProgressBar=Fr;exports.RafHelper=ol;exports.SVGObjectUtils=ed;exports.SceneUtils=_t;exports.SectionUtils=zt;exports.ShaderChunk=Bh;exports.SimplifyUtils=Jh;exports.SnapDrawable=_e;exports.Spinner=tl;exports.TextSearchHelper=Mr;exports.TextureUtils=ms;exports.ThresholdAngleForEdge=Ir;exports.UnitConversionByMeter=xr;exports.UnitLabels=Io;exports.UnitScaleConversion=md;exports.UnitScaleToMeter=wr;exports.Units=Ke;exports.Viewer2d=Vr;exports.Viewer3d=Du;exports.Viewer3dLite=Uu;exports.Viewer3dUtils=sd;exports.ViewerEvent=le;exports.ViewerMode=xl;exports.ViewerName=$e;exports.Views=ko;exports.ZoomToRectHelper=ul;exports.bspline=Lo;exports.checkIsNewVersion=Nu;exports.cn=Ao;exports.createHatchPatternShaderMaterial=jo;exports.decodeDxfTextCharacterCodes=Ro;exports.decodeDxfTextMbcsCharacterCodes=zo;exports.decodeDxfTextUnicodeCodePoints=Fo;exports.en=Po;exports.getLengthValueByUnit=id;exports.getUnitStr=br;exports.getVersionFromLocalStorage=vl;exports.i18n=We;exports.log=P;exports.parseDxfMTextContent=ls;exports.parseDxfTextContent=cn;exports.round10=Do;exports.setIcon=Lh;exports.setLogLevel=To;exports.setVersionToLocalStorage=Ml;exports.showPrecisionValue=Fh;