iflow-engine-base 4.0.9 → 4.0.11

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.
@@ -4929,7 +4929,7 @@ var<${n}> ${e} : ${r};`}}const Ed=new l1,T$=new kR,_be=new Map([[Int8Array,["sin
4929
4929
  #include <tonemapping_fragment>
4930
4930
  #include <colorspace_fragment>
4931
4931
  #include <fog_fragment>
4932
- }`},v=new nr({name:S.name,uniforms:Oc.clone(S.uniforms),vertexShader:S.vertexShader,fragmentShader:S.fragmentShader,lights:!0,side:p,fog:m});v.uniforms.mirrorSampler.value=C.texture,v.uniforms.textureMatrix.value=T,v.uniforms.alpha.value=A,v.uniforms.time.value=a,v.uniforms.normalSampler.value=l,v.uniforms.sunColor.value=h,v.uniforms.waterColor.value=d,v.uniforms.sunDirection.value=c,v.uniforms.distortionScale.value=u,v.uniforms.eye.value=g,n.material=v,n.onBeforeRender=function(Y,k,j){if(y.setFromMatrixPosition(n.matrixWorld),w.setFromMatrixPosition(j.matrixWorld),M.extractRotation(n.matrixWorld),B.set(0,0,1),B.applyMatrix4(M),b.subVectors(y,w),b.dot(B)>0)return;b.reflect(B).negate(),b.add(y),M.extractRotation(j.matrixWorld),D.set(0,0,-1),D.applyMatrix4(M),D.add(w),P.subVectors(y,D),P.reflect(B).negate(),P.add(y),x.position.copy(b),x.up.set(0,1,0),x.up.applyMatrix4(M),x.up.reflect(B),x.lookAt(P),x.far=j.far,x.updateMatrixWorld(),x.projectionMatrix.copy(j.projectionMatrix),T.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),T.multiply(x.projectionMatrix),T.multiply(x.matrixWorldInverse),I.setFromNormalAndCoplanarPoint(B,y),I.applyMatrix4(x.matrixWorldInverse),Q.set(I.normal.x,I.normal.y,I.normal.z,I.constant);const R=x.projectionMatrix;F.x=(Math.sign(Q.x)+R.elements[8])/R.elements[0],F.y=(Math.sign(Q.y)+R.elements[9])/R.elements[5],F.z=-1,F.w=(1+R.elements[10])/R.elements[14],Q.multiplyScalar(2/Q.dot(F)),R.elements[2]=Q.x,R.elements[6]=Q.y,R.elements[10]=Q.z+1-r,R.elements[14]=Q.w,g.setFromMatrixPosition(j.matrixWorld);const U=Y.getRenderTarget(),O=Y.xr.enabled,V=Y.shadowMap.autoUpdate;n.visible=!1,Y.xr.enabled=!1,Y.shadowMap.autoUpdate=!1,Y.setRenderTarget(C),Y.state.buffers.depth.setMask(!0),Y.autoClear===!1&&Y.clear(),Y.render(k,x),n.visible=!0,Y.xr.enabled=O,Y.shadowMap.autoUpdate=V,Y.setRenderTarget(U);const $=j.viewport;$!==void 0&&Y.state.viewport($)}}}const NSe="0",YSe=0,GSe=!1;let LQt=class J6e{engine;currentId=NSe;groundGroup;groundMesh=null;isWaterAddon=!1;groundY=YSe;static DEFAULT_WATER_NORMALS="/texture/waternormals.jpg";groundList=[{id:"0",names:["无","無","None"]},{id:"1",names:["草地1","草地1","Grass 1"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass01.jpg"},{id:"2",names:["草地2","草地2","Grass 2"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass02.jpg"},{id:"3",names:["草地3","草地3","Grass 3"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass03.jpg"},{id:"4",names:["草地4","草地4","Grass 4"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass04.jpg"},{id:"5",names:["混凝土1","混凝土1","Concrete 1"],color:15790320,roughness:.85,metalness:.1,map:"/texture/ground/concrete01.jpg"},{id:"5",names:["混凝土1","混凝土1","Concrete 1"],color:15790320,roughness:.85,metalness:.1,map:"/texture/ground/concrete02.jpg"},{id:"6",names:["马路1","馬路1","Road 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/road01.jpg"},{id:"7",names:["马路2","馬路2","Road 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/road02.jpg"},{id:"8",names:["泥土1","泥土1","Soil 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/tiles01.jpg"},{id:"9",names:["泥土2","泥土2","Soil 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/tiles02.jpg"},{id:"10",names:["木板","木板","Wood Board"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/wood01.jpg"},{id:"11",names:["地砖1","地磚1","Floor Tile 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/z01.jpg"},{id:"12",names:["地砖2","地磚2","Floor Tile 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/z02.jpg"},{id:"13",names:["湖面","湖面","Lake Surface"],water:!0,waterColor:5929582,distortionScale:2.5,size:1},{id:"14",names:["海面","海面","Sea Surface"],water:!0,waterColor:28062,distortionScale:3.7,size:1}];constructor(e){this.engine=e,this.groundGroup=new qn,this.groundGroup.name="groundGroup"}init(){this.engine.scene.add(this.groundGroup),this.groundGroup.visible=GSe}setGround(e,t){if(this._dispose(),this.currentId=e,e==="0")return;const n=this.groundList.find(o=>o.id===e);debugger;if(!n)return;const s=t?.size??3e4;if(n.water){const o=new gd(s,s),r=t?.waterNormalsUrl??bn(J6e.DEFAULT_WATER_NORMALS,typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href),A=new Kc().load(r,g=>{g.wrapS=g.wrapT=Sr}),a=t?.sunDirection??new N(.5,.8,.5).normalize(),l=t?.distortionScale??n.distortionScale??3.7,c=t?.waterSize??n.size??1,h=t?.opacity??.92,d=new RSe(o,{textureWidth:512,textureHeight:512,waterNormals:A,sunDirection:a.clone(),sunColor:16777215,waterColor:n.waterColor??28062,distortionScale:l,alpha:h,fog:!!this.engine.scene?.fog});d.rotation.x=-Math.PI/2,d.position.y=-.01,d.name="groundMesh",d.receiveShadow=!0,d.castShadow=!1,this.ensureWaterShadowUniforms(d.material),d.material.uniforms.size.value=c,this.groundMesh=d,this.isWaterAddon=!0,this.groundGroup.add(d)}else{const o=new gd(s,s,1,1);o.rotateX(-Math.PI/2);const r=new O0({color:n.color,roughness:n.roughness,metalness:n.metalness}),A=t?.textureUrl??(n.map?bn(n.map,typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href):void 0);A&&new Kc().load(A,l=>{l.wrapS=l.wrapT=Sr,l.repeat.set(1e4,1e4),r.map=l,r.needsUpdate=!0},void 0,()=>{});const a=new lt(o,r);a.name="groundMesh",a.receiveShadow=!0,a.castShadow=!1,a.position.y=-.01,this.groundMesh=a,this.isWaterAddon=!1,this.groundGroup.add(a)}this.groundGroup.position.y=this.groundY}setHeight(e){this.groundY=e,this.groundGroup.position.y=e}getHeight(){return this.groundY}update(){if(!this.groundMesh||!this.isWaterAddon)return;const t=this.groundMesh.material?.uniforms;if(!t)return;t.time.value+=1/60;const n=this.engine.scene?.dirLight;n&&t.sunDirection&&t.sunDirection.value.copy(n.position).normalize();const s=this.engine.camera;s&&t.eye&&t.eye.value.setFromMatrixPosition(s.matrixWorld)}getGroundList(){return this.groundList.map(({id:e,names:t})=>({id:e,names:t}))}getCurrentId(){return this.currentId}getVisible(){return this.groundGroup.visible}show(){this.groundGroup.visible=!0}hide(){this.groundGroup.visible=!1}dispose(){this._dispose(),this.engine.scene.remove(this.groundGroup)}ensureWaterShadowUniforms(e){const t=e.uniforms;t.directionalShadowMap||(t.directionalShadowMap={value:[]}),t.spotShadowMap||(t.spotShadowMap={value:[]}),t.pointShadowMap||(t.pointShadowMap={value:[]}),e.uniformsNeedUpdate=!0}_dispose(){if(!this.groundMesh)return;this.groundMesh.geometry.dispose();const e=this.groundMesh.material;Array.isArray(e)?e.forEach(t=>t.dispose()):e.dispose(),this.groundGroup.remove(this.groundMesh),this.groundMesh=null,this.isWaterAddon=!1}};const SB="0",KQt=!0,Lte=.2,Kte=1,XQt=.35;let VQt=class{engine;currentHdrId=SB;isVisible=KQt;currentIntensity=Lte;currentBackgroundIntensity=Kte;currentTexture=null;currentEnvironmentTexture=null;skybox=null;textureCache=new Map;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousAmbientLightIntensity=1;previousToneMapping=Yr;previousToneMappingExposure=1;hdrList=[{id:"0",names:["无","無","None"]},{id:"1",names:["纯净-多云","純淨-多雲","Pure - Cloudy"],url:"assets/hdr/1.hdr"},{id:"2",names:["纯净-落日","純淨-落日","Pure - Sunset"],url:"assets/hdr/2.hdr"},{id:"3",names:["纯净-少云","純淨-少雲","Pure - Few Clouds"],url:"assets/hdr/3.hdr"},{id:"4",names:["纯净-无云","純淨-無雲","Pure - Cloudless"],url:"assets/hdr/4.hdr"},{id:"5",names:["纯净-夜晚","純淨-夜晚","Pure - Night"],url:"assets/hdr/5.hdr"},{id:"6",names:["纯净-阴天","純淨-陰天","Pure - Overcast"],url:"assets/hdr/6.hdr"},{id:"7",names:["纯净-中云","純淨-中雲","Pure - Partly Cloudy"],url:"assets/hdr/7.hdr"},{id:"8",names:["废弃机场","廢棄機場","Abandoned Airport"],url:"assets/hdr/8.hdr"},{id:"9",names:["户外-无云","戶外-無雲","Outdoor - Cloudless"],url:"assets/hdr/9.hdr"},{id:"10",names:["郊区花园","郊區花園","Suburban Garden"],url:"assets/hdr/10.hdr"},{id:"11",names:["室内工作室01","室內工作室01","Indoor Studio 01"],url:"assets/hdr/11.hdr"},{id:"12",names:["室内工作室02","室內工作室02","Indoor Studio 02"],url:"assets/hdr/12.hdr"},{id:"13",names:["室内工作室03","室內工作室03","Indoor Studio 03"],url:"assets/hdr/13.hdr"},{id:"14",names:["室内工作室04","室內工作室04","Indoor Studio 04"],url:"assets/hdr/14.hdr"},{id:"15",names:["小镇教堂","小鎮教堂","Town Church"],url:"assets/hdr/15.hdr"},{id:"16",names:["小镇街道","小鎮街道","Town Street"],url:"assets/hdr/16.hdr"},{id:"17",names:["夜晚街道","夜晚街道","Night Street"],url:"assets/hdr/17.hdr"},{id:"99",names:["默认","默认","default"],url:"assets/hdr/99.hdr"}];constructor(e){this.engine=e}getHdrList(){return this.hdrList}async setHdr(e){const t=this.hdrList.find(n=>n.id===e);if(!t){console.warn(`[Hdr] HDR id "${e}" not found`);return}if(e===SB||!t.url){this._clearHdr(),this.currentHdrId=SB,this._requestRender();return}if(this.textureCache.has(e)){this._applyTexture(this.textureCache.get(e)),this.currentHdrId=e,this._requestRender();return}try{const n=await this._loadHdr(t.url);this.textureCache.set(e,n),this._applyTexture(n),this.currentHdrId=e,this._requestRender()}catch(n){console.error(`[Hdr] Failed to load HDR "${t.url}":`,n)}}setVisible(e){this.isVisible=e,this.skybox&&(this.skybox.visible=e),this.engine.scene&&this.currentTexture&&(this.engine.scene.background=e?this.currentTexture:this.previousBackground,this.engine.scene.backgroundIntensity=e?this.currentBackgroundIntensity:this.previousBackgroundIntensity,this.engine.composerModule?.rebuild?.()),this._requestRender()}getCurrentHdrId(){return this.currentHdrId}getVisible(){return this.isVisible}setIntensity(e){this.currentIntensity=e,this.engine.scene&&(this.engine.scene.environmentIntensity=e,this._requestRender())}setBackgroundIntensity(e){this.currentBackgroundIntensity=Math.max(e,0),this.engine.scene&&(this.engine.scene.backgroundIntensity=this.currentBackgroundIntensity,this._updateSkyboxIntensity(),this._requestRender())}getIntensity(){return this.currentIntensity}getBackgroundIntensity(){return this.currentBackgroundIntensity}addHdrItem(e){const t=this.hdrList.find(n=>n.id===e.id);t?Object.assign(t,e):this.hdrList.push(e)}dispose(){this._clearHdr(),this.textureCache.forEach(e=>e.dispose()),this.textureCache.clear()}_loadHdr(e){const t=bn(e,typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href);return new Promise((n,s)=>{new PSe().load(t,o=>{o.mapping=mm,n(o)},void 0,o=>s(o))})}_applyTexture(e){if(this.currentTexture=e,!this.engine.scene||!this.engine.renderer)return;this._captureSceneState(),this.currentEnvironmentTexture?.dispose();const t=new _6(this.engine.renderer),n=t.fromEquirectangular(e).texture;t.dispose(),this.currentEnvironmentTexture=n,this.engine.scene.background=this.isVisible?e:this.previousBackground,this.engine.scene.backgroundIntensity=this.isVisible?this.currentBackgroundIntensity:this.previousBackgroundIntensity,this.engine.scene.environment=n,this.engine.scene.environmentIntensity=this.currentIntensity,this.engine.renderer.toneMapping=v0,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure>0?this.previousToneMappingExposure:Ute,this._removeSkybox(),this._createSkybox(e),this._setAmbientLightIntensity(this._getHdrAmbientLightIntensity()),this.engine.composerModule?.rebuild?.()}_captureSceneState(){this.currentHdrId!==SB||!this.engine.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousAmbientLightIntensity=this._getAmbientLightIntensity(),this.previousToneMapping=this.engine.renderer?.toneMapping??Yr,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1)}_createSkybox(e){if(!this.engine.scene)return;const t=new Wc(1e3,64,32),n=new Ji({map:e,side:$s,depthWrite:!1,depthTest:!1,fog:!1,toneMapped:!0});this.skybox=new lt(t,n),this.skybox.name="hdr_skybox",this.skybox.renderOrder=-1e3,this.skybox.frustumCulled=!1,this.skybox.visible=this.isVisible,this.skybox.onBeforeRender=(s,o,r)=>{this.skybox?.position.copy(r.position)},this._updateSkyboxIntensity(),this.engine.scene.add(this.skybox)}_updateSkyboxIntensity(){if(!this.skybox)return;this.skybox.material.color.setScalar(Math.max(this.currentBackgroundIntensity,.001))}_removeSkybox(){!this.skybox||!this.engine.scene||(this.engine.scene.remove(this.skybox),this.skybox.geometry.dispose(),this.skybox.material.dispose(),this.skybox=null)}_clearHdr(){this.currentTexture=null,this._removeSkybox(),this.engine.scene&&(this.currentEnvironmentTexture?.dispose(),this.currentEnvironmentTexture=null,this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this._setAmbientLightIntensity(this.previousAmbientLightIntensity),this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousAmbientLightIntensity=1,this.previousToneMapping=Yr,this.previousToneMappingExposure=1)}_getAmbientLightIntensity(){return this.engine.scene?.children.find(t=>t instanceof np)?.intensity??1}_setAmbientLightIntensity(e){const t=this.engine.scene?.children.find(n=>n instanceof np);t&&(t.intensity=e)}_getHdrAmbientLightIntensity(){return Math.max(this.previousAmbientLightIntensity*XQt,0)}_requestRender(){this.engine?.requestComposerRender?.()}};const ZQt=.001,jSe=!1,JQt=[{Id:"339",Name:"L1",Elevation:-.32808398950131235},{Id:"2787",Name:"L2",Elevation:16.896325459317584},{Id:"236633",Name:"L3",Elevation:36.745406824146976}];let zQt=class{engine;isVisible=jSe;levels=[];svgContainer=null;svgOverlay=null;worldToScreen=null;halfSize=500;COLOR="#1890ff";PLANE_OPACITY=.08;constructor(e){this.engine=e,this._initSvg()}setData(e=[],t){this._clearAll(),this.levels=e.map(s=>({data:s,group:null,svgGroup:null}));const n=t??this.getMergedBoundingBox();this.levels.forEach(s=>this._buildThreeObject(s,n))}setMockData(){const e=this.engine.models?.[0]?.levels,t=this.engine.models?.[0]?.boundingBox;this.setData(Array.isArray(e)&&e.length>0?e:JQt,t)}show(){this.isVisible=!0,this.svgContainer&&(this.svgContainer.style.display="block"),this.levels.forEach(e=>{e.group&&(e.group.visible=!0)})}hide(){this.isVisible=!1,this.svgContainer&&(this.svgContainer.style.display="none"),this.levels.forEach(e=>{e.group&&(e.group.visible=!1)})}toggle(){if(this.isVisible){this.hide();return}this.show()}getVisible(){return this.isVisible}update(){!this.isVisible||!this.svgOverlay||this.levels.length===0||!this.engine.camera||!this.engine.renderer||(this._initWorldToScreen(),this.levels.forEach(e=>this._updateSvgLabels(e)))}getLocationByPoint(e,t){const{url:n,targetPoint:s}=this.resolvePointLookupArgs(e,t),o=this.getLevelData(n).slice().sort((g,u)=>g.Elevation-u.Elevation);if(o.length===0)return null;const r=(s instanceof N,s.y),A=o.find(g=>Math.abs(g.Elevation-r)<=ZQt)??null;if(A)return{pointY:r,description:`${A.Name}`,currentLevel:A,lowerLevel:A,upperLevel:A,isOnLevel:!0,isInside:!0};let a=null,l=null;o.forEach(g=>{if(g.Elevation<r){a=g;return}l||(l=g)});const c=this.pickNearestLevel(r,a,l),h=c?`标高${c.Name}`:"";let d=!1;return a&&l&&(d=!0),{pointY:r,description:h,currentLevel:c,lowerLevel:a,upperLevel:l,isOnLevel:!1,isInside:d}}dispose(){this._clearAll(),this.svgContainer&&(this.svgContainer.remove(),this.svgContainer=null),this.svgOverlay=null,this.worldToScreen=null}_initSvg(){this.svgContainer=document.createElement("div"),this.svgContainer.style.position="absolute",this.svgContainer.style.top="0",this.svgContainer.style.left="0",this.svgContainer.style.width="100%",this.svgContainer.style.height="100%",this.svgContainer.style.pointerEvents="none",this.svgContainer.style.overflow="hidden",this.svgContainer.style.display="none",this.engine.container.appendChild(this.svgContainer),this.svgOverlay=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svgOverlay.style.position="absolute",this.svgOverlay.style.top="0",this.svgOverlay.style.left="0",this.svgOverlay.style.width="1920px",this.svgOverlay.style.height="1080px",this.svgOverlay.style.overflow="visible",this.svgContainer.appendChild(this.svgOverlay)}_initWorldToScreen(){this.engine.camera&&this.engine.renderer&&this.engine.scene&&(this.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene))}_clearAll(){this.levels.forEach(e=>{e.group&&this.engine.scene&&(this.engine.scene.remove(e.group),e.group.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose())}),e.group=null),e.svgGroup&&(e.svgGroup.remove(),e.svgGroup=null)}),this.levels=[]}_buildThreeObject(e,t){if(!this.engine.scene)return;const n=new N(t.min.x,t.min.y,t.min.z),s=new N(t.max.x,t.max.y,t.max.z);this.halfSize=s.distanceTo(n);const o=e.data.Elevation,r=new qn,A=new gd(this.halfSize*2,this.halfSize*2);A.rotateX(-Math.PI/2);const a=new Ji({color:this.COLOR,transparent:!0,opacity:this.PLANE_OPACITY,side:An,depthWrite:!1}),l=new lt(A,a);l.position.y=o,r.add(l);const c=[new N(-this.halfSize,o,-this.halfSize),new N(this.halfSize,o,-this.halfSize),new N(this.halfSize,o,this.halfSize),new N(-this.halfSize,o,this.halfSize),new N(-this.halfSize,o,-this.halfSize)],h=new mi().setFromPoints(c),d=new bo({color:this.COLOR,transparent:!0,opacity:.7});if(r.add(new uA(h,d)),r.visible=this.isVisible,this.engine.scene.add(r),e.group=r,this.svgOverlay){const g=document.createElementNS("http://www.w3.org/2000/svg","g");g.dataset.levelId=e.data.Id;for(let u=0;u<4;u+=1)g.appendChild(this._makeLabel(e.data.Name,e.data.Elevation));this.svgOverlay.appendChild(g),e.svgGroup=g}}_updateSvgLabels(e){if(!e.svgGroup||!this.worldToScreen)return;const t=e.data.Elevation,n=[new N(-this.halfSize,t,-this.halfSize),new N(this.halfSize,t,-this.halfSize),new N(this.halfSize,t,this.halfSize),new N(-this.halfSize,t,this.halfSize)],s=Array.from(e.svgGroup.children);n.forEach((o,r)=>{const A=this.worldToScreen?.worldToScreen(o);A&&(s[r].setAttribute("x",String(A.x)),s[r].setAttribute("y",String(A.y)))})}_makeLabel(e,t){const n=document.createElementNS("http://www.w3.org/2000/svg","text");return n.textContent=`${e} ${t.toFixed(3)}m`,n.setAttribute("text-anchor","middle"),n.setAttribute("dominant-baseline","central"),n.setAttribute("fill",this.COLOR),n.setAttribute("font-size","12"),n.setAttribute("font-family","Arial, sans-serif"),n.setAttribute("font-weight","bold"),n.setAttribute("stroke","white"),n.setAttribute("stroke-width","2"),n.setAttribute("paint-order","stroke"),n.style.pointerEvents="none",n}getLevelData(e){if(e){const n=this.findModelByUrl(e);return Array.isArray(n?.levels)?n.levels:[]}if(this.levels.length>0)return this.levels.map(n=>n.data);if(!Array.isArray(this.engine.models))return[];const t=[];return this.engine.models.forEach(n=>{Array.isArray(n.levels)&&t.push(...n.levels)}),t}resolvePointLookupArgs(e,t){if(typeof e=="string"){if(!t)throw new Error("Level.getLocationByPoint(url, point) requires a point argument.");return{url:e,targetPoint:t}}return{targetPoint:e}}findModelByUrl(e){return this.engine.models?.find(t=>t.url===e)}pickNearestLevel(e,t,n){if(t&&n){const s=Math.abs(e-t.Elevation),o=Math.abs(n.Elevation-e);return s<=o?t:n}return t??n}getMergedBoundingBox(){if(!Array.isArray(this.engine.models)||this.engine.models.length===0)return{min:{x:-this.halfSize,y:-this.halfSize,z:-this.halfSize},max:{x:this.halfSize,y:this.halfSize,z:this.halfSize}};const e=new Wt;let t=!1;return this.engine.models.forEach(n=>{const s=n.boundingBox;if(!s)return;const o=new N(s.min.x,s.min.y,s.min.z),r=new N(s.max.x,s.max.y,s.max.z);if(!t){e.min.copy(o),e.max.copy(r),t=!0;return}e.expandByPoint(o),e.expandByPoint(r)}),t?e:{min:{x:-this.halfSize,y:-this.halfSize,z:-this.halfSize},max:{x:this.halfSize,y:this.halfSize,z:this.halfSize}}}};const y9=!0,Xte=.5,HQt=32,qQt=.05,$Qt=.02,eMt=.06,tMt=.01;function iMt(i){return!i?.min||!i?.max?0:i.min.distanceTo(i.max)}function nMt(i,e){return i instanceof N?i.clone():e?.min&&e?.max?e.min.clone().add(e.max).multiplyScalar(.5):new N}function sMt(i,e,t){if(i instanceof Zo)return Math.max((i.top-i.bottom)/Math.max(i.zoom,1e-6),1);const n=i,s=nMt(e,t),o=n.position.distanceTo(s),r=typeof n.getEffectiveFOV=="function"?n.getEffectiveFOV():n.fov,A=Ai.degToRad(r*.5);return Math.max(2*o*Math.tan(A),1)}function oMt(i,e,t,n){if(i==null)return n;const s=iMt(t);if(s<=0)return n;const o=sMt(i,e,t),r=Math.max(s*$Qt,1),A=Math.max(s*eMt,r+1),a=Ai.clamp((o-r)/(A-r),0,1);return Ai.lerp(n,0,a)}let rMt=class{engine;isActive=y9;groupEdge;highlightEdgeGroup;material;highlightEdgeMaterial;baseOpacity=Xte;modelEdgeLoaded=!1;modelEdgeLoadingPromise=null;indexes=new Map;highlightIndexes=new Map;highlightEdgeSyncVersion=0;explodeHidden=!1;groupVisibleBeforeExplode=y9;highlightVisibleBeforeExplode=!0;lastReportedOpacity=null;getModelEntry(e){return this.engine?.models?.find(t=>t?.url===e)??null}shouldLoadModelEdge(e){return e?.loadEdge!==!1}getFilteredIdSet(e){return this.engine?.filterLoaderModel?.getContinueIdSet?.(e)??new Set}getOrCreateItemIndex(e){const t=this.indexes.get(e);if(t)return t;const n=this.getModelEntry(e);if(!this.shouldLoadModelEdge(n))return null;const s=Array.isArray(n?.modelEdge)?n.modelEdge:null;if(!s)return null;const o=new Map;let r=0;return s.forEach((A,a)=>{const l=Array.isArray(A?.points)?A.points:null;if(!l)return;const c=r;for(let h=0;h<l.length;h++)l[h]?.length===2&&(r+=6);o.set(Number(A.id),[c,r,a])}),this.indexes.set(e,o),o}getEdgePointsByIndex(e,t){const n=this.getModelEntry(e),s=Array.isArray(n?.modelEdge)?n.modelEdge[t]:null;return Array.isArray(s?.points)?s.points:null}getLineByUrl(e){return this.groupEdge.children.find(t=>t.url==e)??null}getHighlightIndex(e){const t=this.highlightIndexes.get(e);if(t)return t;const n=this.getModelEntry(e);if(!this.shouldLoadModelEdge(n))return null;const s=Array.isArray(n?.modelEdge)?n.modelEdge:null;if(!s)return null;const o=new Map;return s.forEach((r,A)=>{o.set(Number(r?.id),A)}),this.highlightIndexes.set(e,o),o}constructor(e){this.engine=e,this.groupEdge=this.engine.scene.getObjectByName("groupEdge"),zR(this.groupEdge,this.engine.sectionPlane),this.groupEdge.userData.excludeFromAutoExposure=!0,this.highlightEdgeGroup=new qn,this.highlightEdgeGroup.name="highlightModelEdgeGroup",zR(this.highlightEdgeGroup,this.engine.sectionPlane),this.highlightEdgeGroup.userData.excludeFromAutoExposure=!0,this.highlightEdgeGroup.renderOrder=999,this.engine.scene.add(this.highlightEdgeGroup),this.material=new bo({color:0,transparent:!0,opacity:Xte,depthTest:!0,depthWrite:!1}),this.material.clippingPlanes=this.engine.sectionPlane,this.highlightEdgeMaterial=new bo({color:16777215,transparent:!0,opacity:1,depthTest:!1,depthWrite:!1}),this.highlightEdgeMaterial.clippingPlanes=this.engine.sectionPlane,this.groupEdge.visible=y9}active(){this.isActive=!0,this.groupEdge.visible=!this.explodeHidden,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&Gbe(e,!0)}),this.update(),this.show()}disActive(){this.isActive=!1,this.groupEdge.visible=!1,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&Gbe(e,!1)})}isEnabled(){return this.isActive}getOpacity(){return this.baseOpacity}setExplodeHidden(e){this.explodeHidden!==e&&(this.explodeHidden=e,e?(this.groupVisibleBeforeExplode=this.groupEdge?.visible===!0,this.highlightVisibleBeforeExplode=this.highlightEdgeGroup.visible,this.groupEdge.visible=!1,this.highlightEdgeGroup.visible=!1):(this.groupEdge.visible=this.isActive&&this.groupVisibleBeforeExplode,this.highlightEdgeGroup.visible=this.highlightVisibleBeforeExplode),this.engine.requestComposerRender?.())}update(){if(!this.isActive||!this.material)return;const e=oMt(this.engine?.camera,this.engine?.controls?.target,this.engine?.octreeBox?.getBoundingBox?.(),this.baseOpacity);(this.lastReportedOpacity===null||Math.abs(this.lastReportedOpacity-e)>.001)&&(console.log("[ModelEdge] 实时透明度:",Number(e.toFixed(4))),this.lastReportedOpacity=e),!(e>0&&Math.abs(this.material.opacity-e)<=tMt)&&(this.material.opacity=e,this.material.needsUpdate=!0)}hasPendingModelEdges(){return(this.engine?.models??[]).some(t=>this.shouldLoadModelEdge(t)&&!Array.isArray(t?.modelEdge))}loadZipJsonAsync(e,t){return new Promise((n,s)=>{dC(e,o=>{if(o==null){s(new Error(`[ModelEdge] empty edge zip: ${e}`));return}n(o)},()=>{s(new Error(`[ModelEdge] failed to load edge zip: ${e}`))},t)})}async ensureModelEdgeData(e){if(!this.shouldLoadModelEdge(e))return[];if(Array.isArray(e?.modelEdge))return e.modelEdge;try{const t=this.engine.engineStatus.models.find(o=>o.url==e.url);p1(this.engine,e.url,e.url+"/edge");const n=await this.loadZipJsonAsync(e.url+"/edge",t?.key??e?.key),s=JSON.parse(n);if(Array.isArray(s)){const o=this.getFilteredIdSet(e.url);e.modelEdge=o.size>0?s.filter(r=>o.has(Number(r?.id))===!1):s}else e.modelEdge=[]}catch(t){console.error("[ModelEdge] failed to load model edge",{url:e?.url,error:t}),e.modelEdge=[]}return e.modelEdge}async loadModelEdge(){if(!(this.modelEdgeLoaded&&!this.hasPendingModelEdges())){if(this.modelEdgeLoadingPromise!=null){await this.modelEdgeLoadingPromise;return}this.modelEdgeLoadingPromise=(async()=>{const e=this.engine?.models??[];for(const t of e)!this.shouldLoadModelEdge(t)||Array.isArray(t?.modelEdge)||await this.ensureModelEdgeData(t);this.modelEdgeLoaded=!this.hasPendingModelEdges()})().finally(()=>{this.modelEdgeLoadingPromise=null}),await this.modelEdgeLoadingPromise}}async show(){if(await this.loadModelEdge(),!this.isActive||this.explodeHidden)return;(this.engine?.models??[]).forEach(t=>{if(!this.shouldLoadModelEdge(t))return;const n=t?.url;if(typeof n!="string"||n.length===0)return;const s=this.groupEdge.children.find(c=>c.url==n);if(s){s.visible=!0;return}const o=[],r=new Map;if((Array.isArray(t?.modelEdge)?t.modelEdge:[]).forEach((c,h)=>{r.set(Number(c?.id),h),(Array.isArray(c?.points)?c.points:[]).forEach(g=>{g?.length===2&&(o.push(g[0].X),o.push(g[0].Z),o.push(-g[0].Y),o.push(g[1].X),o.push(g[1].Z),o.push(-g[1].Y))})}),o.length===0)return;const a=new mi;a.setAttribute("position",new Qi(o,3));const l=new ir(a,this.material);l.url=n,this.setLineTransform(l,Ju(this.engine,n)),this.groupEdge.add(l),this.highlightIndexes.set(n,r),this.releaseIndexes(n)})}setModelEdgeTransform(e,t){const n=this.groupEdge.children.find(s=>s.url==e);n&&this.setLineTransform(n,t),this.highlightEdgeGroup.children.forEach(s=>{s?.url==e&&this.setLineTransform(s,t)})}setLineTransform(e,t){e.matrixAutoUpdate=!1,e.matrix.copy(t),e.matrixWorldNeedsUpdate=!0,e.updateMatrixWorld(!0)}syncHighlightModelEdges(e){const t=++this.highlightEdgeSyncVersion;this.syncHighlightModelEdgesAsync(e,t)}clearHighlightModelEdges(){this.highlightEdgeSyncVersion++,this.disposeHighlightEdges()}releaseModel(e){this.highlightEdgeSyncVersion++,[this.groupEdge,this.highlightEdgeGroup].forEach(t=>{[...t?.children??[]].forEach(n=>{n?.url===e&&(t.remove(n),n.geometry?.dispose?.())})}),this.indexes.delete(e),this.highlightIndexes.delete(e)}releaseIndexes(e){if(typeof e=="string"&&e.length>0){this.indexes.delete(e);return}this.indexes.clear()}async syncHighlightModelEdgesAsync(e,t){await this.loadModelEdge(),t===this.highlightEdgeSyncVersion&&(this.disposeHighlightEdges(),e.forEach(n=>{const s=this.getHighlightIndex(n.url);if(!s||!Array.isArray(n.ids))return;const o=[];if(n.ids.forEach(a=>{const l=s?.get(Number(a)),c=typeof l=="number"?this.getEdgePointsByIndex(n.url,l):null;if(Array.isArray(c)){if(c.length>HQt)return;this.appendEdgePositions(o,c)}}),o.length===0)return;const r=new mi;r.setAttribute("position",new Qi(o,3));const A=new ir(r,this.highlightEdgeMaterial);A.name="highlightModelEdge",A.url=n.url,this.setLineTransform(A,Ju(this.engine,n.url)),this.highlightEdgeGroup.add(A)}))}appendEdgePositions(e,t){t.forEach(n=>{n?.length===2&&(e.push(n[0].X,n[0].Z,-n[0].Y),e.push(n[1].X,n[1].Z,-n[1].Y))})}disposeHighlightEdges(){[...this.highlightEdgeGroup.children].forEach(t=>{this.highlightEdgeGroup.remove(t),t.geometry?.dispose?.()})}getModelEdge(e,t){if(!this.shouldLoadModelEdge(this.getModelEntry(e)))return null;const n=this.getOrCreateItemIndex(e);if(n){const s=n.get(Number(t));if(s){const o=typeof s[2]=="number"?this.getEdgePointsByIndex(e,s[2]):null;return[s[0],s[1],o]}}return this.loadModelEdge(),null}hideModelEdge(e,t){if(!this.shouldLoadModelEdge(this.getModelEntry(e)))return;const n=this.getLineByUrl(e),s=this.getOrCreateItemIndex(e);if(!s){this.loadModelEdge();return}const o=s.get(Number(t));if(!o)return;const[r,A]=o;if(n){const a=n.geometry.attributes.position.array;for(let l=r;l<A;l++)a[l]=NaN;n.geometry.attributes.position.needsUpdate=!0}this.releaseIndexes(e)}setOpacity(e){this.baseOpacity=Ai.clamp(e,qQt,1),this.update()}showModelEdge(e,t){if(!this.shouldLoadModelEdge(this.getModelEntry(e)))return;const n=this.getLineByUrl(e),s=this.getOrCreateItemIndex(e);if(!s){this.loadModelEdge();return}const o=s.get(Number(t));if(!o)return;const[r,A,a]=o,l=typeof a=="number"?this.getEdgePointsByIndex(e,a):null;if(n&&Array.isArray(l)){const c=n.geometry.attributes.position.array;let h=0;for(let d=r;d<A;d+=3){const g=Math.floor(h/6),u=h%6>=3;if(l[g]&&l[g].length===2){const p=u?l[g][1]:l[g][0];c[d]=p.X,c[d+1]=p.Z,c[d+2]=-p.Y}h+=3}n.geometry.attributes.position.needsUpdate=!0}this.releaseIndexes(e)}};class USe extends lt{constructor(){const e=new _o;super(new Vo(1,1,1),e),this.turbidity=ui(2),this.rayleigh=ui(1),this.mieCoefficient=ui(.005),this.mieDirectionalG=ui(.8),this.sunPosition=ui(new N),this.cloudScale=ui(2e-4),this.cloudSpeed=ui(2e-5),this.cloudCoverage=ui(.4),this.cloudDensity=ui(.4),this.cloudElevation=ui(.5),this.showSunDisc=ui(1),this.isSky=!0,this.isSkyMesh=!0;const t=r4("vec3"),n=r4("float"),s=r4("vec3"),o=r4("vec3"),r=ss(()=>{const a=ft(2.718281828459045),l=zn(5804542996261093e-21,13562911419845635e-21,30265902468824876e-21),c=zn(18399918514433978e-2,27798023919660528e-2,40790479543861094e-2),h=ft(1.6110731556870734),d=ft(1.5),g=ft(1e3),u=PA(this.sunPosition);t.assign(u);const p=u.y,m=vh(p,-1,1),I=g.mul(an(0,ft(1).sub(Hg(a,h.sub(I1(m)).div(d).negate()))));n.assign(I);const B=ft(1).sub(vh(ft(1).sub(t4(this.sunPosition.y.div(45e4))),0,1)),y=this.rayleigh.sub(ft(1).mul(ft(1).sub(B)));s.assign(l.mul(y));const w=ft(.2).mul(this.turbidity).mul(1e-17),M=ft(.434).mul(w).mul(c);o.assign(M.mul(this.mieCoefficient));const D=UIt;return D.z.assign(D.w),D})(),A=ss(()=>{const a=ft(3.141592653589793),l=ft(8400),c=ft(1250),h=ft(.9999566769464484),d=ft(.05968310365946075),g=ft(.07957747154594767),u=PA(VIt.sub(SIt)),p=I1(an(0,u.y)),m=ft(1).div(oC(p).add(ft(.15).mul(Hg(ft(93.885).sub(p.mul(180).div(a)),-1.253)))),I=l.mul(m),B=c.mul(m),y=t4(Ip(s,I).add(Ip(o,B)).negate()),w=ys(u,t),M=w.mul(.5).add(.5),D=d.mul(ft(1).add(Hg(M,2))),Q=s.mul(D),b=Hg(this.mieDirectionalG,2),P=ft(1).div(Hg(ft(1).sub(ft(2).mul(this.mieDirectionalG).mul(w)).add(b),1.5)),F=g.mul(ft(1).sub(b)).mul(P),T=o.mul(F),x=Hg(n.mul(ib(Q,T).div(ib(s,o))).mul(BB(1,y)),zn(1.5));x.mulAssign(xa(zn(1),Hg(n.mul(ib(Q,T).div(ib(s,o))).mul(y),zn(1/2)),vh(Hg(BB(1,t.y),5),0,1)));const C=zn(.1).mul(y),S=vh(w.sub(h).mul(5e4),0,1).mul(this.showSunDisc),v=TA(n.mul(y),80).mul(760).mul(S),Y=ib(x,C).mul(.04).add(v).add(zn(0,3e-4,75e-5)).toVar(),k=ss(([U])=>{const O=zu(U.xyx.mul(zn(.1031,.103,.0973))).toVar();return O.addAssign(ys(O,O.yzx.add(33.33))),zu(O.xx.add(O.yz).mul(O.zy)).mul(2).sub(1)}),j=ss(([U])=>{const O=rC(U),V=zu(U),$=V.mul(V).mul(V).mul(V.mul(V.mul(6).sub(15)).add(10)),z=ys(k(O),V),ie=ys(k(O.add(or(1,0))),V.sub(or(1,0))),te=ys(k(O.add(or(0,1))),V.sub(or(0,1))),Ae=ys(k(O.add(or(1,1))),V.sub(or(1,1)));return xa(xa(z,ie,$.x),xa(te,Ae,$.x),$.y).mul(1.6)}),R=ss(([U,O])=>{const V=or(U).toVar(),$=ft(0).toVar(),z=ft(1).toVar();return Bd(4,()=>{$.addAssign(z.mul(j(V))),z.mulAssign(.5),V.mulAssign(2).addAssign(O)}),$});return fs(u.y.greaterThan(0).and(this.cloudCoverage.greaterThan(0)),()=>{const U=xa(1,.1,this.cloudElevation),O=u.xz.div(u.y.mul(U)).toVar();O.mulAssign(this.cloudScale),O.addAssign(Zbe.mul(this.cloudSpeed));const V=Zbe.mul(this.cloudSpeed).mul(300),$=R(O.mul(1e3),V).mul(.7).add(.5).clamp(0,1).toVar(),z=j(O.mul(300)).mul(.37).add(.5),ie=vh(this.cloudCoverage.add(z.sub(.5).mul(.6)),0,1),te=BB(1,ie).toVar(),Ae=EB(te,te.add(.3),$).toVar(),J=EB(0,ib(.03,Ip(.06,this.cloudElevation)),u.y);Ae.mulAssign(J);const W=EB(-.08,.3,t.y),ee=n.mul(y).mul(.22).mul(.04).toVar(),q=x.mul(.04).add(zn(0,3e-4,75e-5)),ne=an(0,$.sub(te)).toVar(),Z=t4(ne.mul(-4)).toVar(),K=BB(1,Z.mul(Z)),re=xa(.45,1,Z.mul(K).mul(2.6).clamp(0,1)),ue=ft(.51).div(Hg(BB(1.49,w.mul(1.4)),1.5)).clamp(0,3),le=Ae.mul(BB(1,Ae)).mul(4),ae=q.add(ee.mul(re)).toVar();ae.addAssign(ee.mul(ue).mul(le).mul(.6)),ae.mulAssign(W.max(.03));const he=BB(1,t4(ne.mul(this.cloudDensity).mul(-12))).mul(J).toVar();Y.subAssign(C.mul(.04).add(v).mul(he));const De=xa(Y,ae,y);Y.assign(xa(Y,De,he))}),Yn(Y,1)})();e.side=$s,e.depthWrite=!1,e.fog=!1,e.vertexNode=r,e.colorNode=A}}const kSe={turbidity:2,rayleigh:5,mieCoefficient:.005,mieDirectionalG:.7,elevation:10,azimuth:180,exposure:.2,orthoExposureScale:1.5,cloudScale:2e-4,cloudSpeed:2e-5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},Vte="sunrise_clear",WSe=.2,Zte=[{id:"sunrise_clear",names:["晴朗日出","晴朗日出","Clear Sunrise"],params:{turbidity:4,rayleigh:1.8,mieCoefficient:.004,mieDirectionalG:.72,elevation:8,azimuth:105,exposure:.42,cloudCoverage:.12,cloudDensity:.2,cloudElevation:.45,showSunDisc:!0}},{id:"morning_mist",names:["晨雾薄云","晨霧薄雲","Misty Morning"],params:{turbidity:14,rayleigh:2.4,mieCoefficient:.018,mieDirectionalG:.68,elevation:12,azimuth:120,exposure:.35,cloudCoverage:.45,cloudDensity:.5,cloudElevation:.35,showSunDisc:!0}},{id:"noon_clear",names:["晴空正午","晴空正午","Clear Noon"],params:{turbidity:2,rayleigh:1,mieCoefficient:.002,mieDirectionalG:.82,elevation:68,azimuth:180,exposure:.58,cloudCoverage:.05,cloudDensity:.12,cloudElevation:.55,showSunDisc:!0}},{id:"afternoon_cloudy",names:["午后多云","午後多雲","Cloudy Afternoon"],params:{turbidity:8,rayleigh:1.7,mieCoefficient:.008,mieDirectionalG:.74,elevation:42,azimuth:220,exposure:.5,cloudCoverage:.48,cloudDensity:.42,cloudElevation:.52,showSunDisc:!0}},{id:"sunset_glow",names:["落日晚霞","落日晚霞","Sunset Glow"],params:{turbidity:10,rayleigh:2,mieCoefficient:.006,mieDirectionalG:.7,elevation:6,azimuth:245,exposure:.6,cloudCoverage:.3,cloudDensity:.36,cloudElevation:.5,showSunDisc:!0}},{id:"blue_hour",names:["暮色蓝调","暮色藍調","Blue Hour"],params:{turbidity:7,rayleigh:1.2,mieCoefficient:.003,mieDirectionalG:.76,elevation:-4,azimuth:255,exposure:.22,cloudCoverage:.2,cloudDensity:.24,cloudElevation:.48,showSunDisc:!1}},{id:"overcast_day",names:["阴天白昼","陰天白晝","Overcast Day"],params:{turbidity:20,rayleigh:2,mieCoefficient:.02,mieDirectionalG:.6,elevation:32,azimuth:180,exposure:.38,cloudCoverage:.86,cloudDensity:.68,cloudElevation:.4,showSunDisc:!1}},{id:"storm_rain",names:["暴雨雷云","暴雨雷雲","Storm Rain"],params:{turbidity:19,rayleigh:.9,mieCoefficient:.03,mieDirectionalG:.58,elevation:18,azimuth:210,exposure:.2,cloudCoverage:.95,cloudDensity:.9,cloudElevation:.28,showSunDisc:!1}},{id:"snow_day",names:["雪天漫射","雪天漫射","Snowy Day"],params:{turbidity:15,rayleigh:2.6,mieCoefficient:.012,mieDirectionalG:.65,elevation:24,azimuth:170,exposure:.5,cloudCoverage:.78,cloudDensity:.72,cloudElevation:.43,showSunDisc:!1}},{id:"moonlit_night",names:["月夜星空","月夜星空","Moonlit Night"],params:{turbidity:4,rayleigh:.35,mieCoefficient:.001,mieDirectionalG:.82,elevation:-18,azimuth:160,exposure:.14,cloudCoverage:.1,cloudDensity:.14,cloudElevation:.55,showSunDisc:!1}}],OSe=Zte.reduce((i,e)=>(i[e.id]=e,i),{}),LSe=2e6,Jte=45e4,AMt=128,aMt=100,KSe="v3-sky-clouds",XSe={turbidity:[0,20],rayleigh:[0,4],mieCoefficient:[0,.1],mieDirectionalG:[0,.999],elevation:[-90,90],azimuth:[-360,360],exposure:[0,4],orthoExposureScale:[.1,4],cloudScale:[1e-6,.005],cloudSpeed:[0,.001],cloudCoverage:[0,1],cloudDensity:[0,1],cloudElevation:[0,1]};let lMt=class{engine;sky=null;sun=new N;params=this._resolveParams(OSe[Vte].params);currentPreset=Vte;currentIntensity=WSe;currentEnvironmentTarget=null;environmentRefreshTimer=null;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=Yr;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){this.engine?.scene&&(this._captureSceneState(),this.sky||(this.sky=new USe,this.sky.scale.setScalar(Jte),this.sky.name=this.skyName,this.sky.frustumCulled=!1,this._getBackgroundScene()?.add(this.sky)),this.sky.visible=!0,this._syncSkyToCamera(),this.engine.scene.background=null,this._expandCameraFarForSky(),this._applyParamsToSky(),this._updateAnimationState(),this.engine.composerModule?.rebuild?.(),this._requestRender())}close(e=!0){this.sky&&(this._cancelEnvironmentRefresh(),this.engine?.setIdleFrameRateExempt?.(KSe,!1),this._restoreCameraFar(),this._restoreSceneState(),e?(this.sky.removeFromParent(),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null,this._disposeEnvironmentTarget()):this.sky.visible=!1,this.engine.composerModule?.rebuild?.(),this._requestRender())}isActive(){return this.sky?.visible===!0&&this.sky.parent===this._getBackgroundScene()}getParams(){return{...this.params}}setParams(e){this.params=this._resolveParams({...this.params,...e}),this._applyParamsToSky(),this._requestRender()}setPreset(e){const t=OSe[e];t&&(this.currentPreset=e,this.params=this._resolveParams(t.params),this._applyParamsToSky(),this._requestRender())}getCurrentPreset(){return this.currentPreset}getPresetNames(){return Zte.map(e=>e.id)}getPresetList(){return Zte.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){Number.isFinite(e)&&(this.currentIntensity=Math.max(e,0),this.isActive()&&this.engine?.scene&&(this.engine.scene.environmentIntensity=this.currentIntensity,this.currentEnvironmentTarget||this._scheduleEnvironmentRefresh(),this._requestRender()))}getIntensity(){return this.currentIntensity}update(e){this._syncSkyToCamera()}_getBackgroundScene(){return this.engine?.composerModule?.postProcessingBackgroundScene??this.engine?.scene??null}_syncSkyToCamera(){!this.sky?.visible||!this.engine?.camera||(this.sky.position.copy(this.engine.camera.position),this.sky.updateMatrixWorld())}_isOrthographicCamera(){return this.engine?.camera?.isOrthographicCamera===!0}_getEffectiveExposure(){return this._isOrthographicCamera()?this.params.exposure*this.params.orthoExposureScale:this.params.exposure}_expandCameraFarForSky(){const e=this.engine?.camera;!e||typeof e.far!="number"||e.far>=LSe||(this.savedCameraFar==null&&(this.savedCameraFar=e.far),e.far=LSe,e.updateProjectionMatrix?.())}_restoreCameraFar(){const e=this.engine?.camera;this.savedCameraFar==null||!e||(e.far=this.savedCameraFar,e.updateProjectionMatrix?.(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;this.sky.turbidity.value=this.params.turbidity,this.sky.rayleigh.value=this.params.rayleigh,this.sky.mieCoefficient.value=this.params.mieCoefficient,this.sky.mieDirectionalG.value=this.params.mieDirectionalG,this.sky.cloudScale.value=this.params.cloudScale,this.sky.cloudSpeed.value=this.params.cloudSpeed,this.sky.cloudCoverage.value=this.params.cloudCoverage,this.sky.cloudDensity.value=this.params.cloudDensity,this.sky.cloudElevation.value=this.params.cloudElevation,this.sky.showSunDisc.value=this.params.showSunDisc;const e=Ai.degToRad(90-this.params.elevation),t=Ai.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,e,t),this.sky.sunPosition.value.copy(this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=tw,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()),this._updateAnimationState(),this.isActive()&&this._scheduleEnvironmentRefresh()}_captureSceneState(){this.hasCapturedSceneState||!this.engine?.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousToneMapping=this.engine.renderer?.toneMapping??Yr,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(){!this.hasCapturedSceneState||!this.engine?.scene||(this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=Yr,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1)}_scheduleEnvironmentRefresh(){!this.isActive()||!this.engine?.renderer||(this._cancelEnvironmentRefresh(),this.environmentRefreshTimer=setTimeout(()=>{this.environmentRefreshTimer=null,this._refreshEnvironmentMap()},aMt))}_cancelEnvironmentRefresh(){this.environmentRefreshTimer!=null&&(clearTimeout(this.environmentRefreshTimer),this.environmentRefreshTimer=null)}_refreshEnvironmentMap(){if(!this.isActive()||!this.engine?.renderer||!this.engine?.scene)return;const e=new ld,t=new USe;t.scale.setScalar(Jte),t.turbidity.value=this.params.turbidity,t.rayleigh.value=this.params.rayleigh,t.mieCoefficient.value=this.params.mieCoefficient,t.mieDirectionalG.value=this.params.mieDirectionalG,t.sunPosition.value.copy(this.sun),t.cloudScale.value=this.params.cloudScale,t.cloudSpeed.value=0,t.cloudCoverage.value=this.params.cloudCoverage,t.cloudDensity.value=this.params.cloudDensity,t.cloudElevation.value=this.params.cloudElevation,t.showSunDisc.value=!1,e.add(t);const n=new _6(this.engine.renderer);try{const s=n.fromScene(e,0,.1,Jte*2,{size:AMt}),o=this.currentEnvironmentTarget;this.currentEnvironmentTarget=s,this.engine.scene.environment=s.texture,this.engine.scene.environmentIntensity=this.currentIntensity,o?.dispose(),this._requestRender()}catch(s){console.warn("[SkyManager] WebGPU 天空环境贴图生成失败,将继续显示天空背景。",s)}finally{n.dispose(),t.material.dispose(),t.geometry.dispose()}}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_updateAnimationState(){const e=this.isActive()&&this.params.cloudSpeed>0&&this.params.cloudCoverage>0&&this.params.cloudDensity>0;this.engine?.setIdleFrameRateExempt?.(KSe,e)}_resolveParams(e){const t={...kSe,...e};return Object.keys(XSe).forEach(n=>{const s=XSe[n],o=t[n];if(!s||typeof o!="number")return;const r=Number.isFinite(o)?o:kSe[n];t[n]=Ai.clamp(r,s[0],s[1])}),t.showSunDisc=!!t.showSunDisc,t}_requestRender(){this.engine?.requestComposerRender?.()}},cMt=class{engine;defaultSettings;settings;environmentApplyVersion=0;constructor(e){this.engine=e,this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}init(){this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}getSettings(){return this._syncSettingsFromModules(),this._clone(this.settings)}getPresetLists(){const e=this.engine.ground?.getGroundList()||[],t=this.engine.hdr?.getHdrList()||[],n=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(s=>this._toPresetItem(s)),hdr:t.map(s=>this._toPresetItem(s)),sky:n.map(s=>this._toPresetItem(s))}}async setSettings(e){e.render&&(Object.assign(this.settings.render,e.render),this._applyRenderSettings(this.settings.render)),e.display&&(Object.assign(this.settings.display,e.display),this._applyDisplaySettings(this.settings.display)),e.environment&&(this._mergeEnvironmentSettings(e.environment),await this._applyEnvironmentSettings(this._clone(this.settings.environment)))}async resetToDefault(){this.settings=this._clone(this.defaultSettings),this._applyRenderSettings(this.settings.render),this._applyDisplaySettings(this.settings.display),await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setRenderMode(e){this.settings.render.mode=e,this.engine.engineModelModule?.setQualityLevel(e)}setContrast(e){this.settings.render.contrast=e,this.engine.engineModelModule?.setContrastValue(.5+e/100)}setSaturation(e){this.settings.render.saturation=e,this.engine.engineModelModule?.setSaturationValue(.5+e/100)}setShadowIntensity(e){this.settings.render.shadowIntensity=e,this._updateDirectionalLight(t=>{t.shadow.intensity=e/100*2})}setLightIntensity(e){this.settings.render.lightIntensity=e,this.setAmbientLightIntensity(e/100)}setGTAOIntensity(e){this.settings.render.gtaoIntensity=e,this.engine.engineModelModule?.setGTAOIntensity(e/100)}setShowEdge(e){this.settings.display.showEdge=e,e?this.engine.modelEdge?.active():this.engine.modelEdge?.disActive()}setEdgeOpacity(e){this.settings.display.edgeOpacity=e,this.engine.modelEdge?.setOpacity(e/100)}setShowGrid(e){this.settings.display.showGrid=e,e?this.engine.grid?.show():this.engine.grid?.hide()}setShowLevel(e){this.settings.display.showLevel=e,e?this.engine.level?.show():this.engine.level?.hide()}setShowGround(e){this.settings.display.showGround=e,e?this.engine.ground?.show():this.engine.ground?.hide()}setGroundId(e){this.settings.display.groundId=e,this.engine.ground?.setGround(e)}setGroundHeight(e){this.settings.display.groundHeight=e,this.engine.ground?.setHeight(e)}async setEnvironmentType(e){this.settings.environment.type=e,await this._applyEnvironmentSettings(this._clone(this.settings.environment))}async setHdrId(e){this.settings.environment.hdrId=e,this.settings.environment.type==="hdr"&&await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setHdrIntensity(e){this.settings.environment.hdrIntensity=e,this.settings.environment.hdrEnvironmentIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setHdrBackgroundIntensity(e){this.settings.environment.hdrBackgroundIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setBackgroundIntensity(e/100)}setHdrEnvironmentIntensity(e){this.settings.environment.hdrEnvironmentIntensity=e,this.settings.environment.hdrIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setSkyPreset(e){this.settings.environment.skyPreset=e,this.settings.environment.skyParams={},this.settings.environment.type==="sky"&&this.engine.skyManager?.setPreset(e)}setSkyParams(e){this.settings.environment.skyParams=this._clone(e),this.settings.environment.type==="sky"&&this.engine.skyManager?.setParams(this.settings.environment.skyParams)}setSkyIntensity(e){this.settings.environment.skyIntensity=e,this.settings.environment.type==="sky"&&this.engine.skyManager?.setIntensity(e/100)}setAmbientLightIntensity(e){const t=this.engine.renderer;t&&(t.toneMapping=v0,t.toneMappingExposure=2*e)}_syncSettingsFromModules(){this.settings=this._readCurrentSettingsFromModules()}_buildDefaultSettingsFromModules(){const e=this.engine.composerModule?.getColorGradingParameters?.(),t=this.engine.composerModule?.getEffectParameters?.("gtao"),n=this.engine.renderer?.toneMappingExposure,s=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??SB,r=this.engine.hdr?.getIntensity?.(),A=this.engine.hdr?.getBackgroundIntensity?.(),a=this.engine.skyManager?.getIntensity?.(),l=this.engine.skyManager?.getCurrentPreset?.()??Vte,c=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getQualityLevel?.()),contrast:this._uniformToPercent(e?.contrast,CCt),saturation:this._uniformToPercent(e?.saturation,mCt),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),b4),lightIntensity:this._exposureToPercent(n,Ute),gtaoIntensity:this._unitToPercent(t?.scale,ICt)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??y9,edgeOpacity:this._unitToPercent(s,Xte),showGrid:this.engine.grid?.getVisible?.()??Ote,showLevel:this.engine.level?.getVisible?.()??jSe,showGround:this.engine.ground?.getVisible?.()??GSe,groundId:this.engine.ground?.getCurrentId?.()??NSe,groundHeight:this.engine.ground?.getHeight?.()??YSe},environment:{type:c?"sky":o!==SB?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(r,Lte),hdrBackgroundIntensity:this._unitToPercent(A,Kte),hdrEnvironmentIntensity:this._unitToPercent(r,Lte),skyPreset:l,skyParams:{},skyIntensity:this._unitToPercent(a,WSe)}}}_readCurrentSettingsFromModules(){const e=this.engine.composerModule?.getColorGradingParameters?.(),t=this.engine.composerModule?.getEffectParameters?.("gtao"),n=this.engine.renderer?.toneMappingExposure,s=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??this.settings.environment.hdrId,r=this.engine.hdr?.getIntensity?.(),A=this.engine.hdr?.getBackgroundIntensity?.(),a=this.engine.skyManager?.getIntensity?.(),l=this.engine.skyManager?.getCurrentPreset?.()??this.settings.environment.skyPreset,c=this.engine.skyManager?.getParams?.(),h=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getQualityLevel?.()??this.settings.render.mode),contrast:this._uniformToPercent(e?.contrast,this.settings.render.contrast/100+.5),saturation:this._uniformToPercent(e?.saturation,this.settings.render.saturation/100+.5),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),this.settings.render.shadowIntensity/50),lightIntensity:this._exposureToPercent(n,this.settings.render.lightIntensity/50),gtaoIntensity:this._unitToPercent(t?.scale,this.settings.render.gtaoIntensity/100)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??this.settings.display.showEdge,edgeOpacity:this._unitToPercent(s,this.settings.display.edgeOpacity/100),showGrid:this.engine.grid?.getVisible?.()??this.settings.display.showGrid,showLevel:this.engine.level?.getVisible?.()??this.settings.display.showLevel,showGround:this.engine.ground?.getVisible?.()??this.settings.display.showGround,groundId:this.engine.ground?.getCurrentId?.()??this.settings.display.groundId,groundHeight:this.engine.ground?.getHeight?.()??this.settings.display.groundHeight},environment:{type:h?"sky":o!==SB?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(r,this.settings.environment.hdrIntensity/100),hdrBackgroundIntensity:this._unitToPercent(A,this.settings.environment.hdrBackgroundIntensity/100),hdrEnvironmentIntensity:this._unitToPercent(r,(this.settings.environment.hdrEnvironmentIntensity??this.settings.environment.hdrIntensity)/100),skyPreset:l,skyParams:c?this._clone(c):this._clone(this.settings.environment.skyParams),skyIntensity:this._unitToPercent(a,this.settings.environment.skyIntensity/100)}}}_toRenderMode(e){return e==null?FSe:X1(e)}_uniformToPercent(e,t){const n=typeof e=="number"?e:t;return this._clampPercent((n-.5)*100)}_shadowToPercent(e,t){const n=typeof e=="number"?e:t;return this._clampPercent(n*50)}_exposureToPercent(e,t){const n=typeof e=="number"?e:t;return this._clampPercent(n*50)}_unitToPercent(e,t){const n=typeof e=="number"?e:t;return this._clampPercent(n*100)}_clampPercent(e){return Math.min(100,Math.max(0,Math.round(e)))}_getDirectionalLightShadowIntensity(){const e=this.engine.scene?.children?.filter(n=>n instanceof xh);return!e||e.length===0?b4:(e.find(n=>n.castShadow)??e[0]).shadow?.intensity??b4}_applyRenderSettings(e){this.setRenderMode(e.mode),this.setContrast(e.contrast),this.setSaturation(e.saturation),this.setShadowIntensity(e.shadowIntensity),this.setLightIntensity(e.lightIntensity),this.setGTAOIntensity(e.gtaoIntensity)}_applyDisplaySettings(e){this.setShowEdge(e.showEdge),this.setEdgeOpacity(e.edgeOpacity),this.setShowGrid(e.showGrid),this.setShowLevel(e.showLevel),this.setShowGround(e.showGround),this.setGroundId(e.groundId),this.setGroundHeight(e.groundHeight)}async _applyEnvironmentSettings(e){const t=++this.environmentApplyVersion;if(await this.engine.hdr?.setHdr(SB),t===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),t===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!==SB){if(await this.engine.hdr?.setHdr(e.hdrId),t!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setBackgroundIntensity((e.hdrBackgroundIntensity??Kte)/100),this.engine.hdr?.setIntensity((e.hdrEnvironmentIntensity??e.hdrIntensity)/100)}break;case"sky":this.engine.skyManager?.activate(),this.engine.skyManager?.setPreset(e.skyPreset),Object.keys(e.skyParams).length>0&&this.engine.skyManager?.setParams(this._clone(e.skyParams)),this.engine.skyManager?.setIntensity(e.skyIntensity/100);break}}_updateDirectionalLight(e){const t=this.engine.scene?.children.find(n=>n instanceof xh);t&&e(t)}_mergeEnvironmentSettings(e){Object.assign(this.settings.environment,e),e.skyPreset!==void 0&&e.skyParams===void 0&&(this.settings.environment.skyParams={}),e.skyParams!==void 0&&(this.settings.environment.skyParams=this._clone(e.skyParams))}_toPresetItem(e){const t=Array.isArray(e.names)?[...e.names]:[];return{id:e.id,name:t[0]??e.id,names:t}}_clone(e){return JSON.parse(JSON.stringify(e))}};function $a(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){var e=Math.random()*16|0,t=i=="x"?e:e&3|8;return t.toString(16)})}let xB=class{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Tee(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,t){if(e==null)return null;let n=this.setting.unit,s=n;return t==1?n=="mm"?e=e*1e3:n=="cm"?e=e*100:n=="dm"?e=e*10:n=="m"?e=e*1:n=="km"&&(e=e*.001):t==2&&(n=="mm"?e=e*1e3*1e3:n=="cm"?e=e*100*100:n=="dm"?e=e*10*10:n=="m"?e=e*1*1:n=="km"&&(e=e*.001*.001),s=s+"²"),e.toFixed(this.setting.precision)+" "+s}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight==!0&&(n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData,t=!0;for(let n in e)for(let s=e[n].length-1;s>=0;s--){let o=e[n][s];o.isSelect==!0&&(o.container.remove(),e[n].splice(s,1),t=!1)}this.engine.measure.clearAllPoints(),t&&(this.engine.events.trigger("quit_measure_draw",!0),this.engine.modelToolModule.unhighlightAllModels(),this.engine.measure.quitDraw())}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let t in e)for(let n=e[t].length-1;n>=0;n--){let s=e[t][n];s.highlight==!0&&(s.container.remove(),e[t].splice(n,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;const t=new po(e.engine.camera,e.engine.renderer,e.engine.scene);function n(I){const B=t.worldToScreenIfVisible(I);return B==null?null:(B.x+=e.engine.reactBoundingClientRect.left,B.y+=e.engine.reactBoundingClientRect.top,B)}function s(I,B){I.container!=null&&(I.container.style.display=B?"block":"none")}this.engine.measure.annotationData.normalAnnotation.forEach(I=>{m(I)}),this.engine.measure.annotationData.elevationAnnotation.forEach(I=>{p(I)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(I=>{u(I)}),this.engine.measure.annotationData.angleAnnotation.forEach(I=>{h(I)}),this.engine.measure.annotationData.areaAnnotation.forEach(I=>{d(I)}),this.engine.measure.annotationData.slopeAnnotation.forEach(I=>{g(I)});function h(I){if(I.container==null){let b=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel">'+I.text+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="angle-annotation",I.container.id=I.id,I.container.style.pointerEvents="none",I.container.innerHTML=b,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=n(I.point1),y=n(I.point2),w=n(I.point3);if(B==null||y==null||w==null){s(I,!1);return}s(I,!0);let M=I.container;M.getElementsByTagName("circle")[0].setAttribute("cx",B.x),M.getElementsByTagName("circle")[0].setAttribute("cy",B.y),M.getElementsByTagName("circle")[1].setAttribute("cx",y.x),M.getElementsByTagName("circle")[1].setAttribute("cy",y.y),M.getElementsByTagName("circle")[2].setAttribute("cx",w.x),M.getElementsByTagName("circle")[2].setAttribute("cy",w.y),M.getElementsByTagName("polyline")[0].setAttribute("points",B.x+","+B.y+" "+y.x+","+y.y),M.getElementsByTagName("polyline")[1].setAttribute("points",y.x+","+y.y+" "+w.x+","+w.y);let D=y.x,Q=y.y-30;M.getElementsByTagName("rect")[0].setAttribute("x",D-40),M.getElementsByTagName("rect")[0].setAttribute("y",Q-12.5),M.getElementsByTagName("text")[0].setAttribute("x",D),M.getElementsByTagName("text")[0].setAttribute("y",Q+4),M.getElementsByTagName("text")[0].innerHTML=I.text,M.style.top="0px",M.style.left="0px"}function d(I){if(I.container==null){let T=['<svg class="measureSvg">','<polygon fill="rgba(0, 0, 255, 0.1)" stroke="none" points="" style="opacity: 0.3;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(I.text,2)+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="area-annotation",I.container.id=I.id,I.container.innerHTML=T,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}if(!I.points||I.points.length<2)return;let B=[],y=0,w=0;for(let T=0;T<I.points.length;T++){let x=n(I.points[T]);if(x==null){s(I,!1);return}B.push(x),y+=x.x,w+=x.y}s(I,!0),y=y/B.length,w=w/B.length;let M=B.map(T=>T.x+","+T.y).join(" "),D=[...B];B.length>=3&&D.push(B[0]);let Q=D.map(T=>T.x+","+T.y).join(" "),b=I.container;b.getElementsByTagName("polygon")[0].setAttribute("points",B.length>=3?M:""),b.getElementsByTagName("polyline")[0].setAttribute("points",Q);let P=y,F=w;b.getElementsByTagName("rect")[0].setAttribute("x",P-40),b.getElementsByTagName("rect")[0].setAttribute("y",F-12.5),b.getElementsByTagName("text")[0].setAttribute("x",P+10),b.getElementsByTagName("text")[0].setAttribute("y",F+4),b.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(I.text,2),b.style.top="0px",b.style.left="0px"}function g(I){if(I.container==null){let Q=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+I.id+'" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">','<path class="measureLine" d="M0,0 L0,6 L9,3 z"/>',"</marker>","</defs>",'<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" marker-end="url(#slope-arrow-'+I.id+')" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+I.text+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="slope-annotation",I.container.id=I.id,I.container.innerHTML=Q,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=n(I.point1),y=n(I.point2);if(B==null||y==null){s(I,!1);return}s(I,!0);let w=I.container;w.getElementsByTagName("polyline")[0].setAttribute("points",B.x+","+B.y+" "+y.x+","+y.y);let M=(B.x+y.x)/2,D=(B.y+y.y)/2-30;w.getElementsByTagName("rect")[0].setAttribute("x",M-50),w.getElementsByTagName("rect")[0].setAttribute("y",D-12.5),w.getElementsByTagName("text")[0].setAttribute("x",M),w.getElementsByTagName("text")[0].setAttribute("y",D+4),w.getElementsByTagName("text")[0].innerHTML=I.text,w.style.top="0px",w.style.left="0px"}function u(I){if(I.container==null){let b=['<svg class="measureSvg">','<circle class="measurePointer" cx="0" cy="0" r="5" fill="#f99d0b" />','<rect x="0" y="-25" width="100" height="25" class="measureBack" />','<text x="50" y="-11" text-anchor="middle" class="measureLabel"> X: '+e.getMeasureText(I.textX,1)+"</text>",'<rect x="0" y="-10" width="100" height="25" class="measureBack" />','<text x="50" y="25" text-anchor="middle" class="measureLabel"> Y: '+e.getMeasureText(-I.textZ,1)+"</text>",'<rect x="0" y="10" width="100" height="25" class="measureBack" />','<text x="50" y="51" text-anchor="middle" class="measureLabel"> Z: '+e.getMeasureText(I.textY,1)+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="coordinate-annotation",I.container.id=I.id,I.container.style.position="absolute",I.container.style.pointerEvents="none",I.container.innerHTML=b,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=I.container,y=n(I.point);if(y==null){s(I,!1);return}s(I,!0),B.style.top="0px",B.style.left="0px";let w=B.getElementsByTagName("circle")[0];w&&(w.setAttribute("cx",y.x),w.setAttribute("cy",y.y));let M=B.getElementsByTagName("rect"),D=B.getElementsByTagName("text"),Q=-55;M[0]&&(M[0].setAttribute("x",y.x+10),M[0].setAttribute("y",y.y+10+Q)),D[0]&&(D[0].setAttribute("x",y.x+10+50),D[0].setAttribute("y",y.y+10+16+Q)),M[1]&&(M[1].setAttribute("x",y.x+10),M[1].setAttribute("y",y.y+10+30+Q)),D[1]&&(D[1].setAttribute("x",y.x+10+50),D[1].setAttribute("y",y.y+10+46+Q)),M[2]&&(M[2].setAttribute("x",y.x+10),M[2].setAttribute("y",y.y+10+60+Q)),D[2]&&(D[2].setAttribute("x",y.x+10+50),D[2].setAttribute("y",y.y+10+76+Q)),D[0]&&(D[0].innerHTML="X: "+e.getMeasureText(I.textX,1)),D[1]&&(D[1].innerHTML="Y: "+e.getMeasureText(-I.textZ,1)),D[2]&&(D[2].innerHTML="Z: "+e.getMeasureText(I.textY,1))}function p(I){if(I.container==null){let w=['<svg width="100" height="50" class="measureSvg">','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(I.text,1)+"</text>",'<polyline class="measureLine" stroke-width="2" points="80,32 0,32 16,48 32,32" style="fill: none; opacity: 1;"/>',"</svg>"].join("");I.container=document.createElement("div"),I.container.className="elevation-annotation",I.container.id=I.id,I.container.style.position="absolute",I.container.style.pointerEvents="none",I.container.innerHTML=w,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=I.container,y=n(I.point);if(y==null){s(I,!1);return}s(I,!0),B.style.top=y.y-48+"px",B.style.left=y.x-16+"px",B.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(I.text,1)}function m(I){if(I.container==null){let M=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="80,32 0,32" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(I.text,1)+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="normal-annotation",I.container.id=I.id,I.container.innerHTML=M,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=I.container;if(I.point1==null||I.point2==null){B.style.display="none";return}else B.style.display="block";let y=n(I.point1),w=n(I.point2);if(y==null||w==null){s(I,!1);return}s(I,!0),B.getElementsByTagName("polyline")[0].setAttribute("points",y.x+","+y.y+" "+w.x+","+w.y),B.getElementsByTagName("circle")[0].setAttribute("cx",y.x),B.getElementsByTagName("circle")[0].setAttribute("cy",y.y),B.getElementsByTagName("circle")[1].setAttribute("cx",w.x),B.getElementsByTagName("circle")[1].setAttribute("cy",w.y),B.getElementsByTagName("rect")[0].setAttribute("x",y.x*.5+w.x*.5-40),B.getElementsByTagName("rect")[0].setAttribute("y",y.y*.5+w.y*.5-12.5),B.getElementsByTagName("text")[0].setAttribute("x",y.x*.5+w.x*.5+50-40),B.getElementsByTagName("text")[0].setAttribute("y",y.y*.5+w.y*.5+16-12.5),B.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(I.text,1),B.style.top="0px",B.style.left="0px"}}},hMt=class{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e===0?0:1}handelKeyTabDown(e){e.preventDefault(),!e.repeat&&(this.catchDir=this.catchDir===0?1:0)}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let s=0;s<e.length;s++){const o=e[s];if(!o)continue;typeof o.updateMatrixWorld=="function"&&o.updateMatrixWorld(!0);const r=new Wt().setFromObject(o);!Number.isFinite(r.min.y)||!Number.isFinite(r.max.y)||(r.min.y<t&&(t=r.min.y),r.max.y>n&&(n=r.max.y))}return!Number.isFinite(t)||!Number.isFinite(n)?null:{minY:t,maxY:n}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let o=this.engine.interactionModule.getCatchMeshs(e);var n=this.getMeshesMinMaxY(o);this.catchDir==0?t.set(t.x,n?.minY,t.z):t.set(t.x,n?.maxY,t.z)}else t=e.catch.point;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(t);return}let s=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);s!=null&&(s.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);t==null&&(t={text:null,id:$a(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=e.catch;if(this.type=="element"){let s=e.catch.point.clone();s.set(s.x,this.points[0].y,s.z);let o=new Ao(s.add(new N(0,.01*(this.catchDir==0?-1:1),0)),new N(0,this.catchDir==0?-1:1,0));n.point=this.points[0];const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(o))??this.engine.octreeBox.rayInterationModel(o);if(r.length===0){t.point2=null;return}t.point1=s,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(ia.MeasureChanged,t)}else{let s=new Ao(e.catch.point.clone().add(new N(0,.01*(this.catchDir==0?-1:1),0)),new N(0,this.catchDir==0?-1:1,0));const o=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(s))??this.engine.octreeBox.rayInterationModel(s);if(o.length===0){t.point2=null;return}t.point1=n.point,t.point2=o[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(ia.MeasureChanged,t)}}},dMt=class{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point),this.behavior.setLastPoint(t.point);else if(this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);if(n==null)return;n.point2=t.point,n.isSelect=!1,this.points=[],this.engine.events.trigger(ia.MeasureChanged,n),this.behavior.clearLastPoint()}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);n==null&&(n={id:$a(),point1:this.points[0].clone(),point2:t.point.clone(),text:this.points[0].clone().distanceTo(t.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(n)),n.point2=t.point,n.text=n.point1.clone().distanceTo(n.point2.clone())}}},gMt=class{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);t==null&&(t={text:null,id:$a(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=new Ao(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const s=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(n))??this.engine.octreeBox.rayInterationModel(n);if(s.length==0){t.point2=null;return}let o=e.catch;t.point1=o.point,t.point2=s[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(ia.MeasureChanged,t)}},uMt=class{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.text=e.catch.point.y)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);if(t==null){t={id:$a(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t);return}t.point=e.catch.point.clone(),t.text=e.catch.point.y,t.isSelect=!1,this.engine.events.trigger(ia.MeasureChanged,t)}},fMt=class{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);if(t==null){t={id:$a(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(t);return}t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,t.isSelect=!1,this.engine.events.trigger(ia.MeasureChanged,t)}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(ia.MeasureChanged,e))}},pMt=class{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,t,n){const s=new N().subVectors(e,t),o=new N().subVectors(n,t),r=s.length(),A=o.length();if(r===0||A===0)return 0;const l=s.dot(o)/(r*A),c=Math.max(-1,Math.min(1,l));return Math.acos(c)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1)this.points.push(t.point);else if(this.points.length==2){let n=this.engine.measure.annotationData.angleAnnotation.find(s=>s.isSelect==!0);if(n==null)return;n.point3=t.point.clone(),n.angle=this.calculateAngle(n.point1,n.point2,n.point3),n.text=n.angle.toFixed(2)+"°",n.isSelect=!1,n.type="angle",this.points=[],this.engine.events.trigger(ia.MeasureChanged,n)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:$a(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(t)),t.point3=e.catch.point.clone(),t.angle=this.calculateAngle(t.point1,t.point2,t.point3),t.text=t.angle.toFixed(2)+"°",console.log("角度",t.text)}}},IMt=class{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}getCurrentDrawingMeasure(){return this.engine.measure.annotationData.areaAnnotation.find(e=>e.isSelect==!0)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;const e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;const t=e.length,n=new N(0,0,0);for(let s=0;s<t;s++){const o=(s+1)%t;n.x+=(e[s].y-e[o].y)*(e[s].z+e[o].z),n.y+=(e[s].z-e[o].z)*(e[s].x+e[o].x),n.z+=(e[s].x-e[o].x)*(e[s].y+e[o].y)}return n.length()/2}handleRightMouseClick(){this.finishMeasure()}handleMouseClick(e){if(e.catch==null)return;const t=e.catch;this.points.length===0&&this.engine.measure.tools.clearHighlight(),this.points.push(t.point.clone());let n=this.getCurrentDrawingMeasure();n==null?(n={id:$a(),points:this.points.map(s=>s.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(n)):n.points=this.points.map(s=>s.clone()),this.points.length>=3?(n.area=this.calculateArea(this.points),n.text=n.area):(n.area=0,n.text=0)}handleMouseMove(e){if(e.catch!=null&&this.points.length>=1){let t=this.getCurrentDrawingMeasure();t==null&&(t={id:$a(),points:[],area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t));const n=this.points.map(s=>s.clone());n.push(e.catch.point.clone()),t.points=n,n.length>=3?(t.area=this.calculateArea(n),t.text=t.area):(t.area=0,t.text=0)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){const e=this.getCurrentDrawingMeasure();e!=null&&this.points.length>=3?(e.points=this.points.map(t=>t.clone()),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(ia.MeasureChanged,e)):this.engine.measure.tools.handelKeyEscDown()}},mMt=class d8{engine;tools;static WORLD_UP=new N(0,1,0);static SLOPE_DIRECTION_SNAP_DISTANCE=10;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,t){const n=t.y-e.y,s=t.x-e.x,o=t.z-e.z,r=Math.sqrt(s*s+o*o);if(r===0)return{percentage:0,angle:0,heightDiff:n,horizontalDist:0,type:"slope"};const A=n/r*100,l=Math.atan(n/r)*(180/Math.PI);return{percentage:A,angle:l,heightDiff:n,horizontalDist:r,type:"slope"}}getWorldFaceNormal(e){const t=e?.normal??e?.face?.normal;if(t==null)return null;const n=t.clone(),s=e?.matrix??e?.object?.matrixWorld;return s!=null&&n.transformDirection(s),n.lengthSq()<1e-10?null:n.normalize()}getFaceSlopeDirection(e){const t=this.getWorldFaceNormal(e);if(t==null)return null;const n=new N().crossVectors(t,d8.WORLD_UP);if(n.lengthSq()<1e-10)return null;const s=new N().crossVectors(n.normalize(),t);return s.lengthSq()<1e-10?null:s.normalize()}pointToScreenLineDistance(e,t,n){const s=new Ne().subVectors(n,t),o=s.lengthSq();if(o<1e-10)return e.distanceTo(t);const r=new Ne().subVectors(e,t).dot(s)/o,A=t.clone().add(s.multiplyScalar(r));return e.distanceTo(A)}isNearSlopeDirection(e,t,n,s,o){const r=new po(this.engine.camera,this.engine.renderer,this.engine.scene),A=r.worldToScreenIfVisible(e);if(A==null)return!1;const a=Number.isFinite(o?.offsetX)&&Number.isFinite(o?.offsetY)?new Ne(o.offsetX,o.offsetY):r.worldToScreenIfVisible(s);if(a==null)return!1;const l=Math.max(e.distanceTo(s),e.distanceTo(n),1),c=e.clone().add(t.clone().multiplyScalar(l)),h=r.worldToScreenIfVisible(c);if(h!=null)return this.pointToScreenLineDistance(a,A,h)<=d8.SLOPE_DIRECTION_SNAP_DISTANCE;const d=r.worldToScreenIfVisible(n);return d!=null&&a.distanceTo(d)<=d8.SLOPE_DIRECTION_SNAP_DISTANCE}getSlopeSnappedPoint(e,t,n){const s=t?.point;if(!(s instanceof N))return e.clone();const o=this.getFaceSlopeDirection(t);if(o==null)return s.clone();const r=new N().subVectors(s,e).dot(o);if(!Number.isFinite(r))return s.clone();const A=e.clone().add(o.clone().multiplyScalar(r));return this.isNearSlopeDirection(e,o,A,s,n)?A:s.clone()}updateSlopeMeasure(e,t,n){e.point2=t.clone();const s=this.calculateSlope(e.point1,e.point2);e.slopePercentage=s.percentage,e.slopeAngle=s.angle,e.heightDiff=s.heightDiff,e.horizontalDist=s.horizontalDist,e.text=s.percentage.toFixed(2)+"%";const o=this.getWorldFaceNormal(n),r=this.getFaceSlopeDirection(n);e.faceNormal=o?.clone(),e.slopeDirection=r?.clone(),e.isSlopeDirectionSnapped=n?.point instanceof N?t.distanceTo(n.point)>1e-8:!1}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point.clone());else if(this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(o=>o.isSelect==!0);if(n==null)return;const s=this.getSlopeSnappedPoint(n.point1,t,e);this.updateSlopeMeasure(n,s,t),n.isSelect=!1,this.points=[],this.engine.events.trigger(ia.MeasureChanged,n)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(o=>o.isSelect==!0);n==null&&(n={id:$a(),point1:this.points[0].clone(),point2:this.getSlopeSnappedPoint(this.points[0],t,e),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00%",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(n));const s=this.getSlopeSnappedPoint(n.point1,t,e);this.updateSlopeMeasure(n,s,t)}}},CMt=class{engine;isActive=!1;points=[];behavior;constructor(e){this.engine=e}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.behavior.clearLastPoint?.();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.behavior?.clearLastPoint?.(),this.behavior?.disActive?.()}clearAllPoints(){this.points=[],this.behavior?.clearLastPoint?.()}handleMouseClick(e){if(e.catch==null)return;if(this.points.length===0){this.engine.measure.tools.clearHighlight(),this.points=[e.catch.point.clone()],this.behavior?.setLastPoint?.(e.catch.point.clone());return}const t=this.getFaceInfo(e.catch);if(t==null)return;const n=this.points[0].clone(),s=this.projectPointToFace(n,t);if(s==null)return;let o=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);o==null&&(o={id:$a(),type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(o)),o.point1=n,o.point2=s.footPoint,o.text=s.distance,o.facePoint=t.point.clone(),o.faceNormal=t.normal.clone(),o.isSelect=!1,this.points=[],this.behavior?.clearLastPoint?.(),this.engine.events.trigger(ia.MeasureChanged,o)}handleMouseMove(e){if(e.catch==null||this.points.length!==1)return;const t=this.getFaceInfo(e.catch);if(t==null)return;const n=this.points[0].clone(),s=this.projectPointToFace(n,t);if(s==null)return;let o=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);o==null&&(o={id:$a(),point1:n.clone(),point2:s.footPoint.clone(),text:s.distance,type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(o)),o.point1=n,o.point2=s.footPoint,o.text=s.distance,o.facePoint=t.point.clone(),o.faceNormal=t.normal.clone()}getFaceInfo(e){if(e?.face==null||e?.point==null)return null;const t=e.point.clone?.(),n=this.getWorldFaceNormal(e);return!(t instanceof N)||n==null?null:{point:t,normal:n}}getWorldFaceNormal(e){const t=e?.normal??e?.face?.normal;if(t==null)return null;const n=t.clone(),s=e?.matrix??e?.object?.matrixWorld;return s!=null&&n.transformDirection(s),n.lengthSq()<1e-10?null:n.normalize()}projectPointToFace(e,t){const n=new N().subVectors(e,t.point).dot(t.normal),s=e.clone().sub(t.normal.clone().multiplyScalar(n));return{footPoint:s,distance:e.distanceTo(s)}}},EMt=class{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;faceDistanceMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new hMt(e),this.distanceMeasure=new dMt(e),this.clearDistanceMeasure=new gMt(e),this.elevationMeasure=new uMt(e),this.pointMeasure=new fMt(e),this.angleMeasure=new pMt(e),this.areaMeasure=new IMt(e),this.slopeMeasure=new mMt(e),this.faceDistanceMeasure=new CMt(e),this.tools=new xB(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}setContextMenuDisabled(e){this.engine?.engineStatus!=null&&(this.engine.engineStatus.isDisableContextMenu=e)}active(){this.isActive=!0,this.engine.setIdleFrameRateExempt?.("measure",!0),this.setContextMenuDisabled(!0),this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.engine.setIdleFrameRateExempt?.("measure",!1),this.setContextMenuDisabled(!1),this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}quitDraw(){this.setContextMenuDisabled(!1),this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints(),this.faceDistanceMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(t){for(let n=0;n<t.length;n++)t[n].container.remove()}this.annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]}}saveSetting(e){this.tools.saveSetting(e)}getSetting(){return this.tools.getSetting()}update(){this.isActive&&this.tools.drawNormalAnnotation()}dispose(){this.engine.setIdleFrameRateExempt?.("measure",!1),this.setContextMenuDisabled(!1),this.tools.disActive(),this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.clearAll(),this.annotationContainer.remove(),this.isActive=!1}};var Pa=(i=>(i.ModelLoadStart="model-load-start",i.ModelLoadProgress="model-load-progress",i.ModelLoaded="model-loaded",i.ModelError="model-error",i.SelectionChanged="selection-changed",i.HoverChanged="hover-changed",i.Click="click",i.MouseMove="mouse-move",i.ModelPlaceSelected="model-place-selected",i.ModelCalibrationChanged="model-calibration-changed",i.CameraChanged="camera-changed",i.CameraIdle="camera-idle",i.EngineFree="engine-free",i.EngineBusy="engine-busy",i.MeasureChanged="measure-changed",i.MeasureClick="measure-click",i.SectionMove="section-move",i.LoadingCompleted="loading_completed",i))(Pa||{});class VSe{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;faceIdleOpacity=0;faceHoverOpacity=.05;mobileLongPressDelay=2e3;mobileLongPressMoveTolerance=10;touchLongPressTimer=null;touchLongPressActive=!1;touchStartPosition=null;touchLatestEvent=null;transformControls=new Map;transformAnchors=new Map;transformHelpers=new Map;faceMetaMap=new Map;isSyncingTransform=!1;transformHandleSize=1.05;transformHandleColor=255;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),n=t.intersectObjects(this.getInteractiveMeshes(),!1);n.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:n}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),n=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:n})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeTouchStart=e=>{if(!this.isActive||e.touches.length!==1||!this.isMobileDevice()){this.resetTouchLongPressState();return}const t=this.createMouseEventFromTouch(e);if(!t)return;if(this.createRaycasterFromMouseEvent(t).intersectObjects(this.getInteractiveMeshes(),!1).length===0){this.resetTouchLongPressState();return}e.preventDefault(),e.stopImmediatePropagation(),this.resetTouchLongPressState(),this.touchLatestEvent=t,this.touchStartPosition=this.getTouchPoint(e),this.touchLongPressTimer=window.setTimeout(()=>{const o=this.touchLatestEvent;if(!o||!this.isActive)return;const r=this.createRaycasterFromMouseEvent(o),A=r.intersectObjects(this.getInteractiveMeshes(),!1);A.length!==0&&(this.touchLongPressActive=!0,this.handleMouseDown({button:0,raycaster:r,intersects:A}))},this.mobileLongPressDelay)};handleNativeTouchMove=e=>{if(!this.isMobileDevice())return;if(e.touches.length!==1){this.resetTouchLongPressState();return}const t=this.createMouseEventFromTouch(e);if(!t)return;this.touchLatestEvent=t;const n=this.getTouchPoint(e);if(!this.touchLongPressActive&&this.touchStartPosition&&n&&this.touchStartPosition.distanceTo(n)>this.mobileLongPressMoveTolerance&&this.clearTouchLongPressTimer(),!this.touchLongPressActive)return;e.preventDefault(),e.stopImmediatePropagation();const s=this.createRaycasterFromMouseEvent(t),o=s.intersectObjects(this.getInteractiveMeshes(),!1);this.handleMouseMove({raycaster:s,intersects:o})};handleNativeTouchEnd=e=>{this.isMobileDevice()&&(this.clearTouchLongPressTimer(),this.touchLongPressActive&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:0})),this.resetTouchLongPressState())};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};constructor(e,t){this.engine=e,this.meshs=[]}active(){this.isActive||(this.attachListeners(),this.init(),this.setTransformControlsVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}disActive(){this.init(!1),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.clearClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlsVisible(!0),this.updateClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}init(e=!0){const t=this.engine.octreeBox.getBoundingBox();t.min.x-=.1,t.min.y-=.1,t.min.z-=.1,t.max.x+=.1,t.max.y+=.1,t.max.z+=.1,this.maxBox=JSON.parse(JSON.stringify(t)),this.box=t,this.updata_face(t),e&&this.updateClippingBoxFill()}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box),this.updateClippingBoxFill()}setBox(e){this.box=e,this.updata_face(e),this.updateClippingBoxFill()}reverseBox(){}handleMouseDown(e){const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0){this.clearClippingBoxFill();const n=t[0];this.isDrag=!0,this.pickPoint=n.point.clone(),this.pickMesh=n.object;const s=this.pickMesh?.userData?.dragNormal?.clone?.(),o=n.face?.normal?.clone?.();if(this.pickNormal=(s??o??new N(0,0,1)).clone().normalize(),this.engine.controls.enabled=!1,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const r=new Fn;r.setFromNormalAndCoplanarPoint(new N(0,1,0),this.pickPoint),this.plane=r}else{const r=new N(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),A=new Fn;A.setFromNormalAndCoplanarPoint(r.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=A}}else this.isDrag=!1}handleMouseUp(e,t=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.plane=null,this.engine.controls.enabled=!0,t&&this.updateClippingBoxFill()}clampVector3(e,t,n){return new N(Math.max(t.x,Math.min(n.x,e.x)),Math.max(t.y,Math.min(n.y,e.y)),Math.max(t.z,Math.min(n.z,e.z)))}handleMouseMove(e){this.resetMeshOpacity();const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=this.faceHoverOpacity),this.pickPoint!=null){const n=new N;if(e.raycaster.ray.intersectPlane(this.plane,n)){const s=n.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(!!this.pickMesh?.userData?.isMinFace){const r=this.box_.min.clone().add(this.pickNormal.clone().setLength(s));this.box.min=this.clampVector3(r,this.maxBox.min,this.box.max)}else{const r=this.box_.max.clone().add(this.pickNormal.clone().setLength(s));this.box.max=this.clampVector3(r,this.box.min,this.maxBox.max)}this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){const e=this.maxBox.max.x-this.maxBox.min.x,t=this.maxBox.max.y-this.maxBox.min.y,n=this.maxBox.max.z-this.maxBox.min.z,s=this.toPercent((this.box.min.x-this.maxBox.min.x)/e*100),o=this.toPercent((this.box.max.x-this.maxBox.min.x)/e*100),r=this.toPercent((this.box.min.y-this.maxBox.min.y)/t*100),A=this.toPercent((this.box.max.y-this.maxBox.min.y)/t*100),a=this.toPercent((this.box.min.z-this.maxBox.min.z)/n*100),l=this.toPercent((this.box.max.z-this.maxBox.min.z)/n*100),c={x:{min:s,max:o},y:{min:r,max:A},z:{min:a,max:l}};this.engine.events.trigger(Pa.SectionMove,c)}toPercent(e){return e<0?0:e>100?100:e}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const t=new Ao,n=new Ne,s=this.engine.renderer.domElement.clientWidth,o=this.engine.renderer.domElement.clientHeight;return n.x=e.offsetX/s*2-1,n.y=-(e.offsetY/o)*2+1,t.setFromCamera(n,this.engine.camera),t}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getTouchPoint(e){const t=e.touches[0]||e.changedTouches[0];return t?new Ne(t.clientX,t.clientY):null}createMouseEventFromTouch(e){const t=e.touches[0]||e.changedTouches[0],n=this.engine.renderer?.domElement;if(!t||!n)return null;const s=n.getBoundingClientRect();return{offsetX:t.clientX-s.left,offsetY:t.clientY-s.top,clientX:t.clientX,clientY:t.clientY,button:0}}clearTouchLongPressTimer(){this.touchLongPressTimer!=null&&(clearTimeout(this.touchLongPressTimer),this.touchLongPressTimer=null)}resetTouchLongPressState(){this.clearTouchLongPressTimer(),this.touchLongPressActive=!1,this.touchStartPosition=null,this.touchLatestEvent=null}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),e.addEventListener("touchstart",this.handleNativeTouchStart,{capture:!0,passive:!1}),e.addEventListener("touchmove",this.handleNativeTouchMove,{capture:!0,passive:!1}),e.addEventListener("touchend",this.handleNativeTouchEnd,{capture:!0,passive:!1}),e.addEventListener("touchcancel",this.handleNativeTouchEnd,{capture:!0,passive:!1}),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0),e.removeEventListener("touchstart",this.handleNativeTouchStart,!0),e.removeEventListener("touchmove",this.handleNativeTouchMove,!0),e.removeEventListener("touchend",this.handleNativeTouchEnd,!0),e.removeEventListener("touchcancel",this.handleNativeTouchEnd,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1,this.resetTouchLongPressState()}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.faceIdleOpacity)})}updateClippingBoxFill(){const e=(Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[]).slice(0,6).filter(t=>t instanceof Fn);if(e.length===0){this.clearClippingBoxFill();return}this.engine.clipping?.clippingCSGSimple?.updataFaces?.(e)}clearClippingBoxFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}getFaceTransformOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}keepSingleDirectionArrow(e,t="X"){const n=e.getHelper(),s=[];n.traverse(o=>{if(o?.name!==t||!o.geometry)return;const r=o.geometry;r.boundingBox||r.computeBoundingBox();const A=r.boundingBox;if(!A)return;const a=A.getCenter(new N);if(!(t==="X"&&a.x<0||t==="Y"&&a.y<0||t==="Z"&&a.z<0))return;const c=r.parameters,h=c&&c.radiusTop===0&&c.radiusBottom===.04&&c.height===.1,d=c&&c.radiusTop===.2&&c.radiusBottom===0&&c.height===.6;(h||d)&&s.push(o)}),s.forEach(o=>{o.parent?.remove(o)})}setTransformControlsVisible(e){this.transformControls.forEach(t=>{t.enabled=e}),this.transformHelpers.forEach(t=>{t.visible=e}),this.transformAnchors.forEach(t=>{t.visible=e}),e||(this.engine.controls.enabled=!0)}ensureFaceTransformControl(e){if(this.transformControls.has(e)&&this.transformAnchors.has(e))return;const t=this.engine.renderer?.domElement,n=this.engine.camera;if(!t||!n)return;const s=new Wn;s.name=`SectionBoxTransformAnchor_${e}`,s.visible=this.isActive,this.engine.scene.add(s);const o=new rS(n,t);o.name=`SectionBoxTransformControl_${e}`,o.setMode("translate"),o.setSpace("local"),o.showX=!0,o.showY=!1,o.showZ=!1,o.size=this.transformHandleSize,o.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),o.enabled=this.isActive,o.attach(s),this.keepSingleDirectionArrow(o,"X"),o.addEventListener("dragging-changed",A=>{this.engine.controls.enabled=!A.value,A.value===!0?this.clearClippingBoxFill():this.updateClippingBoxFill()}),o.addEventListener("objectChange",()=>{this.handleTransformObjectChange(e)});const r=o.getHelper();r.userData.excludeFromAmbientOcclusion=!0,r.visible=this.isActive,this.engine.scene.add(r),this.transformAnchors.set(e,s),this.transformControls.set(e,o),this.transformHelpers.set(e,r)}updateFaceTransformControl(e,t,n,s){this.ensureFaceTransformControl(e);const o=this.transformAnchors.get(e),r=this.transformControls.get(e);if(!o||!r)return;const A=this.getFaceTransformOffset(),a=new nn().setFromUnitVectors(new N(1,0,0),t.clone().normalize()),l=n.clone().add(t.clone().setLength(A));this.faceMetaMap.set(e,{normal:t.clone().normalize(),isMinFace:s,center:n.clone()}),this.isSyncingTransform=!0,o.position.copy(l),o.quaternion.copy(a),o.visible=this.isActive,r.object!==o&&r.attach(o),r.enabled=this.isActive;const c=this.transformHelpers.get(e);c&&(c.visible=this.isActive),this.isSyncingTransform=!1}getDominantAxis(e){const t=Math.abs(e.x),n=Math.abs(e.y),s=Math.abs(e.z);return t>=n&&t>=s?"x":n>=t&&n>=s?"y":"z"}handleTransformObjectChange(e){if(this.isSyncingTransform)return;const t=this.transformAnchors.get(e),n=this.faceMetaMap.get(e);if(!t||!n||!this.box||!this.maxBox)return;const s=n.normal,o=this.getDominantAxis(s),r=this.getFaceTransformOffset(),A=s[o],a=t.position[o]-A*r;if(n.isMinFace){const l=this.maxBox.min[o],c=this.box.max[o];this.box.min[o]=Math.max(l,Math.min(c,a))}else{const l=this.box.min[o],c=this.maxBox.max[o];this.box.max[o]=Math.max(l,Math.min(c,a))}this.updata_face(this.box),this.calculate_ratio()}updata_face(e){let t=this.engine.scene.children.find(s=>s.type=="Group"&&s.name=="ClippingBox");t==null&&(t=new qn,t.name="ClippingBox",this.engine.scene.add(t)),[{name:"前",normal:new N(0,0,-1),isMinFace:!0,planePoint:e.min,vertices:[new N(e.min.x,e.max.y,e.min.z),new N(e.max.x,e.max.y,e.min.z),new N(e.max.x,e.min.y,e.min.z),new N(e.min.x,e.min.y,e.min.z)]},{name:"后",normal:new N(0,0,1),isMinFace:!1,planePoint:e.max,vertices:[new N(e.min.x,e.min.y,e.max.z),new N(e.max.x,e.min.y,e.max.z),new N(e.max.x,e.max.y,e.max.z),new N(e.min.x,e.max.y,e.max.z)]},{name:"右",normal:new N(1,0,0),isMinFace:!1,planePoint:e.max,vertices:[new N(e.max.x,e.min.y,e.max.z),new N(e.max.x,e.min.y,e.min.z),new N(e.max.x,e.max.y,e.min.z),new N(e.max.x,e.max.y,e.max.z)]},{name:"左",normal:new N(-1,0,0),isMinFace:!0,planePoint:e.min,vertices:[new N(e.min.x,e.min.y,e.min.z),new N(e.min.x,e.min.y,e.max.z),new N(e.min.x,e.max.y,e.max.z),new N(e.min.x,e.max.y,e.min.z)]},{name:"顶",normal:new N(0,1,0),isMinFace:!1,planePoint:e.max,vertices:[new N(e.min.x,e.max.y,e.max.z),new N(e.max.x,e.max.y,e.max.z),new N(e.max.x,e.max.y,e.min.z),new N(e.min.x,e.max.y,e.min.z)]},{name:"底",normal:new N(0,-1,0),isMinFace:!0,planePoint:e.min,vertices:[new N(e.min.x,e.min.y,e.min.z),new N(e.max.x,e.min.y,e.min.z),new N(e.max.x,e.min.y,e.max.z),new N(e.min.x,e.min.y,e.max.z)]}].forEach(s=>{this.createFace(t,s.vertices,s.normal,s.name,s.isMinFace,s.planePoint)}),b7(this.engine).forEach(s=>{s.material&&Array.isArray(s.material)?s.material.forEach(o=>{o.clippingPlanes=this.engine.sectionPlane}):s.material.clippingPlanes=this.engine.sectionPlane})}createFace(e,t,n,s,o,r){const A=new mi,a=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),l=[0,2,1,0,3,2];A.setAttribute("position",new Bs(a,3)),A.setIndex(l);let c=this.meshs.find(I=>I.name===s);if(c==null){const I=new Ji({color:65280,transparent:!0,opacity:this.faceIdleOpacity,side:An});I.polygonOffset=!0,I.polygonOffsetFactor=1,I.polygonOffsetUnits=4,c=new lt(A,I),c.name=s,e.add(c),this.meshs.push(c)}else c.geometry=A;c.userData={dragNormal:n.clone(),isMinFace:o,faceName:s,excludeFromAmbientOcclusion:!0};const h=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),d=new bo({color:255}),g=new mi;g.setAttribute("position",new Bs(h,3));let u=this.meshs.find(I=>I.name===s+"Line");u==null?(u=new uA(g,d),u.name=s+"Line",e.add(u),this.meshs.push(u)):(u.geometry=g,u.material=d);const p=new N;t.forEach(I=>p.add(I)),p.multiplyScalar(1/t.length),this.updateFaceTransformControl(s,n,p,o);const m=this.engine.sectionPlane.find(I=>I.name==s);m&&m.setFromNormalAndCoplanarPoint(n.clone().setLength(-1),r)}}class ZSe{engine;isActive=!1;isDrag=!1;isCtrlDown=!1;listenersAttached=!1;meshs=[];box=null;pickPoint=null;pickNormal=null;plane=null;angleX=0;angleY=0;angleZ=0;direction=1;normal=new N(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;dragStartCenter=null;idleOpacity=0;hoverOpacity=.05;transformControl=null;transformAnchor=null;transformHelper=null;rotateControl=null;rotateAnchor=null;rotateHelper=null;rotatePivot=null;isSyncingTransformControl=!1;isSyncingRotateControl=!1;activeControlMode=null;moveEpsilon=1e-5;transformHandleSize=1.15;rotateHandleSize=.8;transformHandleColor=255;transformHandleHoverColor=16776960;mobileLongPressDelay=2e3;mobileLongPressMoveTolerance=10;touchLongPressTimer=null;touchLongPressActive=!1;touchStartPosition=null;touchLatestEvent=null;handleNativePointerDown=e=>{if(e.button!==0||!this.isActive)return;this.transformControl?.dragging!==!0&&this.rotateControl?.dragging!==!0&&this.releaseControlModeLock();const t=this.pickControlModeFromPointer(e);t&&this.lockControlMode(t)};handleNativePointerUp=()=>{window.setTimeout(()=>{this.transformControl?.dragging===!0||this.rotateControl?.dragging===!0||this.releaseControlModeLock()},0)};handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),n=t.intersectObjects(this.getInteractiveMeshes(),!1);n.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:n}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),n=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:n})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeTouchStart=e=>{if(!this.isActive||e.touches.length!==1||!this.isMobileDevice()){this.resetTouchLongPressState();return}const t=this.createMouseEventFromTouch(e);if(!t)return;if(this.createRaycasterFromMouseEvent(t).intersectObjects(this.getInteractiveMeshes(),!1).length===0){this.resetTouchLongPressState();return}e.preventDefault(),e.stopImmediatePropagation(),this.resetTouchLongPressState(),this.touchLatestEvent=t,this.touchStartPosition=this.getTouchPoint(e),this.touchLongPressTimer=window.setTimeout(()=>{const o=this.touchLatestEvent;if(!o||!this.isActive)return;const r=this.createRaycasterFromMouseEvent(o),A=r.intersectObjects(this.getInteractiveMeshes(),!1);A.length!==0&&(this.touchLongPressActive=!0,this.handleMouseDown({button:0,raycaster:r,intersects:A}))},this.mobileLongPressDelay)};handleNativeTouchMove=e=>{if(!this.isMobileDevice())return;if(e.touches.length!==1){this.resetTouchLongPressState();return}const t=this.createMouseEventFromTouch(e);if(!t)return;this.touchLatestEvent=t;const n=this.getTouchPoint(e);if(!this.touchLongPressActive&&this.touchStartPosition&&n&&this.touchStartPosition.distanceTo(n)>this.mobileLongPressMoveTolerance&&this.clearTouchLongPressTimer(),!this.touchLongPressActive)return;e.preventDefault(),e.stopImmediatePropagation();const s=this.createRaycasterFromMouseEvent(t),o=s.intersectObjects(this.getInteractiveMeshes(),!1);this.handleMouseMove({raycaster:s,intersects:o})};handleNativeTouchEnd=e=>{this.isMobileDevice()&&(this.clearTouchLongPressTimer(),this.touchLongPressActive&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:0})),this.resetTouchLongPressState())};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};handleTransformObjectChange=()=>{if(this.isSyncingTransformControl||this.activeControlMode==="rotate"||this.rotateControl?.dragging===!0||!this.transformAnchor||!this.center||!this.current_center)return;const e=this.normal.clone().normalize(),t=this.getEffectiveNormal(e),n=this.getDistanceRange(e),s=this.getTransformHandleOffset(),o=this.current_center.clone().sub(this.center).dot(e),r=this.transformAnchor.position.clone().sub(this.center).dot(e)-s*this.getDirectionSign(),A=Math.min(n.max,Math.max(n.min,r));if(Math.abs(A-Number(this.distance))>this.moveEpsilon){const a=this.current_center.clone().add(e.clone().multiplyScalar(A-o));this.updata_face(A,a)}else Math.abs(r-A)>this.moveEpsilon&&this.updateTransformControl(t)};handleRotateObjectChange=()=>{if(this.isSyncingRotateControl||this.activeControlMode==="translate"||this.transformControl?.dragging===!0||!this.rotateAnchor||!this.center||!this.current_center)return;const t=new N(0,0,1).applyQuaternion(this.rotateAnchor.quaternion).normalize().multiplyScalar(this.getDirectionSign()).normalize(),n=(this.rotatePivot??this.rotateAnchor.position??this.current_center).clone(),s=n.clone().sub(this.center).dot(t);t.lengthSq()<=this.moveEpsilon||(this.normal.copy(t),this.updata_face(s,n))};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){this.isActive!=!0&&(this.isActive=!0,this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.attachListeners(),this.ensureTransformControl(),this.ensureRotateControl(),this.setTransformControlVisible(!0),this.applyClippingToModelMeshes(),this.init())}disActive(){this.init(),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.clearClippingFaceFill();const e=this.engine.sectionPlane.find(t=>t.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(n=>{n.name.includes("face")&&(n.visible=!1)})})}init(e){const t=this.engine.octreeBox.getBoundingBox();this.box=t,this.distance=0,this.center=new N((t.min.x+t.max.x)/2,(t.min.y+t.max.y)/2,(t.min.z+t.max.z)/2),this.current_center=this.center.clone(),!e&&this.updata_face(0)}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,t,n){this.angleX=e,this.angleY=t,this.angleZ=n,this.distance=0,this.normal=new N(0,1,0).applyAxisAngle(new N(1,0,0),e).applyAxisAngle(new N(0,0,1),t).applyAxisAngle(new N(0,1,0),n).normalize(),this.updata_face(0),this.updateClippingFaceFill()}setFaceNormal(e,t=0){this.normal=e.clone().normalize(),this.distance=t,this.updata_face(t),this.updateClippingFaceFill()}setFaceNormalPlaneOnly(e,t){if(this.normal=e.clone().normalize(),this.distance=t,!this.center||!this.box)return;const n=this.engine.sectionPlane?.find(s=>s.name==="face");if(n){const s=this.center.clone().add(this.normal.clone().multiplyScalar(t));n.setFromNormalAndCoplanarPoint(this.getEffectiveNormal(),s)}this.updateClippingFaceFill()}activateClippingOnly(){this.isActive||(this.isActive=!0,this.applyClippingToModelMeshes())}reverse(){this.direction=-this.getDirectionSign(),this.applyClippingToModelMeshes(),this.updata_face(this.distance),this.updateClippingFaceFill(),this.requestShadowRefresh()}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e,t){if(!this.box)return;this.distance=e;let n=this.engine.scene.children.find(M=>M.type=="Group"&&M.name=="ClippingBox");n==null&&(n=new qn,n.name="ClippingBox",this.engine.scene.add(n));const s=this.normal.clone().normalize(),o=this.getEffectiveNormal(s),r=this.center??new N((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2);this.center=r.clone();const A=t?.clone()??r.clone().add(s.clone().multiplyScalar(e)),{tangent:a,bitangent:l}=this.getPlaneBasis(s),c=this.getBoxCorners(this.box),h=this.box.min.distanceTo(this.box.max),d=Math.max(h*.02,.01);let g=1/0,u=-1/0,p=1/0,m=-1/0;c.forEach(M=>{const D=M.clone().sub(A),Q=D.dot(a),b=D.dot(l);g=Math.min(g,Q),u=Math.max(u,Q),p=Math.min(p,b),m=Math.max(m,b)}),g-=d,u+=d,p-=d,m+=d;const I=A.clone().add(a.clone().multiplyScalar(g)).add(l.clone().multiplyScalar(p)),B=A.clone().add(a.clone().multiplyScalar(u)).add(l.clone().multiplyScalar(p)),y=A.clone().add(a.clone().multiplyScalar(u)).add(l.clone().multiplyScalar(m)),w=A.clone().add(a.clone().multiplyScalar(g)).add(l.clone().multiplyScalar(m));this.current_center=A.clone(),this.createFace(n,[I,B,y,w],s,"face"),this.updateTransformControl(o),this.updateRotateControl(o)}createFace(e,t,n,s){const o=new mi,r=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),A=this.getEffectiveNormal(n),a=this.getDirectionSign()===1?[0,1,2,0,2,3]:[0,2,1,0,3,2];o.setAttribute("position",new Bs(r,3)),o.setIndex(a),o.computeVertexNormals();let l=this.meshs.find(p=>p.name==s);if(l==null){const p=new Ji({color:65280,transparent:!0,opacity:this.idleOpacity,side:An});p.polygonOffset=!0,p.polygonOffsetFactor=1,p.polygonOffsetUnits=4,l=new lt(o,p),l.name=s,e.add(l),this.meshs.push(l)}else l.geometry=o;l.normal=A.clone(),l.userData.excludeFromAmbientOcclusion=!0;const c=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),h=new bo({color:255}),d=new mi;d.setAttribute("position",new Bs(c,3));let g=this.meshs.find(p=>p.name==s+"Line");g==null?(g=new uA(d,h),g.name=s+"Line",e.add(g),this.meshs.push(g)):(g.geometry=d,g.material=h);const u=this.engine.sectionPlane.find(p=>p.name==s);u&&this.current_center&&u.setFromNormalAndCoplanarPoint(A,this.current_center)}getDirectionSign(){return Number(this.direction)===-1?-1:1}getEffectiveNormal(e=this.normal){return e.clone().normalize().multiplyScalar(this.getDirectionSign())}applyClippingToModelMeshes(){const e=this.engine.sectionPlane?.find?.(t=>t.name==="face");b7(this.engine).forEach(t=>{this.applyClippingToMaterial(t.material),this.engine.clipping.clippingStencil?.addMesh(e,t)}),this.requestShadowRefresh()}applyClippingToMaterial(e){if(Array.isArray(e)){e.forEach(t=>this.applyClippingToMaterial(t));return}e&&(e.clippingPlanes=this.engine.sectionPlane,e.clipShadows=!0,e.shadowSide=An,e.needsUpdate=!0)}requestShadowRefresh(){const e=this.engine?.renderer?.shadowMap;e&&(e.needsUpdate=!0);const t=this.engine?.scene?.dirLight;t?.shadow&&(t.shadow.needsUpdate=!0)}lockControlMode(e){this.activeControlMode=e,this.applyControlModeLock()}releaseControlModeLock(){this.activeControlMode=null,this.applyControlModeLock()}applyControlModeLock(){this.transformControl&&(this.transformControl.enabled=this.isActive&&this.activeControlMode!=="rotate"),this.rotateControl&&(this.rotateControl.enabled=this.isActive&&this.activeControlMode!=="translate")}pickControlModeFromPointer(e){const t=this.raycastTransformControlPicker(this.transformControl,e),n=this.raycastTransformControlPicker(this.rotateControl,e);return t&&n?n.distance<=t.distance?"rotate":"translate":n?"rotate":t?"translate":null}raycastTransformControlPicker(e,t){if(!e||!e.object||!this.engine?.camera||!this.engine?.renderer?.domElement)return null;const n=e._gizmo?.picker?.[e.mode];if(!n)return null;const s=this.engine.renderer.domElement.getBoundingClientRect(),o=new Ne((t.clientX-s.left)/s.width*2-1,-((t.clientY-s.top)/s.height)*2+1),r=new Ao;return r.setFromCamera(o,this.engine.camera),r.intersectObject(n,!0).find(a=>a.object.visible)??null}getPlaneBasis(e){const t=new N(1,0,0),n=new N(0,1,0),s=new N(0,0,1),o=Math.abs(e.dot(t)),r=Math.abs(e.dot(n)),A=Math.abs(e.dot(s));let a=t;r<=o&&r<=A?a=n:A<=o&&A<=r&&(a=s),a=a.clone().sub(e.clone().multiplyScalar(a.dot(e))).normalize();const l=new N().crossVectors(e,a).normalize();return{tangent:a,bitangent:l}}getBoxCorners(e){return[new N(e.min.x,e.min.y,e.min.z),new N(e.min.x,e.min.y,e.max.z),new N(e.min.x,e.max.y,e.min.z),new N(e.min.x,e.max.y,e.max.z),new N(e.max.x,e.min.y,e.min.z),new N(e.max.x,e.min.y,e.max.z),new N(e.max.x,e.max.y,e.min.z),new N(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const t=this.center??new N((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),n=this.getBoxCorners(this.box);let s=1/0,o=-1/0;return n.forEach(r=>{const A=r.clone().sub(t).dot(e);s=Math.min(s,A),o=Math.max(o,A)}),{min:s,max:o}}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}getTransformHandleOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}getPlaneQuaternion(e){const{tangent:t,bitangent:n}=this.getPlaneBasis(e),s=new nt().makeBasis(t,n,e.clone().normalize());return new nn().setFromRotationMatrix(s)}keepSingleDirectionArrow(e,t="X"){const n=e.getHelper(),s=[];n.traverse(o=>{if(o?.name!==t||!o.geometry)return;const r=o.geometry;r.boundingBox||r.computeBoundingBox();const A=r.boundingBox;if(!A)return;const a=A.getCenter(new N);if(!(t==="X"&&a.x<0||t==="Y"&&a.y<0||t==="Z"&&a.z<0))return;const c=r.parameters,h=c&&c.radiusTop===0&&c.radiusBottom===.04&&c.height===.1,d=c&&c.radiusTop===.2&&c.radiusBottom===0&&c.height===.6;(h||d)&&s.push(o)}),s.forEach(o=>{o.parent?.remove(o)})}ensureTransformControl(){if(this.transformControl&&this.transformAnchor)return;const e=this.engine.renderer?.domElement,t=this.engine.camera;if(!e||!t)return;const n=new Wn;n.name="SectionFaceTransformAnchor",n.visible=this.isActive,this.engine.scene.add(n);const s=new rS(t,e);s.name="SectionFaceTransformControl",s.setMode("translate"),s.setSpace("local"),s.showX=!0,s.showY=!1,s.showZ=!1,s.size=this.transformHandleSize,s.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),s.enabled=this.isActive,s.attach(n),this.keepSingleDirectionArrow(s,"X"),s.addEventListener("dragging-changed",r=>{this.engine.controls.enabled=!r.value,r.value===!0?(this.lockControlMode("translate"),this.clearClippingFaceFill()):(this.updateClippingFaceFill(),this.releaseControlModeLock())}),s.addEventListener("objectChange",this.handleTransformObjectChange);const o=s.getHelper();o.userData.excludeFromAmbientOcclusion=!0,o.visible=this.isActive,this.engine.scene.add(o),this.transformAnchor=n,this.transformControl=s,this.transformHelper=o}ensureRotateControl(){if(this.rotateControl&&this.rotateAnchor)return;const e=this.engine.renderer?.domElement,t=this.engine.camera;if(!e||!t)return;const n=new Wn;n.name="SectionFaceRotateAnchor",n.visible=this.isActive,this.engine.scene.add(n);const s=new rS(t,e);s.name="SectionFaceRotateControl",s.setMode("rotate"),s.setSpace("local"),s.showX=!0,s.showY=!0,s.showZ=!1,s.size=this.rotateHandleSize,s.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),s.enabled=this.isActive,s.attach(n),s.addEventListener("dragging-changed",r=>{this.engine.controls.enabled=!r.value,r.value===!0?(this.lockControlMode("rotate"),this.rotatePivot=(this.current_center??this.rotateAnchor?.position??null)?.clone?.()??null,this.clearClippingFaceFill()):(this.rotatePivot=null,this.updateClippingFaceFill(),this.releaseControlModeLock())}),s.addEventListener("objectChange",this.handleRotateObjectChange);const o=s.getHelper();o.userData.excludeFromAmbientOcclusion=!0,o.visible=this.isActive,this.engine.scene.add(o),this.rotateAnchor=n,this.rotateControl=s,this.rotateHelper=o}setTransformControlVisible(e){this.ensureTransformControl(),this.ensureRotateControl(),e||(this.activeControlMode=null),this.transformControl&&(this.transformControl.enabled=e&&this.activeControlMode!=="rotate"),this.transformHelper&&(this.transformHelper.visible=e),this.transformAnchor&&(this.transformAnchor.visible=e),this.rotateControl&&(this.rotateControl.enabled=e&&this.activeControlMode!=="translate"),this.rotateHelper&&(this.rotateHelper.visible=e),this.rotateAnchor&&(this.rotateAnchor.visible=e),e||(this.engine.controls.enabled=!0)}updateTransformControl(e){if(this.ensureTransformControl(),!this.transformControl||!this.transformAnchor||!this.current_center)return;const t=this.getTransformHandleOffset(),n=this.current_center.clone().add(e.clone().setLength(t)),s=new nn().setFromUnitVectors(new N(1,0,0),e.clone().normalize().multiplyScalar(-1));this.isSyncingTransformControl=!0,this.transformAnchor.position.copy(n),this.transformAnchor.quaternion.copy(s),this.transformAnchor.visible=this.isActive,this.transformControl.object!==this.transformAnchor&&this.transformControl.attach(this.transformAnchor),this.applyControlModeLock(),this.transformHelper&&(this.transformHelper.visible=this.isActive),this.isSyncingTransformControl=!1}updateRotateControl(e){this.ensureRotateControl(),!(!this.rotateControl||!this.rotateAnchor||!this.current_center)&&(this.isSyncingRotateControl=!0,this.rotateAnchor.position.copy(this.current_center),this.rotateAnchor.quaternion.copy(this.getPlaneQuaternion(e)),this.rotateAnchor.visible=this.isActive,this.rotateControl.object!==this.rotateAnchor&&this.rotateControl.attach(this.rotateAnchor),this.applyControlModeLock(),this.rotateHelper&&(this.rotateHelper.visible=this.isActive),this.isSyncingRotateControl=!1)}createRaycasterFromMouseEvent(e){const t=new Ao,n=new Ne,s=this.engine.renderer.domElement.clientWidth,o=this.engine.renderer.domElement.clientHeight;return n.x=e.offsetX/s*2-1,n.y=-(e.offsetY/o)*2+1,t.setFromCamera(n,this.engine.camera),t}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getTouchPoint(e){const t=e.touches[0]||e.changedTouches[0];return t?new Ne(t.clientX,t.clientY):null}createMouseEventFromTouch(e){const t=e.touches[0]||e.changedTouches[0],n=this.engine.renderer?.domElement;if(!t||!n)return null;const s=n.getBoundingClientRect();return{offsetX:t.clientX-s.left,offsetY:t.clientY-s.top,clientX:t.clientX,clientY:t.clientY,button:0}}clearTouchLongPressTimer(){this.touchLongPressTimer!=null&&(clearTimeout(this.touchLongPressTimer),this.touchLongPressTimer=null)}resetTouchLongPressState(){this.clearTouchLongPressTimer(),this.touchLongPressActive=!1,this.touchStartPosition=null,this.touchLatestEvent=null}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("pointerdown",this.handleNativePointerDown,!0),e.addEventListener("pointerup",this.handleNativePointerUp,!0),e.addEventListener("pointercancel",this.handleNativePointerUp,!0),e.addEventListener("pointerleave",this.handleNativePointerUp,!0),e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),e.addEventListener("touchstart",this.handleNativeTouchStart,{capture:!0,passive:!1}),e.addEventListener("touchmove",this.handleNativeTouchMove,{capture:!0,passive:!1}),e.addEventListener("touchend",this.handleNativeTouchEnd,{capture:!0,passive:!1}),e.addEventListener("touchcancel",this.handleNativeTouchEnd,{capture:!0,passive:!1}),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("pointerdown",this.handleNativePointerDown,!0),e.removeEventListener("pointerup",this.handleNativePointerUp,!0),e.removeEventListener("pointercancel",this.handleNativePointerUp,!0),e.removeEventListener("pointerleave",this.handleNativePointerUp,!0),e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0),e.removeEventListener("touchstart",this.handleNativeTouchStart,!0),e.removeEventListener("touchmove",this.handleNativeTouchMove,!0),e.removeEventListener("touchend",this.handleNativeTouchEnd,!0),e.removeEventListener("touchcancel",this.handleNativeTouchEnd,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1,this.releaseControlModeLock(),this.resetTouchLongPressState()}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.idleOpacity)})}updateClippingFaceFill(){const e=this.engine.sectionPlane?.find?.(t=>t.name==="face");if(e){this.engine.clipping?.clippingCSGSimple?.updataFace?.(e);return}this.clearClippingFaceFill()}clearClippingFaceFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}handleMouseDown(e){const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0){this.clearClippingFaceFill();const n=t[0],s=n.point.clone();this.isDrag=!0,this.pickPoint=s;const r=(n.face?.normal?.clone()??this.normal.clone()).clone(),A=this.getEffectiveNormal();if(r.dot(A)<0&&r.multiplyScalar(-1),r.normalize(),this.pickNormal=r,this.engine.controls.enabled=!1,this.dragStartDistance=Number(this.distance)||0,this.dragStartCenter=this.current_center?.clone()??null,r.y==0){const a=new Fn;a.setFromNormalAndCoplanarPoint(new N(0,1,0),s),this.plane=a}else{const a=new N(this.engine.camera.position.x,s.y,this.engine.camera.position.z),l=new Fn;l.setFromNormalAndCoplanarPoint(a.clone().sub(s.clone()).setLength(1),s),this.plane=l}}else this.isDrag=!1}handleMouseUp(e,t=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.plane=null,this.dragStartCenter=null,this.engine.controls.enabled=!0,t&&this.updateClippingFaceFill()}handleMouseMove(e){this.resetMeshOpacity();const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);t!=null&&t.length>0&&(t[0].object.material.opacity=this.hoverOpacity);const n=this.pickPoint,s=this.pickNormal,o=this.plane;if(n!=null&&s!=null&&o!=null){const r=new N;if(e.raycaster.ray.intersectPlane(o,r)){const A=r.clone().sub(n.clone()).dot(s.clone()),a=this.getDistanceRange(this.normal.clone().normalize()),l=s.dot(this.normal.clone().normalize())>=0?1:-1,c=this.dragStartDistance+A*l;this.distance=Math.min(a.max,Math.max(a.min,c));const h=(this.dragStartCenter??this.current_center)?.clone().add(this.normal.clone().normalize().multiplyScalar(this.distance-this.dragStartDistance));this.updata_face(this.distance,h)}}}}class JSe{engine;callback_;isActive;constructor(e){this.engine=e}init(){this.isActive=!0,this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}cancel(){this.isActive&&(this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.isActive=!1)}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){if(e.catch?.normal==null&&(e.catch.normal=e.catch.face?.normal),!e.catch?.normal||!e.catch?.point)return;let t=e.catch.normal.setLength(-1);this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.isActive=!1,this.callback_({dir:t,position:e.catch.point})}}function zSe(i){const e=Object.create(i);return e.scene=i.composerModule?.postProcessingOverlayScene??i.scene,e}function HSe(i){i.getObjectByName("ClippingBox")?.traverse(t=>{t.castShadow=!1,t.receiveShadow=!1,t.userData.excludeFromAmbientOcclusion=!0,(Array.isArray(t.material)?t.material:t.material?[t.material]:[]).forEach(s=>{s.depthWrite=!1,s.depthTest=!1,s.toneMapped=!1,s.needsUpdate=!0})})}class BMt{planes;mode="";fillCutFace=!0;engine;constructor(e,t){this.engine=e,this.planes=t}apply(){const e=this.getActivePlanes(),t=[],n=new Set;this.engine.scene.traverse(s=>{!s.isGroup||s===this.engine.scene||n.has(s.uuid)||(s.userData?.__isModelUrlGroup===!0||this.engine.models?.some(o=>o.group===s))&&(n.add(s.uuid),t.push(s))}),t.forEach(s=>{const o=zR(s,e);o.clipShadows=!0}),this.engine.composerModule?.markSceneDirty?.(),this.engine.requestComposerRender?.()}clear(){this.mode="",this.planes.forEach(e=>e.constant=1e5),this.apply()}getActivePlanes(){return this.mode==="box"||this.mode==="viewRange"?this.planes.slice(0,6):this.mode==="x"||this.mode==="y"||this.mode==="z"||this.mode==="face"?[this.planes[6]]:[]}}class yMt extends VSe{webgpuState;interactionScene;constructor(e,t){const n=zSe(e);super(n),this.webgpuState=t,this.interactionScene=n.scene}updata_face(e){super.updata_face(e),HSe(this.interactionScene),this.webgpuState.apply()}dispose(){this.disActive(),this.transformControls?.forEach(r=>r.dispose?.());const t=this.engine?.scene;t?.getObjectByName("ClippingBox")?.removeFromParent();const n=this.transformHelpers,s=this.transformAnchors;n?.forEach(r=>r.removeFromParent()),s?.forEach(r=>r.removeFromParent());const o=[];t?.traverse(r=>{(r.name.startsWith("SectionBoxTransformAnchor_")||r.name.startsWith("SectionBoxTransformControl_"))&&o.push(r)}),o.forEach(r=>r.removeFromParent()),this.webgpuState.apply()}}class wMt extends ZSe{webgpuState;interactionScene;constructor(e,t){const n=zSe(e);super(n),this.webgpuState=t,this.interactionScene=n.scene}updata_face(e,t){super.updata_face(e,t),HSe(this.interactionScene),this.webgpuState.apply()}dispose(){this.disActive(),this.transformControl?.dispose?.(),this.rotateControl?.dispose?.();const e=this.engine?.scene;e?.getObjectByName("ClippingBox")?.removeFromParent(),this.transformHelper?.removeFromParent?.(),this.rotateHelper?.removeFromParent?.(),this.transformAnchor?.removeFromParent?.(),this.rotateAnchor?.removeFromParent?.();const t=[];e?.traverse(n=>{(n.name==="SectionFaceTransformAnchor"||n.name==="SectionFaceRotateAnchor"||n.name==="SectionFaceTransformControl"||n.name==="SectionFaceRotateControl")&&t.push(n)}),t.forEach(n=>n.removeFromParent()),this.webgpuState.apply()}}class bMt extends JSe{}function QMt(){return{clear(){},updataFace(){},updataFaces(){}}}let MMt=class{engine;state;viewRangePlanes=null;sectionPlane;sectionBox;sectionFace;clippingStencil=null;clippingCSGSimple;currentClippingMode="";sectionCatchFace;fillCutFace=!0;constructor(e){this.engine=e,this.sectionPlane=[new Fn(new N(1,0,0),1e5),new Fn(new N(-1,0,0),1e5),new Fn(new N(0,1,0),1e5),new Fn(new N(0,-1,0),1e5),new Fn(new N(0,0,1),1e5),new Fn(new N(0,0,-1),1e5),new Fn(new N(0,0,1),1e5)],this.sectionPlane.forEach((t,n)=>{t.name=["前","左","后","右","顶","底","face"][n]}),this.engine.sectionPlane=this.sectionPlane,this.state=new BMt(e,this.sectionPlane),this.engine.__getActiveWebGPUClippingPlanes=()=>this.state.getActivePlanes(),this.sectionBox=new yMt(e,this.state),this.sectionFace=new wMt(e,this.state),this.sectionCatchFace=new bMt(e),this.clippingCSGSimple=QMt()}init(){this.state.apply()}scaleBox(){const e=this.engine.octreeBox?.getBoundingBox?.();e&&this.sectionBox.setBox(e)}setFillCutFace(e){this.fillCutFace=e,this.state.fillCutFace=e}getFillCutFace(){return this.fillCutFace}clippingModel(e){const t=(e??[]).flatMap(s=>{const o=this.engine.models?.find(r=>r.url===s.url);return(s.ids??[]).flatMap(r=>o?.nodesMap?.get(r)?.infos?.map(A=>A.box)??[])});if(!t.length)return;const n=new Wt;t.forEach(s=>{s?.min&&s?.max&&n.union(new Wt(new N(s.min.x,s.min.y,s.min.z),new N(s.max.x,s.max.y,s.max.z)))}),n.isEmpty()||(n.expandByScalar(.1),this.active("box"),this.sectionBox.setBox(n))}updateClippingValue(e){const t=this.sectionBox.maxBox;!t||!e||this.sectionBox.setboxXyz({minX:Ai.lerp(t.min.x,t.max.x,e.x.min*.01),minY:Ai.lerp(t.min.y,t.max.y,e.y.min*.01),minZ:Ai.lerp(t.min.z,t.max.z,e.z.min*.01),maxX:Ai.lerp(t.min.x,t.max.x,e.x.max*.01),maxY:Ai.lerp(t.min.y,t.max.y,e.y.max*.01),maxZ:Ai.lerp(t.min.z,t.max.z,e.z.max*.01)})}active(e){if(this.sectionCatchFace.cancel(),this.sectionBox.disActive(),this.sectionFace.disActive(),this.currentClippingMode=e,this.state.mode=e,this.engine.engineStatus&&(this.engine.engineStatus.isForceFree=!0),e==="box")this.sectionBox.active();else if(e==="x"||e==="y"||e==="z"){this.sectionFace.direction=1;const t={x:new N(-1,0,0),y:new N(0,0,-1),z:new N(0,-1,0)};this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(t[e])}else e==="face"&&(this.sectionFace.direction=1,this.sectionCatchFace.init(),this.sectionCatchFace.catch_face(t=>{const s=this.engine.octreeBox?.getBoundingBox?.()?.getCenter?.(new N)??new N,o=t.position.clone().sub(s).dot(t.dir);this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(t.dir,o),this.currentClippingMode="face",this.state.mode="face"}));this.state.apply()}disabled(){this.currentClippingMode==="viewRange"?this.state.clear():this.currentClippingMode==="box"?(this.sectionBox.disabled(),this.state.clear()):(this.sectionFace.disabled(),this.state.clear()),this.engine.engineStatus&&(this.engine.engineStatus.isForceFree=!1)}recover(){if(this.currentClippingMode==="viewRange"&&this.viewRangePlanes){this.viewRangePlanes.forEach((e,t)=>this.sectionPlane[t].copy(e)),this.state.mode="viewRange",this.state.apply();return}this.state.mode=this.currentClippingMode,this.state.apply(),this.currentClippingMode==="box"?this.sectionBox.recover():this.currentClippingMode&&this.sectionFace.recover()}reverse(){["x","y","z","face"].includes(this.currentClippingMode)&&this.sectionFace.reverse()}disActive(){this.sectionBox.disActive(),this.sectionFace.disActive(),this.sectionCatchFace.cancel(),this.viewRangePlanes=null,this.state.clear(),this.currentClippingMode="",this.engine.engineStatus&&(this.engine.engineStatus.isForceFree=!1)}dispose(){this.disActive(),this.sectionBox.dispose(),this.sectionFace.dispose(),this.engine.__getActiveWebGPUClippingPlanes&&delete this.engine.__getActiveWebGPUClippingPlanes}isPointInClippingRange(e,t=1e-4){return e?this.state.getActivePlanes().every(n=>n.distanceToPoint(e)>=-t):!1}filterIntersectionsByClipping(e,t=1e-4){return(e??[]).filter(n=>this.isPointInClippingRange(n.point,t))}doesBoxIntersectClippingRange(e,t=1e-4){const n=this.toBox3(e);return!n||n.isEmpty()?!1:this.state.getActivePlanes().every(s=>{const o=new N(s.normal.x>=0?n.max.x:n.min.x,s.normal.y>=0?n.max.y:n.min.y,s.normal.z>=0?n.max.z:n.min.z);return s.distanceToPoint(o)>=-t})}getClippedBoundingBox(e){const t=this.toBox3(e??this.engine.octreeBox?.getBoundingBox?.());if(!t||t.isEmpty())return null;const n=this.state.getActivePlanes();if(!n.length)return t.clone();const s=this.getBoxBoundaryPlanes(t).concat(n),o=[];for(let r=0;r<s.length-2;r+=1)for(let A=r+1;A<s.length-1;A+=1)for(let a=A+1;a<s.length;a+=1){const l=this.intersectThreePlanes(s[r],s[A],s[a]);l&&s.every(c=>c.distanceToPoint(l)>=-1e-6)&&o.push(l)}return o.length?new Wt().setFromPoints(o):null}setSectionByView(e,t){const n=this.engine.octreeBox?.getBoundingBox?.();if(!n)return;this.sectionBox.disActive(),this.sectionFace.disActive(),this.scaleBox();const s=n.getCenter(new N),o=new N(t.x,t.y,t.z).normalize().negate(),r=new N(e.x,e.y,e.z).sub(s).dot(o);this.sectionFace.init(!0),this.sectionFace.setFaceNormalPlaneOnly(o,r),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face",this.state.mode="face"}setSectionPlanesByViewRange(e){!Array.isArray(e)||e.length!==6||(this.sectionBox.disActive(),this.sectionFace.disActive(),this.sectionCatchFace.cancel(),this.viewRangePlanes=e.map(t=>t.clone()),this.viewRangePlanes.forEach((t,n)=>this.sectionPlane[n].copy(t)),this.sectionPlane[6].constant=1e5,this.currentClippingMode="viewRange",this.state.mode="viewRange",this.state.apply(),this.engine.engineStatus&&(this.engine.engineStatus.isForceFree=!0))}toBox3(e){return!e?.min||!e?.max?null:e instanceof Wt?e.clone():new Wt(new N(e.min.x,e.min.y,e.min.z),new N(e.max.x,e.max.y,e.max.z))}getBoxBoundaryPlanes(e){return[new Fn(new N(1,0,0),-e.min.x),new Fn(new N(-1,0,0),e.max.x),new Fn(new N(0,1,0),-e.min.y),new Fn(new N(0,-1,0),e.max.y),new Fn(new N(0,0,1),-e.min.z),new Fn(new N(0,0,-1),e.max.z)]}intersectThreePlanes(e,t,n){const s=new N().crossVectors(e.normal,t.normal),o=s.dot(n.normal);return Math.abs(o)<1e-8?null:new N().crossVectors(t.normal,n.normal).multiplyScalar(-e.constant).add(new N().crossVectors(n.normal,e.normal).multiplyScalar(-t.constant)).add(s.multiplyScalar(-n.constant)).divideScalar(o)}},DMt=class{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return(this.engine?.models??[]).forEach(n=>{e.push({children:n.modelTree?.modelTreeLevel,name:n.baseInfo?.name,url:n.url})}),e}getTypeTreeData(){let e=[];return(this.engine?.models??[]).forEach(n=>{e.push({children:n.modelTree?.modelTreeType,name:n.baseInfo?.name,url:n.url})}),e}getMajorTreeData(){let e=[];return(this.engine?.models??[]).forEach(n=>{e.push({children:n.modelTree?.modelTreeMajor,name:n.baseInfo?.name,url:n.url})}),e}},SMt=class{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,n=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(s=>{if(s instanceof lt){const o=s.geometry;if(o&&o.attributes){const r=o.attributes.position;if(r){const A=r.count;e+=A;let a=0;o.index?a=o.index.count/3:a=A/3,t+=a}}}}),(this.engine?.models??[]).forEach(s=>{n=n+s.nodesMap.size}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:n})}};const xMt='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="10.8" cy="10.8" r="6.5" stroke="currentColor" stroke-width="2"/><path d="m16 16 4.3 4.3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';let TMt=class{manager;wrapper;input;status;list;pagination;results=[];activeIndex=-1;currentPage=1;pageSize=20;debounceTimer=null;constructor(e,t){this.manager=t,this.wrapper=document.createElement("div"),this.wrapper.className="engine-3d-search",this.wrapper.innerHTML=`
4932
+ }`},v=new nr({name:S.name,uniforms:Oc.clone(S.uniforms),vertexShader:S.vertexShader,fragmentShader:S.fragmentShader,lights:!0,side:p,fog:m});v.uniforms.mirrorSampler.value=C.texture,v.uniforms.textureMatrix.value=T,v.uniforms.alpha.value=A,v.uniforms.time.value=a,v.uniforms.normalSampler.value=l,v.uniforms.sunColor.value=h,v.uniforms.waterColor.value=d,v.uniforms.sunDirection.value=c,v.uniforms.distortionScale.value=u,v.uniforms.eye.value=g,n.material=v,n.onBeforeRender=function(Y,k,j){if(y.setFromMatrixPosition(n.matrixWorld),w.setFromMatrixPosition(j.matrixWorld),M.extractRotation(n.matrixWorld),B.set(0,0,1),B.applyMatrix4(M),b.subVectors(y,w),b.dot(B)>0)return;b.reflect(B).negate(),b.add(y),M.extractRotation(j.matrixWorld),D.set(0,0,-1),D.applyMatrix4(M),D.add(w),P.subVectors(y,D),P.reflect(B).negate(),P.add(y),x.position.copy(b),x.up.set(0,1,0),x.up.applyMatrix4(M),x.up.reflect(B),x.lookAt(P),x.far=j.far,x.updateMatrixWorld(),x.projectionMatrix.copy(j.projectionMatrix),T.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),T.multiply(x.projectionMatrix),T.multiply(x.matrixWorldInverse),I.setFromNormalAndCoplanarPoint(B,y),I.applyMatrix4(x.matrixWorldInverse),Q.set(I.normal.x,I.normal.y,I.normal.z,I.constant);const R=x.projectionMatrix;F.x=(Math.sign(Q.x)+R.elements[8])/R.elements[0],F.y=(Math.sign(Q.y)+R.elements[9])/R.elements[5],F.z=-1,F.w=(1+R.elements[10])/R.elements[14],Q.multiplyScalar(2/Q.dot(F)),R.elements[2]=Q.x,R.elements[6]=Q.y,R.elements[10]=Q.z+1-r,R.elements[14]=Q.w,g.setFromMatrixPosition(j.matrixWorld);const U=Y.getRenderTarget(),O=Y.xr.enabled,V=Y.shadowMap.autoUpdate;n.visible=!1,Y.xr.enabled=!1,Y.shadowMap.autoUpdate=!1,Y.setRenderTarget(C),Y.state.buffers.depth.setMask(!0),Y.autoClear===!1&&Y.clear(),Y.render(k,x),n.visible=!0,Y.xr.enabled=O,Y.shadowMap.autoUpdate=V,Y.setRenderTarget(U);const $=j.viewport;$!==void 0&&Y.state.viewport($)}}}const NSe="0",YSe=0,GSe=!1;let LQt=class J6e{engine;currentId=NSe;groundGroup;groundMesh=null;isWaterAddon=!1;groundY=YSe;static DEFAULT_WATER_NORMALS="/texture/waternormals.jpg";groundList=[{id:"0",names:["无","無","None"]},{id:"1",names:["草地1","草地1","Grass 1"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass01.jpg"},{id:"2",names:["草地2","草地2","Grass 2"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass02.jpg"},{id:"3",names:["草地3","草地3","Grass 3"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass03.jpg"},{id:"4",names:["草地4","草地4","Grass 4"],color:4881486,roughness:.9,metalness:0,map:"/texture/ground/grass04.jpg"},{id:"5",names:["混凝土1","混凝土1","Concrete 1"],color:15790320,roughness:.85,metalness:.1,map:"/texture/ground/concrete01.jpg"},{id:"5",names:["混凝土1","混凝土1","Concrete 1"],color:15790320,roughness:.85,metalness:.1,map:"/texture/ground/concrete02.jpg"},{id:"6",names:["马路1","馬路1","Road 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/road01.jpg"},{id:"7",names:["马路2","馬路2","Road 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/road02.jpg"},{id:"8",names:["泥土1","泥土1","Soil 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/tiles01.jpg"},{id:"9",names:["泥土2","泥土2","Soil 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/tiles02.jpg"},{id:"10",names:["木板","木板","Wood Board"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/wood01.jpg"},{id:"11",names:["地砖1","地磚1","Floor Tile 1"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/z01.jpg"},{id:"12",names:["地砖2","地磚2","Floor Tile 2"],color:15790320,roughness:.55,metalness:.1,map:"/texture/ground/z02.jpg"},{id:"13",names:["湖面","湖面","Lake Surface"],water:!0,waterColor:5929582,distortionScale:2.5,size:1},{id:"14",names:["海面","海面","Sea Surface"],water:!0,waterColor:28062,distortionScale:3.7,size:1}];constructor(e){this.engine=e,this.groundGroup=new qn,this.groundGroup.name="groundGroup"}init(){this.engine.scene.add(this.groundGroup),this.groundGroup.visible=GSe}setGround(e,t){if(this._dispose(),this.currentId=e,e==="0")return;const n=this.groundList.find(o=>o.id===e);debugger;if(!n)return;const s=t?.size??3e4;if(n.water){const o=new gd(s,s),r=t?.waterNormalsUrl??bn(J6e.DEFAULT_WATER_NORMALS,typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href),A=new Kc().load(r,g=>{g.wrapS=g.wrapT=Sr}),a=t?.sunDirection??new N(.5,.8,.5).normalize(),l=t?.distortionScale??n.distortionScale??3.7,c=t?.waterSize??n.size??1,h=t?.opacity??.92,d=new RSe(o,{textureWidth:512,textureHeight:512,waterNormals:A,sunDirection:a.clone(),sunColor:16777215,waterColor:n.waterColor??28062,distortionScale:l,alpha:h,fog:!!this.engine.scene?.fog});d.rotation.x=-Math.PI/2,d.position.y=-.01,d.name="groundMesh",d.receiveShadow=!0,d.castShadow=!1,this.ensureWaterShadowUniforms(d.material),d.material.uniforms.size.value=c,this.groundMesh=d,this.isWaterAddon=!0,this.groundGroup.add(d)}else{const o=new gd(s,s,1,1);o.rotateX(-Math.PI/2);const r=new O0({color:n.color,roughness:n.roughness,metalness:n.metalness}),A=t?.textureUrl??(n.map?bn(n.map,typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href):void 0);A&&new Kc().load(A,l=>{l.wrapS=l.wrapT=Sr,l.repeat.set(1e4,1e4),r.map=l,r.needsUpdate=!0},void 0,()=>{});const a=new lt(o,r);a.name="groundMesh",a.receiveShadow=!0,a.castShadow=!1,a.position.y=-.01,this.groundMesh=a,this.isWaterAddon=!1,this.groundGroup.add(a)}this.groundGroup.position.y=this.groundY}setHeight(e){this.groundY=e,this.groundGroup.position.y=e}getHeight(){return this.groundY}update(){if(!this.groundMesh||!this.isWaterAddon)return;const t=this.groundMesh.material?.uniforms;if(!t)return;t.time.value+=1/60;const n=this.engine.scene?.dirLight;n&&t.sunDirection&&t.sunDirection.value.copy(n.position).normalize();const s=this.engine.camera;s&&t.eye&&t.eye.value.setFromMatrixPosition(s.matrixWorld)}getGroundList(){return this.groundList.map(({id:e,names:t})=>({id:e,names:t}))}getCurrentId(){return this.currentId}getVisible(){return this.groundGroup.visible}show(){this.groundGroup.visible=!0}hide(){this.groundGroup.visible=!1}dispose(){this._dispose(),this.engine.scene.remove(this.groundGroup)}ensureWaterShadowUniforms(e){const t=e.uniforms;t.directionalShadowMap||(t.directionalShadowMap={value:[]}),t.spotShadowMap||(t.spotShadowMap={value:[]}),t.pointShadowMap||(t.pointShadowMap={value:[]}),e.uniformsNeedUpdate=!0}_dispose(){if(!this.groundMesh)return;this.groundMesh.geometry.dispose();const e=this.groundMesh.material;Array.isArray(e)?e.forEach(t=>t.dispose()):e.dispose(),this.groundGroup.remove(this.groundMesh),this.groundMesh=null,this.isWaterAddon=!1}};const SB="0",KQt=!0,Lte=.2,Kte=1,XQt=.35;let VQt=class{engine;currentHdrId=SB;isVisible=KQt;currentIntensity=Lte;currentBackgroundIntensity=Kte;currentTexture=null;currentEnvironmentTexture=null;skybox=null;textureCache=new Map;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousAmbientLightIntensity=1;previousToneMapping=Yr;previousToneMappingExposure=1;hdrList=[{id:"0",names:["无","無","None"]},{id:"1",names:["纯净-多云","純淨-多雲","Pure - Cloudy"],url:"assets/hdr/1.hdr"},{id:"2",names:["纯净-落日","純淨-落日","Pure - Sunset"],url:"assets/hdr/2.hdr"},{id:"3",names:["纯净-少云","純淨-少雲","Pure - Few Clouds"],url:"assets/hdr/3.hdr"},{id:"4",names:["纯净-无云","純淨-無雲","Pure - Cloudless"],url:"assets/hdr/4.hdr"},{id:"5",names:["纯净-夜晚","純淨-夜晚","Pure - Night"],url:"assets/hdr/5.hdr"},{id:"6",names:["纯净-阴天","純淨-陰天","Pure - Overcast"],url:"assets/hdr/6.hdr"},{id:"7",names:["纯净-中云","純淨-中雲","Pure - Partly Cloudy"],url:"assets/hdr/7.hdr"},{id:"8",names:["废弃机场","廢棄機場","Abandoned Airport"],url:"assets/hdr/8.hdr"},{id:"9",names:["户外-无云","戶外-無雲","Outdoor - Cloudless"],url:"assets/hdr/9.hdr"},{id:"10",names:["郊区花园","郊區花園","Suburban Garden"],url:"assets/hdr/10.hdr"},{id:"11",names:["室内工作室01","室內工作室01","Indoor Studio 01"],url:"assets/hdr/11.hdr"},{id:"12",names:["室内工作室02","室內工作室02","Indoor Studio 02"],url:"assets/hdr/12.hdr"},{id:"13",names:["室内工作室03","室內工作室03","Indoor Studio 03"],url:"assets/hdr/13.hdr"},{id:"14",names:["室内工作室04","室內工作室04","Indoor Studio 04"],url:"assets/hdr/14.hdr"},{id:"15",names:["小镇教堂","小鎮教堂","Town Church"],url:"assets/hdr/15.hdr"},{id:"16",names:["小镇街道","小鎮街道","Town Street"],url:"assets/hdr/16.hdr"},{id:"17",names:["夜晚街道","夜晚街道","Night Street"],url:"assets/hdr/17.hdr"},{id:"99",names:["默认","默认","default"],url:"assets/hdr/99.hdr"}];constructor(e){this.engine=e}getHdrList(){return this.hdrList}async setHdr(e){const t=this.hdrList.find(n=>n.id===e);if(!t){console.warn(`[Hdr] HDR id "${e}" not found`);return}if(e===SB||!t.url){this._clearHdr(),this.currentHdrId=SB,this._requestRender();return}if(this.textureCache.has(e)){this._applyTexture(this.textureCache.get(e)),this.currentHdrId=e,this._requestRender();return}try{const n=await this._loadHdr(t.url);this.textureCache.set(e,n),this._applyTexture(n),this.currentHdrId=e,this._requestRender()}catch(n){console.error(`[Hdr] Failed to load HDR "${t.url}":`,n)}}setVisible(e){this.isVisible=e,this.skybox&&(this.skybox.visible=e),this.engine.scene&&this.currentTexture&&(this.engine.scene.background=e?this.currentTexture:this.previousBackground,this.engine.scene.backgroundIntensity=e?this.currentBackgroundIntensity:this.previousBackgroundIntensity,this.engine.composerModule?.rebuild?.()),this._requestRender()}getCurrentHdrId(){return this.currentHdrId}getVisible(){return this.isVisible}setIntensity(e){this.currentIntensity=e,this.engine.scene&&(this.engine.scene.environmentIntensity=e,this._requestRender())}setBackgroundIntensity(e){this.currentBackgroundIntensity=Math.max(e,0),this.engine.scene&&(this.engine.scene.backgroundIntensity=this.currentBackgroundIntensity,this._updateSkyboxIntensity(),this._requestRender())}getIntensity(){return this.currentIntensity}getBackgroundIntensity(){return this.currentBackgroundIntensity}addHdrItem(e){const t=this.hdrList.find(n=>n.id===e.id);t?Object.assign(t,e):this.hdrList.push(e)}dispose(){this._clearHdr(),this.textureCache.forEach(e=>e.dispose()),this.textureCache.clear()}_loadHdr(e){const t=bn(e,typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href);return new Promise((n,s)=>{new PSe().load(t,o=>{o.mapping=mm,n(o)},void 0,o=>s(o))})}_applyTexture(e){if(this.currentTexture=e,!this.engine.scene||!this.engine.renderer)return;this._captureSceneState(),this.currentEnvironmentTexture?.dispose();const t=new _6(this.engine.renderer),n=t.fromEquirectangular(e).texture;t.dispose(),this.currentEnvironmentTexture=n,this.engine.scene.background=this.isVisible?e:this.previousBackground,this.engine.scene.backgroundIntensity=this.isVisible?this.currentBackgroundIntensity:this.previousBackgroundIntensity,this.engine.scene.environment=n,this.engine.scene.environmentIntensity=this.currentIntensity,this.engine.renderer.toneMapping=v0,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure>0?this.previousToneMappingExposure:Ute,this._removeSkybox(),this._createSkybox(e),this._setAmbientLightIntensity(this._getHdrAmbientLightIntensity()),this.engine.composerModule?.rebuild?.()}_captureSceneState(){this.currentHdrId!==SB||!this.engine.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousAmbientLightIntensity=this._getAmbientLightIntensity(),this.previousToneMapping=this.engine.renderer?.toneMapping??Yr,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1)}_createSkybox(e){if(!this.engine.scene)return;const t=new Wc(1e3,64,32),n=new Ji({map:e,side:$s,depthWrite:!1,depthTest:!1,fog:!1,toneMapped:!0});this.skybox=new lt(t,n),this.skybox.name="hdr_skybox",this.skybox.renderOrder=-1e3,this.skybox.frustumCulled=!1,this.skybox.visible=this.isVisible,this.skybox.onBeforeRender=(s,o,r)=>{this.skybox?.position.copy(r.position)},this._updateSkyboxIntensity(),this.engine.scene.add(this.skybox)}_updateSkyboxIntensity(){if(!this.skybox)return;this.skybox.material.color.setScalar(Math.max(this.currentBackgroundIntensity,.001))}_removeSkybox(){!this.skybox||!this.engine.scene||(this.engine.scene.remove(this.skybox),this.skybox.geometry.dispose(),this.skybox.material.dispose(),this.skybox=null)}_clearHdr(){this.currentTexture=null,this._removeSkybox(),this.engine.scene&&(this.currentEnvironmentTexture?.dispose(),this.currentEnvironmentTexture=null,this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this._setAmbientLightIntensity(this.previousAmbientLightIntensity),this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousAmbientLightIntensity=1,this.previousToneMapping=Yr,this.previousToneMappingExposure=1)}_getAmbientLightIntensity(){return this.engine.scene?.children.find(t=>t instanceof np)?.intensity??1}_setAmbientLightIntensity(e){const t=this.engine.scene?.children.find(n=>n instanceof np);t&&(t.intensity=e)}_getHdrAmbientLightIntensity(){return Math.max(this.previousAmbientLightIntensity*XQt,0)}_requestRender(){this.engine?.requestComposerRender?.()}};const ZQt=.001,jSe=!1,JQt=[{Id:"339",Name:"L1",Elevation:-.32808398950131235},{Id:"2787",Name:"L2",Elevation:16.896325459317584},{Id:"236633",Name:"L3",Elevation:36.745406824146976}];let zQt=class{engine;isVisible=jSe;levels=[];svgContainer=null;svgOverlay=null;worldToScreen=null;halfSize=500;COLOR="#1890ff";PLANE_OPACITY=.08;constructor(e){this.engine=e,this._initSvg()}setData(e=[],t){this._clearAll(),this.levels=e.map(s=>({data:s,group:null,svgGroup:null}));const n=t??this.getMergedBoundingBox();this.levels.forEach(s=>this._buildThreeObject(s,n))}setMockData(){const e=this.engine.models?.[0]?.levels,t=this.engine.models?.[0]?.boundingBox;this.setData(Array.isArray(e)&&e.length>0?e:JQt,t)}show(){this.isVisible=!0,this.svgContainer&&(this.svgContainer.style.display="block"),this.levels.forEach(e=>{e.group&&(e.group.visible=!0)})}hide(){this.isVisible=!1,this.svgContainer&&(this.svgContainer.style.display="none"),this.levels.forEach(e=>{e.group&&(e.group.visible=!1)})}toggle(){if(this.isVisible){this.hide();return}this.show()}getVisible(){return this.isVisible}update(){!this.isVisible||!this.svgOverlay||this.levels.length===0||!this.engine.camera||!this.engine.renderer||(this._initWorldToScreen(),this.levels.forEach(e=>this._updateSvgLabels(e)))}getLocationByPoint(e,t){const{url:n,targetPoint:s}=this.resolvePointLookupArgs(e,t),o=this.getLevelData(n).slice().sort((g,u)=>g.Elevation-u.Elevation);if(o.length===0)return null;const r=(s instanceof N,s.y),A=o.find(g=>Math.abs(g.Elevation-r)<=ZQt)??null;if(A)return{pointY:r,description:`${A.Name}`,currentLevel:A,lowerLevel:A,upperLevel:A,isOnLevel:!0,isInside:!0};let a=null,l=null;o.forEach(g=>{if(g.Elevation<r){a=g;return}l||(l=g)});const c=this.pickNearestLevel(r,a,l),h=c?`标高${c.Name}`:"";let d=!1;return a&&l&&(d=!0),{pointY:r,description:h,currentLevel:c,lowerLevel:a,upperLevel:l,isOnLevel:!1,isInside:d}}dispose(){this._clearAll(),this.svgContainer&&(this.svgContainer.remove(),this.svgContainer=null),this.svgOverlay=null,this.worldToScreen=null}_initSvg(){this.svgContainer=document.createElement("div"),this.svgContainer.style.position="absolute",this.svgContainer.style.top="0",this.svgContainer.style.left="0",this.svgContainer.style.width="100%",this.svgContainer.style.height="100%",this.svgContainer.style.pointerEvents="none",this.svgContainer.style.overflow="hidden",this.svgContainer.style.display="none",this.engine.container.appendChild(this.svgContainer),this.svgOverlay=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.svgOverlay.style.position="absolute",this.svgOverlay.style.top="0",this.svgOverlay.style.left="0",this.svgOverlay.style.width="1920px",this.svgOverlay.style.height="1080px",this.svgOverlay.style.overflow="visible",this.svgContainer.appendChild(this.svgOverlay)}_initWorldToScreen(){this.engine.camera&&this.engine.renderer&&this.engine.scene&&(this.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene))}_clearAll(){this.levels.forEach(e=>{e.group&&this.engine.scene&&(this.engine.scene.remove(e.group),e.group.traverse(t=>{t.geometry&&t.geometry.dispose(),t.material&&(Array.isArray(t.material)?t.material.forEach(n=>n.dispose()):t.material.dispose())}),e.group=null),e.svgGroup&&(e.svgGroup.remove(),e.svgGroup=null)}),this.levels=[]}_buildThreeObject(e,t){if(!this.engine.scene)return;const n=new N(t.min.x,t.min.y,t.min.z),s=new N(t.max.x,t.max.y,t.max.z);this.halfSize=s.distanceTo(n);const o=e.data.Elevation,r=new qn,A=new gd(this.halfSize*2,this.halfSize*2);A.rotateX(-Math.PI/2);const a=new Ji({color:this.COLOR,transparent:!0,opacity:this.PLANE_OPACITY,side:An,depthWrite:!1}),l=new lt(A,a);l.position.y=o,r.add(l);const c=[new N(-this.halfSize,o,-this.halfSize),new N(this.halfSize,o,-this.halfSize),new N(this.halfSize,o,this.halfSize),new N(-this.halfSize,o,this.halfSize),new N(-this.halfSize,o,-this.halfSize)],h=new mi().setFromPoints(c),d=new bo({color:this.COLOR,transparent:!0,opacity:.7});if(r.add(new uA(h,d)),r.visible=this.isVisible,this.engine.scene.add(r),e.group=r,this.svgOverlay){const g=document.createElementNS("http://www.w3.org/2000/svg","g");g.dataset.levelId=e.data.Id;for(let u=0;u<4;u+=1)g.appendChild(this._makeLabel(e.data.Name,e.data.Elevation));this.svgOverlay.appendChild(g),e.svgGroup=g}}_updateSvgLabels(e){if(!e.svgGroup||!this.worldToScreen)return;const t=e.data.Elevation,n=[new N(-this.halfSize,t,-this.halfSize),new N(this.halfSize,t,-this.halfSize),new N(this.halfSize,t,this.halfSize),new N(-this.halfSize,t,this.halfSize)],s=Array.from(e.svgGroup.children);n.forEach((o,r)=>{const A=this.worldToScreen?.worldToScreen(o);A&&(s[r].setAttribute("x",String(A.x)),s[r].setAttribute("y",String(A.y)))})}_makeLabel(e,t){const n=document.createElementNS("http://www.w3.org/2000/svg","text");return n.textContent=`${e} ${t.toFixed(3)}m`,n.setAttribute("text-anchor","middle"),n.setAttribute("dominant-baseline","central"),n.setAttribute("fill",this.COLOR),n.setAttribute("font-size","12"),n.setAttribute("font-family","Arial, sans-serif"),n.setAttribute("font-weight","bold"),n.setAttribute("stroke","white"),n.setAttribute("stroke-width","2"),n.setAttribute("paint-order","stroke"),n.style.pointerEvents="none",n}getLevelData(e){if(e){const n=this.findModelByUrl(e);return Array.isArray(n?.levels)?n.levels:[]}if(this.levels.length>0)return this.levels.map(n=>n.data);if(!Array.isArray(this.engine.models))return[];const t=[];return this.engine.models.forEach(n=>{Array.isArray(n.levels)&&t.push(...n.levels)}),t}resolvePointLookupArgs(e,t){if(typeof e=="string"){if(!t)throw new Error("Level.getLocationByPoint(url, point) requires a point argument.");return{url:e,targetPoint:t}}return{targetPoint:e}}findModelByUrl(e){return this.engine.models?.find(t=>t.url===e)}pickNearestLevel(e,t,n){if(t&&n){const s=Math.abs(e-t.Elevation),o=Math.abs(n.Elevation-e);return s<=o?t:n}return t??n}getMergedBoundingBox(){if(!Array.isArray(this.engine.models)||this.engine.models.length===0)return{min:{x:-this.halfSize,y:-this.halfSize,z:-this.halfSize},max:{x:this.halfSize,y:this.halfSize,z:this.halfSize}};const e=new Wt;let t=!1;return this.engine.models.forEach(n=>{const s=n.boundingBox;if(!s)return;const o=new N(s.min.x,s.min.y,s.min.z),r=new N(s.max.x,s.max.y,s.max.z);if(!t){e.min.copy(o),e.max.copy(r),t=!0;return}e.expandByPoint(o),e.expandByPoint(r)}),t?e:{min:{x:-this.halfSize,y:-this.halfSize,z:-this.halfSize},max:{x:this.halfSize,y:this.halfSize,z:this.halfSize}}}};const y9=!0,Xte=.5,HQt=32,qQt=.05,$Qt=.02,eMt=.06,tMt=.01;function iMt(i){return!i?.min||!i?.max?0:i.min.distanceTo(i.max)}function nMt(i,e){return i instanceof N?i.clone():e?.min&&e?.max?e.min.clone().add(e.max).multiplyScalar(.5):new N}function sMt(i,e,t){if(i instanceof Zo)return Math.max((i.top-i.bottom)/Math.max(i.zoom,1e-6),1);const n=i,s=nMt(e,t),o=n.position.distanceTo(s),r=typeof n.getEffectiveFOV=="function"?n.getEffectiveFOV():n.fov,A=Ai.degToRad(r*.5);return Math.max(2*o*Math.tan(A),1)}function oMt(i,e,t,n){if(i==null)return n;const s=iMt(t);if(s<=0)return n;const o=sMt(i,e,t),r=Math.max(s*$Qt,1),A=Math.max(s*eMt,r+1),a=Ai.clamp((o-r)/(A-r),0,1);return Ai.lerp(n,0,a)}let rMt=class{engine;isActive=y9;groupEdge;highlightEdgeGroup;material;highlightEdgeMaterial;baseOpacity=Xte;modelEdgeLoaded=!1;modelEdgeLoadingPromise=null;indexes=new Map;highlightIndexes=new Map;highlightEdgeSyncVersion=0;explodeHidden=!1;groupVisibleBeforeExplode=y9;highlightVisibleBeforeExplode=!0;lastReportedOpacity=null;getModelEntry(e){return this.engine?.models?.find(t=>t?.url===e)??null}shouldLoadModelEdge(e){return e?.loadEdge!==!1}getFilteredIdSet(e){return this.engine?.filterLoaderModel?.getContinueIdSet?.(e)??new Set}getOrCreateItemIndex(e){const t=this.indexes.get(e);if(t)return t;const n=this.getModelEntry(e);if(!this.shouldLoadModelEdge(n))return null;const s=Array.isArray(n?.modelEdge)?n.modelEdge:null;if(!s)return null;const o=new Map;let r=0;return s.forEach((A,a)=>{const l=Array.isArray(A?.points)?A.points:null;if(!l)return;const c=r;for(let h=0;h<l.length;h++)l[h]?.length===2&&(r+=6);o.set(Number(A.id),[c,r,a])}),this.indexes.set(e,o),o}getEdgePointsByIndex(e,t){const n=this.getModelEntry(e),s=Array.isArray(n?.modelEdge)?n.modelEdge[t]:null;return Array.isArray(s?.points)?s.points:null}getLineByUrl(e){return this.groupEdge.children.find(t=>t.url==e)??null}getHighlightIndex(e){const t=this.highlightIndexes.get(e);if(t)return t;const n=this.getModelEntry(e);if(!this.shouldLoadModelEdge(n))return null;const s=Array.isArray(n?.modelEdge)?n.modelEdge:null;if(!s)return null;const o=new Map;return s.forEach((r,A)=>{o.set(Number(r?.id),A)}),this.highlightIndexes.set(e,o),o}constructor(e){this.engine=e,this.groupEdge=this.engine.scene.getObjectByName("groupEdge"),zR(this.groupEdge,this.engine.sectionPlane),this.groupEdge.userData.excludeFromAutoExposure=!0,this.highlightEdgeGroup=new qn,this.highlightEdgeGroup.name="highlightModelEdgeGroup",zR(this.highlightEdgeGroup,this.engine.sectionPlane),this.highlightEdgeGroup.userData.excludeFromAutoExposure=!0,this.highlightEdgeGroup.renderOrder=999,this.engine.scene.add(this.highlightEdgeGroup),this.material=new bo({color:0,transparent:!0,opacity:Xte,depthTest:!0,depthWrite:!1}),this.material.clippingPlanes=this.engine.sectionPlane,this.highlightEdgeMaterial=new bo({color:16777215,transparent:!0,opacity:1,depthTest:!1,depthWrite:!1}),this.highlightEdgeMaterial.clippingPlanes=this.engine.sectionPlane,this.groupEdge.visible=y9}active(){this.isActive=!0,this.groupEdge.visible=!this.explodeHidden,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&Gbe(e,!0)}),this.update(),this.show()}disActive(){this.isActive=!1,this.groupEdge.visible=!1,this.engine.scene.traverse(e=>{e.isMesh&&e.material&&Gbe(e,!1)})}isEnabled(){return this.isActive}getOpacity(){return this.baseOpacity}setExplodeHidden(e){this.explodeHidden!==e&&(this.explodeHidden=e,e?(this.groupVisibleBeforeExplode=this.groupEdge?.visible===!0,this.highlightVisibleBeforeExplode=this.highlightEdgeGroup.visible,this.groupEdge.visible=!1,this.highlightEdgeGroup.visible=!1):(this.groupEdge.visible=this.isActive&&this.groupVisibleBeforeExplode,this.highlightEdgeGroup.visible=this.highlightVisibleBeforeExplode),this.engine.requestComposerRender?.())}update(){if(!this.isActive||!this.material)return;const e=oMt(this.engine?.camera,this.engine?.controls?.target,this.engine?.octreeBox?.getBoundingBox?.(),this.baseOpacity);(this.lastReportedOpacity===null||Math.abs(this.lastReportedOpacity-e)>.001)&&(console.log("[ModelEdge] 实时透明度:",Number(e.toFixed(4))),this.lastReportedOpacity=e),!(e>0&&Math.abs(this.material.opacity-e)<=tMt)&&(this.material.opacity=e,this.material.needsUpdate=!0)}hasPendingModelEdges(){return(this.engine?.models??[]).some(t=>this.shouldLoadModelEdge(t)&&!Array.isArray(t?.modelEdge))}loadZipJsonAsync(e,t){return new Promise((n,s)=>{dC(e,o=>{if(o==null){s(new Error(`[ModelEdge] empty edge zip: ${e}`));return}n(o)},()=>{s(new Error(`[ModelEdge] failed to load edge zip: ${e}`))},t)})}async ensureModelEdgeData(e){if(!this.shouldLoadModelEdge(e))return[];if(Array.isArray(e?.modelEdge))return e.modelEdge;try{const t=this.engine.engineStatus.models.find(o=>o.url==e.url);p1(this.engine,e.url,e.url+"/edge");const n=await this.loadZipJsonAsync(e.url+"/edge",t?.key??e?.key),s=JSON.parse(n);if(Array.isArray(s)){const o=this.getFilteredIdSet(e.url);e.modelEdge=o.size>0?s.filter(r=>o.has(Number(r?.id))===!1):s}else e.modelEdge=[]}catch(t){console.error("[ModelEdge] failed to load model edge",{url:e?.url,error:t}),e.modelEdge=[]}return e.modelEdge}async loadModelEdge(){if(!(this.modelEdgeLoaded&&!this.hasPendingModelEdges())){if(this.modelEdgeLoadingPromise!=null){await this.modelEdgeLoadingPromise;return}this.modelEdgeLoadingPromise=(async()=>{const e=this.engine?.models??[];for(const t of e)!this.shouldLoadModelEdge(t)||Array.isArray(t?.modelEdge)||await this.ensureModelEdgeData(t);this.modelEdgeLoaded=!this.hasPendingModelEdges()})().finally(()=>{this.modelEdgeLoadingPromise=null}),await this.modelEdgeLoadingPromise}}async show(){if(await this.loadModelEdge(),!this.isActive||this.explodeHidden)return;(this.engine?.models??[]).forEach(t=>{if(!this.shouldLoadModelEdge(t))return;const n=t?.url;if(typeof n!="string"||n.length===0)return;const s=this.groupEdge.children.find(c=>c.url==n);if(s){s.visible=!0;return}const o=[],r=new Map;if((Array.isArray(t?.modelEdge)?t.modelEdge:[]).forEach((c,h)=>{r.set(Number(c?.id),h),(Array.isArray(c?.points)?c.points:[]).forEach(g=>{g?.length===2&&(o.push(g[0].X),o.push(g[0].Z),o.push(-g[0].Y),o.push(g[1].X),o.push(g[1].Z),o.push(-g[1].Y))})}),o.length===0)return;const a=new mi;a.setAttribute("position",new Qi(o,3));const l=new ir(a,this.material);l.url=n,this.setLineTransform(l,Ju(this.engine,n)),this.groupEdge.add(l),this.highlightIndexes.set(n,r),this.releaseIndexes(n)})}setModelEdgeTransform(e,t){const n=this.groupEdge.children.find(s=>s.url==e);n&&this.setLineTransform(n,t),this.highlightEdgeGroup.children.forEach(s=>{s?.url==e&&this.setLineTransform(s,t)})}setLineTransform(e,t){e.matrixAutoUpdate=!1,e.matrix.copy(t),e.matrixWorldNeedsUpdate=!0,e.updateMatrixWorld(!0)}syncHighlightModelEdges(e){const t=++this.highlightEdgeSyncVersion;this.syncHighlightModelEdgesAsync(e,t)}clearHighlightModelEdges(){this.highlightEdgeSyncVersion++,this.disposeHighlightEdges()}releaseModel(e){this.highlightEdgeSyncVersion++,[this.groupEdge,this.highlightEdgeGroup].forEach(t=>{[...t?.children??[]].forEach(n=>{n?.url===e&&(t.remove(n),n.geometry?.dispose?.())})}),this.indexes.delete(e),this.highlightIndexes.delete(e)}releaseIndexes(e){if(typeof e=="string"&&e.length>0){this.indexes.delete(e);return}this.indexes.clear()}async syncHighlightModelEdgesAsync(e,t){await this.loadModelEdge(),t===this.highlightEdgeSyncVersion&&(this.disposeHighlightEdges(),e.forEach(n=>{const s=this.getHighlightIndex(n.url);if(!s||!Array.isArray(n.ids))return;const o=[];if(n.ids.forEach(a=>{const l=s?.get(Number(a)),c=typeof l=="number"?this.getEdgePointsByIndex(n.url,l):null;if(Array.isArray(c)){if(c.length>HQt)return;this.appendEdgePositions(o,c)}}),o.length===0)return;const r=new mi;r.setAttribute("position",new Qi(o,3));const A=new ir(r,this.highlightEdgeMaterial);A.name="highlightModelEdge",A.url=n.url,this.setLineTransform(A,Ju(this.engine,n.url)),this.highlightEdgeGroup.add(A)}))}appendEdgePositions(e,t){t.forEach(n=>{n?.length===2&&(e.push(n[0].X,n[0].Z,-n[0].Y),e.push(n[1].X,n[1].Z,-n[1].Y))})}disposeHighlightEdges(){[...this.highlightEdgeGroup.children].forEach(t=>{this.highlightEdgeGroup.remove(t),t.geometry?.dispose?.()})}getModelEdge(e,t){if(!this.shouldLoadModelEdge(this.getModelEntry(e)))return null;const n=this.getOrCreateItemIndex(e);if(n){const s=n.get(Number(t));if(s){const o=typeof s[2]=="number"?this.getEdgePointsByIndex(e,s[2]):null;return[s[0],s[1],o]}}return this.loadModelEdge(),null}hideModelEdge(e,t){if(!this.shouldLoadModelEdge(this.getModelEntry(e)))return;const n=this.getLineByUrl(e),s=this.getOrCreateItemIndex(e);if(!s){this.loadModelEdge();return}const o=s.get(Number(t));if(!o)return;const[r,A]=o;if(n){const a=n.geometry.attributes.position.array;for(let l=r;l<A;l++)a[l]=NaN;n.geometry.attributes.position.needsUpdate=!0}this.releaseIndexes(e)}setOpacity(e){this.baseOpacity=Ai.clamp(e,qQt,1),this.update()}showModelEdge(e,t){if(!this.shouldLoadModelEdge(this.getModelEntry(e)))return;const n=this.getLineByUrl(e),s=this.getOrCreateItemIndex(e);if(!s){this.loadModelEdge();return}const o=s.get(Number(t));if(!o)return;const[r,A,a]=o,l=typeof a=="number"?this.getEdgePointsByIndex(e,a):null;if(n&&Array.isArray(l)){const c=n.geometry.attributes.position.array;let h=0;for(let d=r;d<A;d+=3){const g=Math.floor(h/6),u=h%6>=3;if(l[g]&&l[g].length===2){const p=u?l[g][1]:l[g][0];c[d]=p.X,c[d+1]=p.Z,c[d+2]=-p.Y}h+=3}n.geometry.attributes.position.needsUpdate=!0}this.releaseIndexes(e)}};class USe extends lt{constructor(){const e=new _o;super(new Vo(1,1,1),e),this.turbidity=ui(2),this.rayleigh=ui(1),this.mieCoefficient=ui(.005),this.mieDirectionalG=ui(.8),this.sunPosition=ui(new N),this.cloudScale=ui(2e-4),this.cloudSpeed=ui(2e-5),this.cloudCoverage=ui(.4),this.cloudDensity=ui(.4),this.cloudElevation=ui(.5),this.showSunDisc=ui(1),this.isSky=!0,this.isSkyMesh=!0;const t=r4("vec3"),n=r4("float"),s=r4("vec3"),o=r4("vec3"),r=ss(()=>{const a=ft(2.718281828459045),l=zn(5804542996261093e-21,13562911419845635e-21,30265902468824876e-21),c=zn(18399918514433978e-2,27798023919660528e-2,40790479543861094e-2),h=ft(1.6110731556870734),d=ft(1.5),g=ft(1e3),u=PA(this.sunPosition);t.assign(u);const p=u.y,m=vh(p,-1,1),I=g.mul(an(0,ft(1).sub(Hg(a,h.sub(I1(m)).div(d).negate()))));n.assign(I);const B=ft(1).sub(vh(ft(1).sub(t4(this.sunPosition.y.div(45e4))),0,1)),y=this.rayleigh.sub(ft(1).mul(ft(1).sub(B)));s.assign(l.mul(y));const w=ft(.2).mul(this.turbidity).mul(1e-17),M=ft(.434).mul(w).mul(c);o.assign(M.mul(this.mieCoefficient));const D=UIt;return D.z.assign(D.w),D})(),A=ss(()=>{const a=ft(3.141592653589793),l=ft(8400),c=ft(1250),h=ft(.9999566769464484),d=ft(.05968310365946075),g=ft(.07957747154594767),u=PA(VIt.sub(SIt)),p=I1(an(0,u.y)),m=ft(1).div(oC(p).add(ft(.15).mul(Hg(ft(93.885).sub(p.mul(180).div(a)),-1.253)))),I=l.mul(m),B=c.mul(m),y=t4(Ip(s,I).add(Ip(o,B)).negate()),w=ys(u,t),M=w.mul(.5).add(.5),D=d.mul(ft(1).add(Hg(M,2))),Q=s.mul(D),b=Hg(this.mieDirectionalG,2),P=ft(1).div(Hg(ft(1).sub(ft(2).mul(this.mieDirectionalG).mul(w)).add(b),1.5)),F=g.mul(ft(1).sub(b)).mul(P),T=o.mul(F),x=Hg(n.mul(ib(Q,T).div(ib(s,o))).mul(BB(1,y)),zn(1.5));x.mulAssign(xa(zn(1),Hg(n.mul(ib(Q,T).div(ib(s,o))).mul(y),zn(1/2)),vh(Hg(BB(1,t.y),5),0,1)));const C=zn(.1).mul(y),S=vh(w.sub(h).mul(5e4),0,1).mul(this.showSunDisc),v=TA(n.mul(y),80).mul(760).mul(S),Y=ib(x,C).mul(.04).add(v).add(zn(0,3e-4,75e-5)).toVar(),k=ss(([U])=>{const O=zu(U.xyx.mul(zn(.1031,.103,.0973))).toVar();return O.addAssign(ys(O,O.yzx.add(33.33))),zu(O.xx.add(O.yz).mul(O.zy)).mul(2).sub(1)}),j=ss(([U])=>{const O=rC(U),V=zu(U),$=V.mul(V).mul(V).mul(V.mul(V.mul(6).sub(15)).add(10)),z=ys(k(O),V),ie=ys(k(O.add(or(1,0))),V.sub(or(1,0))),te=ys(k(O.add(or(0,1))),V.sub(or(0,1))),Ae=ys(k(O.add(or(1,1))),V.sub(or(1,1)));return xa(xa(z,ie,$.x),xa(te,Ae,$.x),$.y).mul(1.6)}),R=ss(([U,O])=>{const V=or(U).toVar(),$=ft(0).toVar(),z=ft(1).toVar();return Bd(4,()=>{$.addAssign(z.mul(j(V))),z.mulAssign(.5),V.mulAssign(2).addAssign(O)}),$});return fs(u.y.greaterThan(0).and(this.cloudCoverage.greaterThan(0)),()=>{const U=xa(1,.1,this.cloudElevation),O=u.xz.div(u.y.mul(U)).toVar();O.mulAssign(this.cloudScale),O.addAssign(Zbe.mul(this.cloudSpeed));const V=Zbe.mul(this.cloudSpeed).mul(300),$=R(O.mul(1e3),V).mul(.7).add(.5).clamp(0,1).toVar(),z=j(O.mul(300)).mul(.37).add(.5),ie=vh(this.cloudCoverage.add(z.sub(.5).mul(.6)),0,1),te=BB(1,ie).toVar(),Ae=EB(te,te.add(.3),$).toVar(),J=EB(0,ib(.03,Ip(.06,this.cloudElevation)),u.y);Ae.mulAssign(J);const W=EB(-.08,.3,t.y),ee=n.mul(y).mul(.22).mul(.04).toVar(),q=x.mul(.04).add(zn(0,3e-4,75e-5)),ne=an(0,$.sub(te)).toVar(),Z=t4(ne.mul(-4)).toVar(),K=BB(1,Z.mul(Z)),re=xa(.45,1,Z.mul(K).mul(2.6).clamp(0,1)),ue=ft(.51).div(Hg(BB(1.49,w.mul(1.4)),1.5)).clamp(0,3),le=Ae.mul(BB(1,Ae)).mul(4),ae=q.add(ee.mul(re)).toVar();ae.addAssign(ee.mul(ue).mul(le).mul(.6)),ae.mulAssign(W.max(.03));const he=BB(1,t4(ne.mul(this.cloudDensity).mul(-12))).mul(J).toVar();Y.subAssign(C.mul(.04).add(v).mul(he));const De=xa(Y,ae,y);Y.assign(xa(Y,De,he))}),Yn(Y,1)})();e.side=$s,e.depthWrite=!1,e.fog=!1,e.vertexNode=r,e.colorNode=A}}const kSe={turbidity:2,rayleigh:5,mieCoefficient:.005,mieDirectionalG:.7,elevation:60,azimuth:180,exposure:.1,orthoExposureScale:1.5,cloudScale:2e-4,cloudSpeed:2e-5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},Vte="sunrise_clear",WSe=.2,Zte=[{id:"sunrise_clear",names:["晴朗日出","晴朗日出","Clear Sunrise"],params:{turbidity:4,rayleigh:1.8,mieCoefficient:.004,mieDirectionalG:.72,elevation:8,azimuth:105,exposure:.42,cloudCoverage:.12,cloudDensity:.2,cloudElevation:.45,showSunDisc:!0}},{id:"morning_mist",names:["晨雾薄云","晨霧薄雲","Misty Morning"],params:{turbidity:14,rayleigh:2.4,mieCoefficient:.018,mieDirectionalG:.68,elevation:12,azimuth:120,exposure:.35,cloudCoverage:.45,cloudDensity:.5,cloudElevation:.35,showSunDisc:!0}},{id:"noon_clear",names:["晴空正午","晴空正午","Clear Noon"],params:{turbidity:2,rayleigh:1,mieCoefficient:.002,mieDirectionalG:.82,elevation:68,azimuth:180,exposure:.58,cloudCoverage:.05,cloudDensity:.12,cloudElevation:.55,showSunDisc:!0}},{id:"afternoon_cloudy",names:["午后多云","午後多雲","Cloudy Afternoon"],params:{turbidity:8,rayleigh:1.7,mieCoefficient:.008,mieDirectionalG:.74,elevation:42,azimuth:220,exposure:.5,cloudCoverage:.48,cloudDensity:.42,cloudElevation:.52,showSunDisc:!0}},{id:"sunset_glow",names:["落日晚霞","落日晚霞","Sunset Glow"],params:{turbidity:10,rayleigh:2,mieCoefficient:.006,mieDirectionalG:.7,elevation:6,azimuth:245,exposure:.6,cloudCoverage:.3,cloudDensity:.36,cloudElevation:.5,showSunDisc:!0}},{id:"blue_hour",names:["暮色蓝调","暮色藍調","Blue Hour"],params:{turbidity:7,rayleigh:1.2,mieCoefficient:.003,mieDirectionalG:.76,elevation:-4,azimuth:255,exposure:.22,cloudCoverage:.2,cloudDensity:.24,cloudElevation:.48,showSunDisc:!1}},{id:"overcast_day",names:["阴天白昼","陰天白晝","Overcast Day"],params:{turbidity:20,rayleigh:2,mieCoefficient:.02,mieDirectionalG:.6,elevation:32,azimuth:180,exposure:.38,cloudCoverage:.86,cloudDensity:.68,cloudElevation:.4,showSunDisc:!1}},{id:"storm_rain",names:["暴雨雷云","暴雨雷雲","Storm Rain"],params:{turbidity:19,rayleigh:.9,mieCoefficient:.03,mieDirectionalG:.58,elevation:18,azimuth:210,exposure:.2,cloudCoverage:.95,cloudDensity:.9,cloudElevation:.28,showSunDisc:!1}},{id:"snow_day",names:["雪天漫射","雪天漫射","Snowy Day"],params:{turbidity:15,rayleigh:2.6,mieCoefficient:.012,mieDirectionalG:.65,elevation:24,azimuth:170,exposure:.5,cloudCoverage:.78,cloudDensity:.72,cloudElevation:.43,showSunDisc:!1}},{id:"moonlit_night",names:["月夜星空","月夜星空","Moonlit Night"],params:{turbidity:4,rayleigh:.35,mieCoefficient:.001,mieDirectionalG:.82,elevation:-18,azimuth:160,exposure:.14,cloudCoverage:.1,cloudDensity:.14,cloudElevation:.55,showSunDisc:!1}}],OSe=Zte.reduce((i,e)=>(i[e.id]=e,i),{}),LSe=2e6,Jte=45e4,AMt=128,aMt=100,KSe="v3-sky-clouds",XSe={turbidity:[0,20],rayleigh:[0,4],mieCoefficient:[0,.1],mieDirectionalG:[0,.999],elevation:[-90,90],azimuth:[-360,360],exposure:[0,4],orthoExposureScale:[.1,4],cloudScale:[1e-6,.005],cloudSpeed:[0,.001],cloudCoverage:[0,1],cloudDensity:[0,1],cloudElevation:[0,1]};let lMt=class{engine;sky=null;sun=new N;params=this._resolveParams(OSe[Vte].params);currentPreset=Vte;currentIntensity=WSe;currentEnvironmentTarget=null;environmentRefreshTimer=null;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=Yr;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){this.engine?.scene&&(this._captureSceneState(),this.sky||(this.sky=new USe,this.sky.scale.setScalar(Jte),this.sky.name=this.skyName,this.sky.frustumCulled=!1,this._getBackgroundScene()?.add(this.sky)),this.sky.visible=!0,this._syncSkyToCamera(),this.engine.scene.background=null,this._expandCameraFarForSky(),this._applyParamsToSky(),this._updateAnimationState(),this.engine.composerModule?.rebuild?.(),this._requestRender())}close(e=!0){this.sky&&(this._cancelEnvironmentRefresh(),this.engine?.setIdleFrameRateExempt?.(KSe,!1),this._restoreCameraFar(),this._restoreSceneState(),e?(this.sky.removeFromParent(),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null,this._disposeEnvironmentTarget()):this.sky.visible=!1,this.engine.composerModule?.rebuild?.(),this._requestRender())}isActive(){return this.sky?.visible===!0&&this.sky.parent===this._getBackgroundScene()}getParams(){return{...this.params}}setParams(e){this.params=this._resolveParams({...this.params,...e}),this._applyParamsToSky(),this._requestRender()}setPreset(e){const t=OSe[e];t&&(this.currentPreset=e,this.params=this._resolveParams(t.params),this._applyParamsToSky(),this._requestRender())}getCurrentPreset(){return this.currentPreset}getPresetNames(){return Zte.map(e=>e.id)}getPresetList(){return Zte.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){Number.isFinite(e)&&(this.currentIntensity=Math.max(e,0),this.isActive()&&this.engine?.scene&&(this.engine.scene.environmentIntensity=this.currentIntensity,this.currentEnvironmentTarget||this._scheduleEnvironmentRefresh(),this._requestRender()))}getIntensity(){return this.currentIntensity}update(e){this._syncSkyToCamera()}_getBackgroundScene(){return this.engine?.composerModule?.postProcessingBackgroundScene??this.engine?.scene??null}_syncSkyToCamera(){!this.sky?.visible||!this.engine?.camera||(this.sky.position.copy(this.engine.camera.position),this.sky.updateMatrixWorld())}_isOrthographicCamera(){return this.engine?.camera?.isOrthographicCamera===!0}_getEffectiveExposure(){return this._isOrthographicCamera()?this.params.exposure*this.params.orthoExposureScale:this.params.exposure}_expandCameraFarForSky(){const e=this.engine?.camera;!e||typeof e.far!="number"||e.far>=LSe||(this.savedCameraFar==null&&(this.savedCameraFar=e.far),e.far=LSe,e.updateProjectionMatrix?.())}_restoreCameraFar(){const e=this.engine?.camera;this.savedCameraFar==null||!e||(e.far=this.savedCameraFar,e.updateProjectionMatrix?.(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;this.sky.turbidity.value=this.params.turbidity,this.sky.rayleigh.value=this.params.rayleigh,this.sky.mieCoefficient.value=this.params.mieCoefficient,this.sky.mieDirectionalG.value=this.params.mieDirectionalG,this.sky.cloudScale.value=this.params.cloudScale,this.sky.cloudSpeed.value=this.params.cloudSpeed,this.sky.cloudCoverage.value=this.params.cloudCoverage,this.sky.cloudDensity.value=this.params.cloudDensity,this.sky.cloudElevation.value=this.params.cloudElevation,this.sky.showSunDisc.value=this.params.showSunDisc;const e=Ai.degToRad(90-this.params.elevation),t=Ai.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,e,t),this.sky.sunPosition.value.copy(this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=tw,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()),this._updateAnimationState(),this.isActive()&&this._scheduleEnvironmentRefresh()}_captureSceneState(){this.hasCapturedSceneState||!this.engine?.scene||(this.previousBackground=this.engine.scene.background,this.previousEnvironment=this.engine.scene.environment,this.previousBackgroundIntensity=this.engine.scene.backgroundIntensity??1,this.previousEnvironmentIntensity=this.engine.scene.environmentIntensity??1,this.previousToneMapping=this.engine.renderer?.toneMapping??Yr,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(){!this.hasCapturedSceneState||!this.engine?.scene||(this.engine.scene.background=this.previousBackground,this.engine.scene.environment=this.previousEnvironment,this.engine.scene.backgroundIntensity=this.previousBackgroundIntensity,this.engine.scene.environmentIntensity=this.previousEnvironmentIntensity,this.engine.renderer&&(this.engine.renderer.toneMapping=this.previousToneMapping,this.engine.renderer.toneMappingExposure=this.previousToneMappingExposure),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=Yr,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1)}_scheduleEnvironmentRefresh(){!this.isActive()||!this.engine?.renderer||(this._cancelEnvironmentRefresh(),this.environmentRefreshTimer=setTimeout(()=>{this.environmentRefreshTimer=null,this._refreshEnvironmentMap()},aMt))}_cancelEnvironmentRefresh(){this.environmentRefreshTimer!=null&&(clearTimeout(this.environmentRefreshTimer),this.environmentRefreshTimer=null)}_refreshEnvironmentMap(){if(!this.isActive()||!this.engine?.renderer||!this.engine?.scene)return;const e=new ld,t=new USe;t.scale.setScalar(Jte),t.turbidity.value=this.params.turbidity,t.rayleigh.value=this.params.rayleigh,t.mieCoefficient.value=this.params.mieCoefficient,t.mieDirectionalG.value=this.params.mieDirectionalG,t.sunPosition.value.copy(this.sun),t.cloudScale.value=this.params.cloudScale,t.cloudSpeed.value=0,t.cloudCoverage.value=this.params.cloudCoverage,t.cloudDensity.value=this.params.cloudDensity,t.cloudElevation.value=this.params.cloudElevation,t.showSunDisc.value=!1,e.add(t);const n=new _6(this.engine.renderer);try{const s=n.fromScene(e,0,.1,Jte*2,{size:AMt}),o=this.currentEnvironmentTarget;this.currentEnvironmentTarget=s,this.engine.scene.environment=s.texture,this.engine.scene.environmentIntensity=this.currentIntensity,o?.dispose(),this._requestRender()}catch(s){console.warn("[SkyManager] WebGPU 天空环境贴图生成失败,将继续显示天空背景。",s)}finally{n.dispose(),t.material.dispose(),t.geometry.dispose()}}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_updateAnimationState(){const e=this.isActive()&&this.params.cloudSpeed>0&&this.params.cloudCoverage>0&&this.params.cloudDensity>0;this.engine?.setIdleFrameRateExempt?.(KSe,e)}_resolveParams(e){const t={...kSe,...e};return Object.keys(XSe).forEach(n=>{const s=XSe[n],o=t[n];if(!s||typeof o!="number")return;const r=Number.isFinite(o)?o:kSe[n];t[n]=Ai.clamp(r,s[0],s[1])}),t.showSunDisc=!!t.showSunDisc,t}_requestRender(){this.engine?.requestComposerRender?.()}},cMt=class{engine;defaultSettings;settings;environmentApplyVersion=0;constructor(e){this.engine=e,this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}init(){this.defaultSettings=this._buildDefaultSettingsFromModules(),this.settings=this._clone(this.defaultSettings)}getSettings(){return this._syncSettingsFromModules(),this._clone(this.settings)}getPresetLists(){const e=this.engine.ground?.getGroundList()||[],t=this.engine.hdr?.getHdrList()||[],n=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(s=>this._toPresetItem(s)),hdr:t.map(s=>this._toPresetItem(s)),sky:n.map(s=>this._toPresetItem(s))}}async setSettings(e){e.render&&(Object.assign(this.settings.render,e.render),this._applyRenderSettings(this.settings.render)),e.display&&(Object.assign(this.settings.display,e.display),this._applyDisplaySettings(this.settings.display)),e.environment&&(this._mergeEnvironmentSettings(e.environment),await this._applyEnvironmentSettings(this._clone(this.settings.environment)))}async resetToDefault(){this.settings=this._clone(this.defaultSettings),this._applyRenderSettings(this.settings.render),this._applyDisplaySettings(this.settings.display),await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setRenderMode(e){this.settings.render.mode=e,this.engine.engineModelModule?.setQualityLevel(e)}setContrast(e){this.settings.render.contrast=e,this.engine.engineModelModule?.setContrastValue(.5+e/100)}setSaturation(e){this.settings.render.saturation=e,this.engine.engineModelModule?.setSaturationValue(.5+e/100)}setShadowIntensity(e){this.settings.render.shadowIntensity=e,this._updateDirectionalLight(t=>{t.shadow.intensity=e/100*2})}setLightIntensity(e){this.settings.render.lightIntensity=e,this.setAmbientLightIntensity(e/100)}setGTAOIntensity(e){this.settings.render.gtaoIntensity=e,this.engine.engineModelModule?.setGTAOIntensity(e/100)}setShowEdge(e){this.settings.display.showEdge=e,e?this.engine.modelEdge?.active():this.engine.modelEdge?.disActive()}setEdgeOpacity(e){this.settings.display.edgeOpacity=e,this.engine.modelEdge?.setOpacity(e/100)}setShowGrid(e){this.settings.display.showGrid=e,e?this.engine.grid?.show():this.engine.grid?.hide()}setShowLevel(e){this.settings.display.showLevel=e,e?this.engine.level?.show():this.engine.level?.hide()}setShowGround(e){this.settings.display.showGround=e,e?this.engine.ground?.show():this.engine.ground?.hide()}setGroundId(e){this.settings.display.groundId=e,this.engine.ground?.setGround(e)}setGroundHeight(e){this.settings.display.groundHeight=e,this.engine.ground?.setHeight(e)}async setEnvironmentType(e){this.settings.environment.type=e,await this._applyEnvironmentSettings(this._clone(this.settings.environment))}async setHdrId(e){this.settings.environment.hdrId=e,this.settings.environment.type==="hdr"&&await this._applyEnvironmentSettings(this._clone(this.settings.environment))}setHdrIntensity(e){this.settings.environment.hdrIntensity=e,this.settings.environment.hdrEnvironmentIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setHdrBackgroundIntensity(e){this.settings.environment.hdrBackgroundIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setBackgroundIntensity(e/100)}setHdrEnvironmentIntensity(e){this.settings.environment.hdrEnvironmentIntensity=e,this.settings.environment.hdrIntensity=e,this.settings.environment.type==="hdr"&&this.engine.hdr?.setIntensity(e/100)}setSkyPreset(e){this.settings.environment.skyPreset=e,this.settings.environment.skyParams={},this.settings.environment.type==="sky"&&this.engine.skyManager?.setPreset(e)}setSkyParams(e){this.settings.environment.skyParams=this._clone(e),this.settings.environment.type==="sky"&&this.engine.skyManager?.setParams(this.settings.environment.skyParams)}setSkyIntensity(e){this.settings.environment.skyIntensity=e,this.settings.environment.type==="sky"&&this.engine.skyManager?.setIntensity(e/100)}setAmbientLightIntensity(e){const t=this.engine.renderer;t&&(t.toneMapping=v0,t.toneMappingExposure=2*e)}_syncSettingsFromModules(){this.settings=this._readCurrentSettingsFromModules()}_buildDefaultSettingsFromModules(){const e=this.engine.composerModule?.getColorGradingParameters?.(),t=this.engine.composerModule?.getEffectParameters?.("gtao"),n=this.engine.renderer?.toneMappingExposure,s=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??SB,r=this.engine.hdr?.getIntensity?.(),A=this.engine.hdr?.getBackgroundIntensity?.(),a=this.engine.skyManager?.getIntensity?.(),l=this.engine.skyManager?.getCurrentPreset?.()??Vte,c=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getQualityLevel?.()),contrast:this._uniformToPercent(e?.contrast,CCt),saturation:this._uniformToPercent(e?.saturation,mCt),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),b4),lightIntensity:this._exposureToPercent(n,Ute),gtaoIntensity:this._unitToPercent(t?.scale,ICt)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??y9,edgeOpacity:this._unitToPercent(s,Xte),showGrid:this.engine.grid?.getVisible?.()??Ote,showLevel:this.engine.level?.getVisible?.()??jSe,showGround:this.engine.ground?.getVisible?.()??GSe,groundId:this.engine.ground?.getCurrentId?.()??NSe,groundHeight:this.engine.ground?.getHeight?.()??YSe},environment:{type:c?"sky":o!==SB?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(r,Lte),hdrBackgroundIntensity:this._unitToPercent(A,Kte),hdrEnvironmentIntensity:this._unitToPercent(r,Lte),skyPreset:l,skyParams:{},skyIntensity:this._unitToPercent(a,WSe)}}}_readCurrentSettingsFromModules(){const e=this.engine.composerModule?.getColorGradingParameters?.(),t=this.engine.composerModule?.getEffectParameters?.("gtao"),n=this.engine.renderer?.toneMappingExposure,s=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??this.settings.environment.hdrId,r=this.engine.hdr?.getIntensity?.(),A=this.engine.hdr?.getBackgroundIntensity?.(),a=this.engine.skyManager?.getIntensity?.(),l=this.engine.skyManager?.getCurrentPreset?.()??this.settings.environment.skyPreset,c=this.engine.skyManager?.getParams?.(),h=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getQualityLevel?.()??this.settings.render.mode),contrast:this._uniformToPercent(e?.contrast,this.settings.render.contrast/100+.5),saturation:this._uniformToPercent(e?.saturation,this.settings.render.saturation/100+.5),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),this.settings.render.shadowIntensity/50),lightIntensity:this._exposureToPercent(n,this.settings.render.lightIntensity/50),gtaoIntensity:this._unitToPercent(t?.scale,this.settings.render.gtaoIntensity/100)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??this.settings.display.showEdge,edgeOpacity:this._unitToPercent(s,this.settings.display.edgeOpacity/100),showGrid:this.engine.grid?.getVisible?.()??this.settings.display.showGrid,showLevel:this.engine.level?.getVisible?.()??this.settings.display.showLevel,showGround:this.engine.ground?.getVisible?.()??this.settings.display.showGround,groundId:this.engine.ground?.getCurrentId?.()??this.settings.display.groundId,groundHeight:this.engine.ground?.getHeight?.()??this.settings.display.groundHeight},environment:{type:h?"sky":o!==SB?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(r,this.settings.environment.hdrIntensity/100),hdrBackgroundIntensity:this._unitToPercent(A,this.settings.environment.hdrBackgroundIntensity/100),hdrEnvironmentIntensity:this._unitToPercent(r,(this.settings.environment.hdrEnvironmentIntensity??this.settings.environment.hdrIntensity)/100),skyPreset:l,skyParams:c?this._clone(c):this._clone(this.settings.environment.skyParams),skyIntensity:this._unitToPercent(a,this.settings.environment.skyIntensity/100)}}}_toRenderMode(e){return e==null?FSe:X1(e)}_uniformToPercent(e,t){const n=typeof e=="number"?e:t;return this._clampPercent((n-.5)*100)}_shadowToPercent(e,t){const n=typeof e=="number"?e:t;return this._clampPercent(n*50)}_exposureToPercent(e,t){const n=typeof e=="number"?e:t;return this._clampPercent(n*50)}_unitToPercent(e,t){const n=typeof e=="number"?e:t;return this._clampPercent(n*100)}_clampPercent(e){return Math.min(100,Math.max(0,Math.round(e)))}_getDirectionalLightShadowIntensity(){const e=this.engine.scene?.children?.filter(n=>n instanceof xh);return!e||e.length===0?b4:(e.find(n=>n.castShadow)??e[0]).shadow?.intensity??b4}_applyRenderSettings(e){this.setRenderMode(e.mode),this.setContrast(e.contrast),this.setSaturation(e.saturation),this.setShadowIntensity(e.shadowIntensity),this.setLightIntensity(e.lightIntensity),this.setGTAOIntensity(e.gtaoIntensity)}_applyDisplaySettings(e){this.setShowEdge(e.showEdge),this.setEdgeOpacity(e.edgeOpacity),this.setShowGrid(e.showGrid),this.setShowLevel(e.showLevel),this.setShowGround(e.showGround),this.setGroundId(e.groundId),this.setGroundHeight(e.groundHeight)}async _applyEnvironmentSettings(e){const t=++this.environmentApplyVersion;if(await this.engine.hdr?.setHdr(SB),t===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),t===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!==SB){if(await this.engine.hdr?.setHdr(e.hdrId),t!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setBackgroundIntensity((e.hdrBackgroundIntensity??Kte)/100),this.engine.hdr?.setIntensity((e.hdrEnvironmentIntensity??e.hdrIntensity)/100)}break;case"sky":this.engine.skyManager?.activate(),this.engine.skyManager?.setPreset(e.skyPreset),Object.keys(e.skyParams).length>0&&this.engine.skyManager?.setParams(this._clone(e.skyParams)),this.engine.skyManager?.setIntensity(e.skyIntensity/100);break}}_updateDirectionalLight(e){const t=this.engine.scene?.children.find(n=>n instanceof xh);t&&e(t)}_mergeEnvironmentSettings(e){Object.assign(this.settings.environment,e),e.skyPreset!==void 0&&e.skyParams===void 0&&(this.settings.environment.skyParams={}),e.skyParams!==void 0&&(this.settings.environment.skyParams=this._clone(e.skyParams))}_toPresetItem(e){const t=Array.isArray(e.names)?[...e.names]:[];return{id:e.id,name:t[0]??e.id,names:t}}_clone(e){return JSON.parse(JSON.stringify(e))}};function $a(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(i){var e=Math.random()*16|0,t=i=="x"?e:e&3|8;return t.toString(16)})}let xB=class{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Tee(e),this.handelBehaved.init(this,null),this.setting={unit:"m",precision:3}}getSetting(){return this.setting}saveSetting(e){this.setting=e}active(){this.handelBehaved.active()}disActive(){this.handelBehaved.disActive()}getMeasureText(e,t){if(e==null)return null;let n=this.setting.unit,s=n;return t==1?n=="mm"?e=e*1e3:n=="cm"?e=e*100:n=="dm"?e=e*10:n=="m"?e=e*1:n=="km"&&(e=e*.001):t==2&&(n=="mm"?e=e*1e3*1e3:n=="cm"?e=e*100*100:n=="dm"?e=e*10*10:n=="m"?e=e*1*1:n=="km"&&(e=e*.001*.001),s=s+"²"),e.toFixed(this.setting.precision)+" "+s}cancelCurrentSelectedAnnotation(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight==!0&&(n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData,t=!0;for(let n in e)for(let s=e[n].length-1;s>=0;s--){let o=e[n][s];o.isSelect==!0&&(o.container.remove(),e[n].splice(s,1),t=!1)}this.engine.measure.clearAllPoints(),t&&(this.engine.events.trigger("quit_measure_draw",!0),this.engine.modelToolModule.unhighlightAllModels(),this.engine.measure.quitDraw())}handelKeyDeleteDown(){let e=this.engine.measure.annotationData;for(let t in e)for(let n=e[t].length-1;n>=0;n--){let s=e[t][n];s.highlight==!0&&(s.container.remove(),e[t].splice(n,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(n=>{n.highlight=!1,n.container.classList.remove("Hight"),n.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;const t=new po(e.engine.camera,e.engine.renderer,e.engine.scene);function n(I){const B=t.worldToScreenIfVisible(I);return B==null?null:(B.x+=e.engine.reactBoundingClientRect.left,B.y+=e.engine.reactBoundingClientRect.top,B)}function s(I,B){I.container!=null&&(I.container.style.display=B?"block":"none")}this.engine.measure.annotationData.normalAnnotation.forEach(I=>{m(I)}),this.engine.measure.annotationData.elevationAnnotation.forEach(I=>{p(I)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(I=>{u(I)}),this.engine.measure.annotationData.angleAnnotation.forEach(I=>{h(I)}),this.engine.measure.annotationData.areaAnnotation.forEach(I=>{d(I)}),this.engine.measure.annotationData.slopeAnnotation.forEach(I=>{g(I)});function h(I){if(I.container==null){let b=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel">'+I.text+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="angle-annotation",I.container.id=I.id,I.container.style.pointerEvents="none",I.container.innerHTML=b,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=n(I.point1),y=n(I.point2),w=n(I.point3);if(B==null||y==null||w==null){s(I,!1);return}s(I,!0);let M=I.container;M.getElementsByTagName("circle")[0].setAttribute("cx",B.x),M.getElementsByTagName("circle")[0].setAttribute("cy",B.y),M.getElementsByTagName("circle")[1].setAttribute("cx",y.x),M.getElementsByTagName("circle")[1].setAttribute("cy",y.y),M.getElementsByTagName("circle")[2].setAttribute("cx",w.x),M.getElementsByTagName("circle")[2].setAttribute("cy",w.y),M.getElementsByTagName("polyline")[0].setAttribute("points",B.x+","+B.y+" "+y.x+","+y.y),M.getElementsByTagName("polyline")[1].setAttribute("points",y.x+","+y.y+" "+w.x+","+w.y);let D=y.x,Q=y.y-30;M.getElementsByTagName("rect")[0].setAttribute("x",D-40),M.getElementsByTagName("rect")[0].setAttribute("y",Q-12.5),M.getElementsByTagName("text")[0].setAttribute("x",D),M.getElementsByTagName("text")[0].setAttribute("y",Q+4),M.getElementsByTagName("text")[0].innerHTML=I.text,M.style.top="0px",M.style.left="0px"}function d(I){if(I.container==null){let T=['<svg class="measureSvg">','<polygon fill="rgba(0, 0, 255, 0.1)" stroke="none" points="" style="opacity: 0.3;"/>','<polyline class="measureLine" stroke="orange" stroke-width="2" points="" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(I.text,2)+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="area-annotation",I.container.id=I.id,I.container.innerHTML=T,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}if(!I.points||I.points.length<2)return;let B=[],y=0,w=0;for(let T=0;T<I.points.length;T++){let x=n(I.points[T]);if(x==null){s(I,!1);return}B.push(x),y+=x.x,w+=x.y}s(I,!0),y=y/B.length,w=w/B.length;let M=B.map(T=>T.x+","+T.y).join(" "),D=[...B];B.length>=3&&D.push(B[0]);let Q=D.map(T=>T.x+","+T.y).join(" "),b=I.container;b.getElementsByTagName("polygon")[0].setAttribute("points",B.length>=3?M:""),b.getElementsByTagName("polyline")[0].setAttribute("points",Q);let P=y,F=w;b.getElementsByTagName("rect")[0].setAttribute("x",P-40),b.getElementsByTagName("rect")[0].setAttribute("y",F-12.5),b.getElementsByTagName("text")[0].setAttribute("x",P+10),b.getElementsByTagName("text")[0].setAttribute("y",F+4),b.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(I.text,2),b.style.top="0px",b.style.left="0px"}function g(I){if(I.container==null){let Q=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+I.id+'" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto" markerUnits="strokeWidth">','<path class="measureLine" d="M0,0 L0,6 L9,3 z"/>',"</marker>","</defs>",'<polyline class="measureLine" stroke="orange" stroke-width="2" points="0,0 0,0" marker-end="url(#slope-arrow-'+I.id+')" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+I.text+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="slope-annotation",I.container.id=I.id,I.container.innerHTML=Q,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=n(I.point1),y=n(I.point2);if(B==null||y==null){s(I,!1);return}s(I,!0);let w=I.container;w.getElementsByTagName("polyline")[0].setAttribute("points",B.x+","+B.y+" "+y.x+","+y.y);let M=(B.x+y.x)/2,D=(B.y+y.y)/2-30;w.getElementsByTagName("rect")[0].setAttribute("x",M-50),w.getElementsByTagName("rect")[0].setAttribute("y",D-12.5),w.getElementsByTagName("text")[0].setAttribute("x",M),w.getElementsByTagName("text")[0].setAttribute("y",D+4),w.getElementsByTagName("text")[0].innerHTML=I.text,w.style.top="0px",w.style.left="0px"}function u(I){if(I.container==null){let b=['<svg class="measureSvg">','<circle class="measurePointer" cx="0" cy="0" r="5" fill="#f99d0b" />','<rect x="0" y="-25" width="100" height="25" class="measureBack" />','<text x="50" y="-11" text-anchor="middle" class="measureLabel"> X: '+e.getMeasureText(I.textX,1)+"</text>",'<rect x="0" y="-10" width="100" height="25" class="measureBack" />','<text x="50" y="25" text-anchor="middle" class="measureLabel"> Y: '+e.getMeasureText(-I.textZ,1)+"</text>",'<rect x="0" y="10" width="100" height="25" class="measureBack" />','<text x="50" y="51" text-anchor="middle" class="measureLabel"> Z: '+e.getMeasureText(I.textY,1)+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="coordinate-annotation",I.container.id=I.id,I.container.style.position="absolute",I.container.style.pointerEvents="none",I.container.innerHTML=b,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=I.container,y=n(I.point);if(y==null){s(I,!1);return}s(I,!0),B.style.top="0px",B.style.left="0px";let w=B.getElementsByTagName("circle")[0];w&&(w.setAttribute("cx",y.x),w.setAttribute("cy",y.y));let M=B.getElementsByTagName("rect"),D=B.getElementsByTagName("text"),Q=-55;M[0]&&(M[0].setAttribute("x",y.x+10),M[0].setAttribute("y",y.y+10+Q)),D[0]&&(D[0].setAttribute("x",y.x+10+50),D[0].setAttribute("y",y.y+10+16+Q)),M[1]&&(M[1].setAttribute("x",y.x+10),M[1].setAttribute("y",y.y+10+30+Q)),D[1]&&(D[1].setAttribute("x",y.x+10+50),D[1].setAttribute("y",y.y+10+46+Q)),M[2]&&(M[2].setAttribute("x",y.x+10),M[2].setAttribute("y",y.y+10+60+Q)),D[2]&&(D[2].setAttribute("x",y.x+10+50),D[2].setAttribute("y",y.y+10+76+Q)),D[0]&&(D[0].innerHTML="X: "+e.getMeasureText(I.textX,1)),D[1]&&(D[1].innerHTML="Y: "+e.getMeasureText(-I.textZ,1)),D[2]&&(D[2].innerHTML="Z: "+e.getMeasureText(I.textY,1))}function p(I){if(I.container==null){let w=['<svg width="100" height="50" class="measureSvg">','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(I.text,1)+"</text>",'<polyline class="measureLine" stroke-width="2" points="80,32 0,32 16,48 32,32" style="fill: none; opacity: 1;"/>',"</svg>"].join("");I.container=document.createElement("div"),I.container.className="elevation-annotation",I.container.id=I.id,I.container.style.position="absolute",I.container.style.pointerEvents="none",I.container.innerHTML=w,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=I.container,y=n(I.point);if(y==null){s(I,!1);return}s(I,!0),B.style.top=y.y-48+"px",B.style.left=y.x-16+"px",B.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(I.text,1)}function m(I){if(I.container==null){let M=['<svg class="measureSvg">','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<circle class="measurePointer" cx="50" cy="50" r="5" fill="#f99d0b" />','<polyline class="measureLine" stroke="orange" stroke-width="2" points="80,32 0,32" style="fill: none; opacity: 1;"/>','<rect x="0" y="0" width="100" height="25" class="measureBack" />','<text x="50" y="16" text-anchor="middle" class="measureLabel"> '+e.getMeasureText(I.text,1)+"</text>","</svg>"].join("");I.container=document.createElement("div"),I.container.className="normal-annotation",I.container.id=I.id,I.container.innerHTML=M,e.engine.measure.annotationContainer.appendChild(I.container),I.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0,e.engine.events.trigger(ia.MeasureClick,I)}),I.isSelect&&(I.container.getElementsByTagName("svg")[0].classList.add("Hight"),I.highlight=!0)}let B=I.container;if(I.point1==null||I.point2==null){B.style.display="none";return}else B.style.display="block";let y=n(I.point1),w=n(I.point2);if(y==null||w==null){s(I,!1);return}s(I,!0),B.getElementsByTagName("polyline")[0].setAttribute("points",y.x+","+y.y+" "+w.x+","+w.y),B.getElementsByTagName("circle")[0].setAttribute("cx",y.x),B.getElementsByTagName("circle")[0].setAttribute("cy",y.y),B.getElementsByTagName("circle")[1].setAttribute("cx",w.x),B.getElementsByTagName("circle")[1].setAttribute("cy",w.y),B.getElementsByTagName("rect")[0].setAttribute("x",y.x*.5+w.x*.5-40),B.getElementsByTagName("rect")[0].setAttribute("y",y.y*.5+w.y*.5-12.5),B.getElementsByTagName("text")[0].setAttribute("x",y.x*.5+w.x*.5+50-40),B.getElementsByTagName("text")[0].setAttribute("y",y.y*.5+w.y*.5+16-12.5),B.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(I.text,1),B.style.top="0px",B.style.left="0px"}}},hMt=class{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}setDirection(e){this.catchDir=e===0?0:1}handelKeyTabDown(e){e.preventDefault(),!e.repeat&&(this.catchDir=this.catchDir===0?1:0)}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let s=0;s<e.length;s++){const o=e[s];if(!o)continue;typeof o.updateMatrixWorld=="function"&&o.updateMatrixWorld(!0);const r=new Wt().setFromObject(o);!Number.isFinite(r.min.y)||!Number.isFinite(r.max.y)||(r.min.y<t&&(t=r.min.y),r.max.y>n&&(n=r.max.y))}return!Number.isFinite(t)||!Number.isFinite(n)?null:{minY:t,maxY:n}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let o=this.engine.interactionModule.getCatchMeshs(e);var n=this.getMeshesMinMaxY(o);this.catchDir==0?t.set(t.x,n?.minY,t.z):t.set(t.x,n?.maxY,t.z)}else t=e.catch.point;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(t);return}let s=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);s!=null&&(s.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);t==null&&(t={text:null,id:$a(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=e.catch;if(this.type=="element"){let s=e.catch.point.clone();s.set(s.x,this.points[0].y,s.z);let o=new Ao(s.add(new N(0,.01*(this.catchDir==0?-1:1),0)),new N(0,this.catchDir==0?-1:1,0));n.point=this.points[0];const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(o))??this.engine.octreeBox.rayInterationModel(o);if(r.length===0){t.point2=null;return}t.point1=s,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(ia.MeasureChanged,t)}else{let s=new Ao(e.catch.point.clone().add(new N(0,.01*(this.catchDir==0?-1:1),0)),new N(0,this.catchDir==0?-1:1,0));const o=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(s))??this.engine.octreeBox.rayInterationModel(s);if(o.length===0){t.point2=null;return}t.point1=n.point,t.point2=o[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(ia.MeasureChanged,t)}}},dMt=class{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.engine.handelBehaved.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point),this.behavior.setLastPoint(t.point);else if(this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);if(n==null)return;n.point2=t.point,n.isSelect=!1,this.points=[],this.engine.events.trigger(ia.MeasureChanged,n),this.behavior.clearLastPoint()}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);n==null&&(n={id:$a(),point1:this.points[0].clone(),point2:t.point.clone(),text:this.points[0].clone().distanceTo(t.point.clone()),type:"distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(n)),n.point2=t.point,n.text=n.point1.clone().distanceTo(n.point2.clone())}}},gMt=class{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseClick(e){if(e.catch==null)return;if(this.points.length==0){this.engine.measure.tools.clearHighlight(),this.points.push(e.catch.point);return}let t=this.engine.measure.annotationData.normalAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.isSelect=!1)}handleMouseMove(e){if(e.catch==null||this.points.length==0)return;let t=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);t==null&&(t={text:null,id:$a(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let n=new Ao(e.catch.point.clone().add(e.catch.face.normal.clone().setLength(.01)),e.catch.face.normal);const s=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(n))??this.engine.octreeBox.rayInterationModel(n);if(s.length==0){t.point2=null;return}let o=e.catch;t.point1=o.point,t.point2=s[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(ia.MeasureChanged,t)}},uMt=class{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.text=e.catch.point.y)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.elevationAnnotation.find(n=>n.isSelect==!0);if(t==null){t={id:$a(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t);return}t.point=e.catch.point.clone(),t.text=e.catch.point.y,t.isSelect=!1,this.engine.events.trigger(ia.MeasureChanged,t)}},fMt=class{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.isActive=!0;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.isActive=!1,this.behavior?.disActive()}clearAllPoints(){this.points=[]}handleMouseUp(e){this.engine.deviceType!="PC"&&this.createMeasure()}handleMouseMove(e){if(e.catch==null)return;let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);t!=null&&(t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z)}handleMouseClick(e){if(e.catch==null)return;this.engine.measure.tools.clearHighlight();let t=this.engine.measure.annotationData.coordinateAnnotation.find(n=>n.isSelect==!0);if(t==null){t={id:$a(),point:e.catch.point.clone(),text:Math.round(e.catch.point.y)+" m",isSelect:!0,type:"point"},this.engine.measure.annotationData.coordinateAnnotation.push(t);return}t.point=e.catch.point.clone(),t.textX=e.catch.point.x,t.textY=e.catch.point.y,t.textZ=e.catch.point.z,t.isSelect=!1,this.engine.events.trigger(ia.MeasureChanged,t)}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(ia.MeasureChanged,e))}},pMt=class{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateAngle(e,t,n){const s=new N().subVectors(e,t),o=new N().subVectors(n,t),r=s.length(),A=o.length();if(r===0||A===0)return 0;const l=s.dot(o)/(r*A),c=Math.max(-1,Math.min(1,l));return Math.acos(c)*(180/Math.PI)}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point);else if(this.points.length==1)this.points.push(t.point);else if(this.points.length==2){let n=this.engine.measure.annotationData.angleAnnotation.find(s=>s.isSelect==!0);if(n==null)return;n.point3=t.point.clone(),n.angle=this.calculateAngle(n.point1,n.point2,n.point3),n.text=n.angle.toFixed(2)+"°",n.isSelect=!1,n.type="angle",this.points=[],this.engine.events.trigger(ia.MeasureChanged,n)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(n=>n.isSelect==!0);t==null&&(t={id:$a(),point1:this.points[0].clone(),point2:this.points[1].clone(),point3:e.catch.point.clone(),angle:0,text:"0.00°",isSelect:!0,type:"angle"},this.engine.measure.annotationData.angleAnnotation.push(t)),t.point3=e.catch.point.clone(),t.angle=this.calculateAngle(t.point1,t.point2,t.point3),t.text=t.angle.toFixed(2)+"°",console.log("角度",t.text)}}},IMt=class{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}getCurrentDrawingMeasure(){return this.engine.measure.annotationData.areaAnnotation.find(e=>e.isSelect==!0)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;const e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateArea(e){if(e.length<3)return 0;const t=e.length,n=new N(0,0,0);for(let s=0;s<t;s++){const o=(s+1)%t;n.x+=(e[s].y-e[o].y)*(e[s].z+e[o].z),n.y+=(e[s].z-e[o].z)*(e[s].x+e[o].x),n.z+=(e[s].x-e[o].x)*(e[s].y+e[o].y)}return n.length()/2}handleRightMouseClick(){this.finishMeasure()}handleMouseClick(e){if(e.catch==null)return;const t=e.catch;this.points.length===0&&this.engine.measure.tools.clearHighlight(),this.points.push(t.point.clone());let n=this.getCurrentDrawingMeasure();n==null?(n={id:$a(),points:this.points.map(s=>s.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(n)):n.points=this.points.map(s=>s.clone()),this.points.length>=3?(n.area=this.calculateArea(this.points),n.text=n.area):(n.area=0,n.text=0)}handleMouseMove(e){if(e.catch!=null&&this.points.length>=1){let t=this.getCurrentDrawingMeasure();t==null&&(t={id:$a(),points:[],area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t));const n=this.points.map(s=>s.clone());n.push(e.catch.point.clone()),t.points=n,n.length>=3?(t.area=this.calculateArea(n),t.text=t.area):(t.area=0,t.text=0)}}handelKeyEnterDown(){this.finishMeasure()}finishMeasure(){const e=this.getCurrentDrawingMeasure();e!=null&&this.points.length>=3?(e.points=this.points.map(t=>t.clone()),e.area=this.calculateArea(e.points),e.text=e.area,e.isSelect=!1,this.points=[],this.engine.events.trigger(ia.MeasureChanged,e)):this.engine.measure.tools.handelKeyEscDown()}},mMt=class d8{engine;tools;static WORLD_UP=new N(0,1,0);static SLOPE_DIRECTION_SNAP_DISTANCE=10;points=[];behavior;constructor(e){this.engine=e,this.tools=new xB(e)}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1;let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.behavior?.disActive()}clearAllPoints(){this.points=[]}calculateSlope(e,t){const n=t.y-e.y,s=t.x-e.x,o=t.z-e.z,r=Math.sqrt(s*s+o*o);if(r===0)return{percentage:0,angle:0,heightDiff:n,horizontalDist:0,type:"slope"};const A=n/r*100,l=Math.atan(n/r)*(180/Math.PI);return{percentage:A,angle:l,heightDiff:n,horizontalDist:r,type:"slope"}}getWorldFaceNormal(e){const t=e?.normal??e?.face?.normal;if(t==null)return null;const n=t.clone(),s=e?.matrix??e?.object?.matrixWorld;return s!=null&&n.transformDirection(s),n.lengthSq()<1e-10?null:n.normalize()}getFaceSlopeDirection(e){const t=this.getWorldFaceNormal(e);if(t==null)return null;const n=new N().crossVectors(t,d8.WORLD_UP);if(n.lengthSq()<1e-10)return null;const s=new N().crossVectors(n.normalize(),t);return s.lengthSq()<1e-10?null:s.normalize()}pointToScreenLineDistance(e,t,n){const s=new Ne().subVectors(n,t),o=s.lengthSq();if(o<1e-10)return e.distanceTo(t);const r=new Ne().subVectors(e,t).dot(s)/o,A=t.clone().add(s.multiplyScalar(r));return e.distanceTo(A)}isNearSlopeDirection(e,t,n,s,o){const r=new po(this.engine.camera,this.engine.renderer,this.engine.scene),A=r.worldToScreenIfVisible(e);if(A==null)return!1;const a=Number.isFinite(o?.offsetX)&&Number.isFinite(o?.offsetY)?new Ne(o.offsetX,o.offsetY):r.worldToScreenIfVisible(s);if(a==null)return!1;const l=Math.max(e.distanceTo(s),e.distanceTo(n),1),c=e.clone().add(t.clone().multiplyScalar(l)),h=r.worldToScreenIfVisible(c);if(h!=null)return this.pointToScreenLineDistance(a,A,h)<=d8.SLOPE_DIRECTION_SNAP_DISTANCE;const d=r.worldToScreenIfVisible(n);return d!=null&&a.distanceTo(d)<=d8.SLOPE_DIRECTION_SNAP_DISTANCE}getSlopeSnappedPoint(e,t,n){const s=t?.point;if(!(s instanceof N))return e.clone();const o=this.getFaceSlopeDirection(t);if(o==null)return s.clone();const r=new N().subVectors(s,e).dot(o);if(!Number.isFinite(r))return s.clone();const A=e.clone().add(o.clone().multiplyScalar(r));return this.isNearSlopeDirection(e,o,A,s,n)?A:s.clone()}updateSlopeMeasure(e,t,n){e.point2=t.clone();const s=this.calculateSlope(e.point1,e.point2);e.slopePercentage=s.percentage,e.slopeAngle=s.angle,e.heightDiff=s.heightDiff,e.horizontalDist=s.horizontalDist,e.text=s.percentage.toFixed(2)+"%";const o=this.getWorldFaceNormal(n),r=this.getFaceSlopeDirection(n);e.faceNormal=o?.clone(),e.slopeDirection=r?.clone(),e.isSlopeDirectionSnapped=n?.point instanceof N?t.distanceTo(n.point)>1e-8:!1}handleMouseClick(e){if(e.catch==null)return;let t=e.catch;if(this.points.length==0)this.engine.measure.tools.clearHighlight(),this.points.push(t.point.clone());else if(this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(o=>o.isSelect==!0);if(n==null)return;const s=this.getSlopeSnappedPoint(n.point1,t,e);this.updateSlopeMeasure(n,s,t),n.isSelect=!1,this.points=[],this.engine.events.trigger(ia.MeasureChanged,n)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let n=this.engine.measure.annotationData.slopeAnnotation.find(o=>o.isSelect==!0);n==null&&(n={id:$a(),point1:this.points[0].clone(),point2:this.getSlopeSnappedPoint(this.points[0],t,e),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00%",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(n));const s=this.getSlopeSnappedPoint(n.point1,t,e);this.updateSlopeMeasure(n,s,t)}}},CMt=class{engine;isActive=!1;points=[];behavior;constructor(e){this.engine=e}active(){this.engine.measure.tools.cancelCurrentSelectedAnnotation(),this.isActive=!0,this.points=[],this.behavior=this.engine.handelBehaved,this.behavior.init(this,{showCatch:!0}),this.behavior.active(),this.behavior.isClickSimpleModel=!1,this.behavior.clearLastPoint?.();let e=this.engine.measure.annotationData.normalAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1)}disActive(){this.points=[],this.isActive=!1,this.behavior?.clearLastPoint?.(),this.behavior?.disActive?.()}clearAllPoints(){this.points=[],this.behavior?.clearLastPoint?.()}handleMouseClick(e){if(e.catch==null)return;if(this.points.length===0){this.engine.measure.tools.clearHighlight(),this.points=[e.catch.point.clone()],this.behavior?.setLastPoint?.(e.catch.point.clone());return}const t=this.getFaceInfo(e.catch);if(t==null)return;const n=this.points[0].clone(),s=this.projectPointToFace(n,t);if(s==null)return;let o=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);o==null&&(o={id:$a(),type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(o)),o.point1=n,o.point2=s.footPoint,o.text=s.distance,o.facePoint=t.point.clone(),o.faceNormal=t.normal.clone(),o.isSelect=!1,this.points=[],this.behavior?.clearLastPoint?.(),this.engine.events.trigger(ia.MeasureChanged,o)}handleMouseMove(e){if(e.catch==null||this.points.length!==1)return;const t=this.getFaceInfo(e.catch);if(t==null)return;const n=this.points[0].clone(),s=this.projectPointToFace(n,t);if(s==null)return;let o=this.engine.measure.annotationData.normalAnnotation.find(r=>r.isSelect==!0);o==null&&(o={id:$a(),point1:n.clone(),point2:s.footPoint.clone(),text:s.distance,type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(o)),o.point1=n,o.point2=s.footPoint,o.text=s.distance,o.facePoint=t.point.clone(),o.faceNormal=t.normal.clone()}getFaceInfo(e){if(e?.face==null||e?.point==null)return null;const t=e.point.clone?.(),n=this.getWorldFaceNormal(e);return!(t instanceof N)||n==null?null:{point:t,normal:n}}getWorldFaceNormal(e){const t=e?.normal??e?.face?.normal;if(t==null)return null;const n=t.clone(),s=e?.matrix??e?.object?.matrixWorld;return s!=null&&n.transformDirection(s),n.lengthSq()<1e-10?null:n.normalize()}projectPointToFace(e,t){const n=new N().subVectors(e,t.point).dot(t.normal),s=e.clone().sub(t.normal.clone().multiplyScalar(n));return{footPoint:s,distance:e.distanceTo(s)}}},EMt=class{isActive=!1;engine;clearHeightMeasure;distanceMeasure;clearDistanceMeasure;elevationMeasure;pointMeasure;angleMeasure;areaMeasure;slopeMeasure;faceDistanceMeasure;tools;annotationContainer;annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]};constructor(e){this.engine=e,this.clearHeightMeasure=new hMt(e),this.distanceMeasure=new dMt(e),this.clearDistanceMeasure=new gMt(e),this.elevationMeasure=new uMt(e),this.pointMeasure=new fMt(e),this.angleMeasure=new pMt(e),this.areaMeasure=new IMt(e),this.slopeMeasure=new mMt(e),this.faceDistanceMeasure=new CMt(e),this.tools=new xB(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}setContextMenuDisabled(e){this.engine?.engineStatus!=null&&(this.engine.engineStatus.isDisableContextMenu=e)}active(){this.isActive=!0,this.engine.setIdleFrameRateExempt?.("measure",!0),this.setContextMenuDisabled(!0),this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){this.engine.setIdleFrameRateExempt?.("measure",!1),this.setContextMenuDisabled(!1),this.tools.disActive(),this.clearAll(),this.isActive=!1,this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}quitDraw(){this.setContextMenuDisabled(!1),this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active()}clearAllPoints(){this.clearHeightMeasure.clearAllPoints(),this.distanceMeasure.clearAllPoints(),this.clearDistanceMeasure.clearAllPoints(),this.elevationMeasure.clearAllPoints(),this.pointMeasure.clearAllPoints(),this.angleMeasure.clearAllPoints(),this.areaMeasure.clearAllPoints(),this.slopeMeasure.clearAllPoints(),this.faceDistanceMeasure.clearAllPoints()}clearAll(){e(this.annotationData.normalAnnotation),e(this.annotationData.textAnnotation),e(this.annotationData.coordinateAnnotation),e(this.annotationData.angleAnnotation),e(this.annotationData.distanceAnnotation),e(this.annotationData.areaAnnotation),e(this.annotationData.slopeAnnotation),e(this.annotationData.elevationAnnotation),e(this.annotationData.volumeAnnotation);function e(t){for(let n=0;n<t.length;n++)t[n].container.remove()}this.annotationData={normalAnnotation:[],textAnnotation:[],coordinateAnnotation:[],angleAnnotation:[],distanceAnnotation:[],areaAnnotation:[],slopeAnnotation:[],elevationAnnotation:[],volumeAnnotation:[]}}saveSetting(e){this.tools.saveSetting(e)}getSetting(){return this.tools.getSetting()}update(){this.isActive&&this.tools.drawNormalAnnotation()}dispose(){this.engine.setIdleFrameRateExempt?.("measure",!1),this.setContextMenuDisabled(!1),this.tools.disActive(),this.clearHeightMeasure.disActive(),this.distanceMeasure.disActive(),this.clearDistanceMeasure.disActive(),this.elevationMeasure.disActive(),this.pointMeasure.disActive(),this.angleMeasure.disActive(),this.areaMeasure.disActive(),this.slopeMeasure.disActive(),this.faceDistanceMeasure.disActive(),this.clearAll(),this.annotationContainer.remove(),this.isActive=!1}};var Pa=(i=>(i.ModelLoadStart="model-load-start",i.ModelLoadProgress="model-load-progress",i.ModelLoaded="model-loaded",i.ModelError="model-error",i.SelectionChanged="selection-changed",i.HoverChanged="hover-changed",i.Click="click",i.MouseMove="mouse-move",i.ModelPlaceSelected="model-place-selected",i.ModelCalibrationChanged="model-calibration-changed",i.CameraChanged="camera-changed",i.CameraIdle="camera-idle",i.EngineFree="engine-free",i.EngineBusy="engine-busy",i.MeasureChanged="measure-changed",i.MeasureClick="measure-click",i.SectionMove="section-move",i.LoadingCompleted="loading_completed",i))(Pa||{});class VSe{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;faceIdleOpacity=0;faceHoverOpacity=.05;mobileLongPressDelay=2e3;mobileLongPressMoveTolerance=10;touchLongPressTimer=null;touchLongPressActive=!1;touchStartPosition=null;touchLatestEvent=null;transformControls=new Map;transformAnchors=new Map;transformHelpers=new Map;faceMetaMap=new Map;isSyncingTransform=!1;transformHandleSize=1.05;transformHandleColor=255;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),n=t.intersectObjects(this.getInteractiveMeshes(),!1);n.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:n}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),n=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:n})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeTouchStart=e=>{if(!this.isActive||e.touches.length!==1||!this.isMobileDevice()){this.resetTouchLongPressState();return}const t=this.createMouseEventFromTouch(e);if(!t)return;if(this.createRaycasterFromMouseEvent(t).intersectObjects(this.getInteractiveMeshes(),!1).length===0){this.resetTouchLongPressState();return}e.preventDefault(),e.stopImmediatePropagation(),this.resetTouchLongPressState(),this.touchLatestEvent=t,this.touchStartPosition=this.getTouchPoint(e),this.touchLongPressTimer=window.setTimeout(()=>{const o=this.touchLatestEvent;if(!o||!this.isActive)return;const r=this.createRaycasterFromMouseEvent(o),A=r.intersectObjects(this.getInteractiveMeshes(),!1);A.length!==0&&(this.touchLongPressActive=!0,this.handleMouseDown({button:0,raycaster:r,intersects:A}))},this.mobileLongPressDelay)};handleNativeTouchMove=e=>{if(!this.isMobileDevice())return;if(e.touches.length!==1){this.resetTouchLongPressState();return}const t=this.createMouseEventFromTouch(e);if(!t)return;this.touchLatestEvent=t;const n=this.getTouchPoint(e);if(!this.touchLongPressActive&&this.touchStartPosition&&n&&this.touchStartPosition.distanceTo(n)>this.mobileLongPressMoveTolerance&&this.clearTouchLongPressTimer(),!this.touchLongPressActive)return;e.preventDefault(),e.stopImmediatePropagation();const s=this.createRaycasterFromMouseEvent(t),o=s.intersectObjects(this.getInteractiveMeshes(),!1);this.handleMouseMove({raycaster:s,intersects:o})};handleNativeTouchEnd=e=>{this.isMobileDevice()&&(this.clearTouchLongPressTimer(),this.touchLongPressActive&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:0})),this.resetTouchLongPressState())};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};constructor(e,t){this.engine=e,this.meshs=[]}active(){this.isActive||(this.attachListeners(),this.init(),this.setTransformControlsVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}disActive(){this.init(!1),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.clearClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlsVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlsVisible(!0),this.updateClippingBoxFill(),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")||(t.visible=!0)})}),this.isActive=!0)}init(e=!0){const t=this.engine.octreeBox.getBoundingBox();t.min.x-=.1,t.min.y-=.1,t.min.z-=.1,t.max.x+=.1,t.max.y+=.1,t.max.z+=.1,this.maxBox=JSON.parse(JSON.stringify(t)),this.box=t,this.updata_face(t),e&&this.updateClippingBoxFill()}getboxXyz(){return{minX:this.box.min.x,minY:this.box.min.y,minZ:this.box.min.z,maxX:this.box.max.x,maxY:this.box.max.y,maxZ:this.box.max.z}}setboxXyz(e){this.box.min.x=e.minX,this.box.min.y=e.minY,this.box.min.z=e.minZ,this.box.max.x=e.maxX,this.box.max.y=e.maxY,this.box.max.z=e.maxZ,this.updata_face(this.box),this.updateClippingBoxFill()}setBox(e){this.box=e,this.updata_face(e),this.updateClippingBoxFill()}reverseBox(){}handleMouseDown(e){const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0){this.clearClippingBoxFill();const n=t[0];this.isDrag=!0,this.pickPoint=n.point.clone(),this.pickMesh=n.object;const s=this.pickMesh?.userData?.dragNormal?.clone?.(),o=n.face?.normal?.clone?.();if(this.pickNormal=(s??o??new N(0,0,1)).clone().normalize(),this.engine.controls.enabled=!1,this.box_={min:this.box.min.clone(),max:this.box.max.clone()},this.pickNormal.y==0){const r=new Fn;r.setFromNormalAndCoplanarPoint(new N(0,1,0),this.pickPoint),this.plane=r}else{const r=new N(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),A=new Fn;A.setFromNormalAndCoplanarPoint(r.clone().sub(this.pickPoint.clone()).setLength(1),this.pickPoint),this.plane=A}}else this.isDrag=!1}handleMouseUp(e,t=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.pickMesh=null,this.plane=null,this.engine.controls.enabled=!0,t&&this.updateClippingBoxFill()}clampVector3(e,t,n){return new N(Math.max(t.x,Math.min(n.x,e.x)),Math.max(t.y,Math.min(n.y,e.y)),Math.max(t.z,Math.min(n.z,e.z)))}handleMouseMove(e){this.resetMeshOpacity();const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0&&(t[0].object.material.opacity=this.faceHoverOpacity),this.pickPoint!=null){const n=new N;if(e.raycaster.ray.intersectPlane(this.plane,n)){const s=n.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(!!this.pickMesh?.userData?.isMinFace){const r=this.box_.min.clone().add(this.pickNormal.clone().setLength(s));this.box.min=this.clampVector3(r,this.maxBox.min,this.box.max)}else{const r=this.box_.max.clone().add(this.pickNormal.clone().setLength(s));this.box.max=this.clampVector3(r,this.box.min,this.maxBox.max)}this.updata_face(this.box),this.calculate_ratio()}}}calculate_ratio(){const e=this.maxBox.max.x-this.maxBox.min.x,t=this.maxBox.max.y-this.maxBox.min.y,n=this.maxBox.max.z-this.maxBox.min.z,s=this.toPercent((this.box.min.x-this.maxBox.min.x)/e*100),o=this.toPercent((this.box.max.x-this.maxBox.min.x)/e*100),r=this.toPercent((this.box.min.y-this.maxBox.min.y)/t*100),A=this.toPercent((this.box.max.y-this.maxBox.min.y)/t*100),a=this.toPercent((this.box.min.z-this.maxBox.min.z)/n*100),l=this.toPercent((this.box.max.z-this.maxBox.min.z)/n*100),c={x:{min:s,max:o},y:{min:r,max:A},z:{min:a,max:l}};this.engine.events.trigger(Pa.SectionMove,c)}toPercent(e){return e<0?0:e>100?100:e}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const t=new Ao,n=new Ne,s=this.engine.renderer.domElement.clientWidth,o=this.engine.renderer.domElement.clientHeight;return n.x=e.offsetX/s*2-1,n.y=-(e.offsetY/o)*2+1,t.setFromCamera(n,this.engine.camera),t}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getTouchPoint(e){const t=e.touches[0]||e.changedTouches[0];return t?new Ne(t.clientX,t.clientY):null}createMouseEventFromTouch(e){const t=e.touches[0]||e.changedTouches[0],n=this.engine.renderer?.domElement;if(!t||!n)return null;const s=n.getBoundingClientRect();return{offsetX:t.clientX-s.left,offsetY:t.clientY-s.top,clientX:t.clientX,clientY:t.clientY,button:0}}clearTouchLongPressTimer(){this.touchLongPressTimer!=null&&(clearTimeout(this.touchLongPressTimer),this.touchLongPressTimer=null)}resetTouchLongPressState(){this.clearTouchLongPressTimer(),this.touchLongPressActive=!1,this.touchStartPosition=null,this.touchLatestEvent=null}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),e.addEventListener("touchstart",this.handleNativeTouchStart,{capture:!0,passive:!1}),e.addEventListener("touchmove",this.handleNativeTouchMove,{capture:!0,passive:!1}),e.addEventListener("touchend",this.handleNativeTouchEnd,{capture:!0,passive:!1}),e.addEventListener("touchcancel",this.handleNativeTouchEnd,{capture:!0,passive:!1}),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0),e.removeEventListener("touchstart",this.handleNativeTouchStart,!0),e.removeEventListener("touchmove",this.handleNativeTouchMove,!0),e.removeEventListener("touchend",this.handleNativeTouchEnd,!0),e.removeEventListener("touchcancel",this.handleNativeTouchEnd,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1,this.resetTouchLongPressState()}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.faceIdleOpacity)})}updateClippingBoxFill(){const e=(Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[]).slice(0,6).filter(t=>t instanceof Fn);if(e.length===0){this.clearClippingBoxFill();return}this.engine.clipping?.clippingCSGSimple?.updataFaces?.(e)}clearClippingBoxFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}getFaceTransformOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}keepSingleDirectionArrow(e,t="X"){const n=e.getHelper(),s=[];n.traverse(o=>{if(o?.name!==t||!o.geometry)return;const r=o.geometry;r.boundingBox||r.computeBoundingBox();const A=r.boundingBox;if(!A)return;const a=A.getCenter(new N);if(!(t==="X"&&a.x<0||t==="Y"&&a.y<0||t==="Z"&&a.z<0))return;const c=r.parameters,h=c&&c.radiusTop===0&&c.radiusBottom===.04&&c.height===.1,d=c&&c.radiusTop===.2&&c.radiusBottom===0&&c.height===.6;(h||d)&&s.push(o)}),s.forEach(o=>{o.parent?.remove(o)})}setTransformControlsVisible(e){this.transformControls.forEach(t=>{t.enabled=e}),this.transformHelpers.forEach(t=>{t.visible=e}),this.transformAnchors.forEach(t=>{t.visible=e}),e||(this.engine.controls.enabled=!0)}ensureFaceTransformControl(e){if(this.transformControls.has(e)&&this.transformAnchors.has(e))return;const t=this.engine.renderer?.domElement,n=this.engine.camera;if(!t||!n)return;const s=new Wn;s.name=`SectionBoxTransformAnchor_${e}`,s.visible=this.isActive,this.engine.scene.add(s);const o=new rS(n,t);o.name=`SectionBoxTransformControl_${e}`,o.setMode("translate"),o.setSpace("local"),o.showX=!0,o.showY=!1,o.showZ=!1,o.size=this.transformHandleSize,o.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),o.enabled=this.isActive,o.attach(s),this.keepSingleDirectionArrow(o,"X"),o.addEventListener("dragging-changed",A=>{this.engine.controls.enabled=!A.value,A.value===!0?this.clearClippingBoxFill():this.updateClippingBoxFill()}),o.addEventListener("objectChange",()=>{this.handleTransformObjectChange(e)});const r=o.getHelper();r.userData.excludeFromAmbientOcclusion=!0,r.visible=this.isActive,this.engine.scene.add(r),this.transformAnchors.set(e,s),this.transformControls.set(e,o),this.transformHelpers.set(e,r)}updateFaceTransformControl(e,t,n,s){this.ensureFaceTransformControl(e);const o=this.transformAnchors.get(e),r=this.transformControls.get(e);if(!o||!r)return;const A=this.getFaceTransformOffset(),a=new nn().setFromUnitVectors(new N(1,0,0),t.clone().normalize()),l=n.clone().add(t.clone().setLength(A));this.faceMetaMap.set(e,{normal:t.clone().normalize(),isMinFace:s,center:n.clone()}),this.isSyncingTransform=!0,o.position.copy(l),o.quaternion.copy(a),o.visible=this.isActive,r.object!==o&&r.attach(o),r.enabled=this.isActive;const c=this.transformHelpers.get(e);c&&(c.visible=this.isActive),this.isSyncingTransform=!1}getDominantAxis(e){const t=Math.abs(e.x),n=Math.abs(e.y),s=Math.abs(e.z);return t>=n&&t>=s?"x":n>=t&&n>=s?"y":"z"}handleTransformObjectChange(e){if(this.isSyncingTransform)return;const t=this.transformAnchors.get(e),n=this.faceMetaMap.get(e);if(!t||!n||!this.box||!this.maxBox)return;const s=n.normal,o=this.getDominantAxis(s),r=this.getFaceTransformOffset(),A=s[o],a=t.position[o]-A*r;if(n.isMinFace){const l=this.maxBox.min[o],c=this.box.max[o];this.box.min[o]=Math.max(l,Math.min(c,a))}else{const l=this.box.min[o],c=this.maxBox.max[o];this.box.max[o]=Math.max(l,Math.min(c,a))}this.updata_face(this.box),this.calculate_ratio()}updata_face(e){let t=this.engine.scene.children.find(s=>s.type=="Group"&&s.name=="ClippingBox");t==null&&(t=new qn,t.name="ClippingBox",this.engine.scene.add(t)),[{name:"前",normal:new N(0,0,-1),isMinFace:!0,planePoint:e.min,vertices:[new N(e.min.x,e.max.y,e.min.z),new N(e.max.x,e.max.y,e.min.z),new N(e.max.x,e.min.y,e.min.z),new N(e.min.x,e.min.y,e.min.z)]},{name:"后",normal:new N(0,0,1),isMinFace:!1,planePoint:e.max,vertices:[new N(e.min.x,e.min.y,e.max.z),new N(e.max.x,e.min.y,e.max.z),new N(e.max.x,e.max.y,e.max.z),new N(e.min.x,e.max.y,e.max.z)]},{name:"右",normal:new N(1,0,0),isMinFace:!1,planePoint:e.max,vertices:[new N(e.max.x,e.min.y,e.max.z),new N(e.max.x,e.min.y,e.min.z),new N(e.max.x,e.max.y,e.min.z),new N(e.max.x,e.max.y,e.max.z)]},{name:"左",normal:new N(-1,0,0),isMinFace:!0,planePoint:e.min,vertices:[new N(e.min.x,e.min.y,e.min.z),new N(e.min.x,e.min.y,e.max.z),new N(e.min.x,e.max.y,e.max.z),new N(e.min.x,e.max.y,e.min.z)]},{name:"顶",normal:new N(0,1,0),isMinFace:!1,planePoint:e.max,vertices:[new N(e.min.x,e.max.y,e.max.z),new N(e.max.x,e.max.y,e.max.z),new N(e.max.x,e.max.y,e.min.z),new N(e.min.x,e.max.y,e.min.z)]},{name:"底",normal:new N(0,-1,0),isMinFace:!0,planePoint:e.min,vertices:[new N(e.min.x,e.min.y,e.min.z),new N(e.max.x,e.min.y,e.min.z),new N(e.max.x,e.min.y,e.max.z),new N(e.min.x,e.min.y,e.max.z)]}].forEach(s=>{this.createFace(t,s.vertices,s.normal,s.name,s.isMinFace,s.planePoint)}),b7(this.engine).forEach(s=>{s.material&&Array.isArray(s.material)?s.material.forEach(o=>{o.clippingPlanes=this.engine.sectionPlane}):s.material.clippingPlanes=this.engine.sectionPlane})}createFace(e,t,n,s,o,r){const A=new mi,a=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),l=[0,2,1,0,3,2];A.setAttribute("position",new Bs(a,3)),A.setIndex(l);let c=this.meshs.find(I=>I.name===s);if(c==null){const I=new Ji({color:65280,transparent:!0,opacity:this.faceIdleOpacity,side:An});I.polygonOffset=!0,I.polygonOffsetFactor=1,I.polygonOffsetUnits=4,c=new lt(A,I),c.name=s,e.add(c),this.meshs.push(c)}else c.geometry=A;c.userData={dragNormal:n.clone(),isMinFace:o,faceName:s,excludeFromAmbientOcclusion:!0};const h=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),d=new bo({color:255}),g=new mi;g.setAttribute("position",new Bs(h,3));let u=this.meshs.find(I=>I.name===s+"Line");u==null?(u=new uA(g,d),u.name=s+"Line",e.add(u),this.meshs.push(u)):(u.geometry=g,u.material=d);const p=new N;t.forEach(I=>p.add(I)),p.multiplyScalar(1/t.length),this.updateFaceTransformControl(s,n,p,o);const m=this.engine.sectionPlane.find(I=>I.name==s);m&&m.setFromNormalAndCoplanarPoint(n.clone().setLength(-1),r)}}class ZSe{engine;isActive=!1;isDrag=!1;isCtrlDown=!1;listenersAttached=!1;meshs=[];box=null;pickPoint=null;pickNormal=null;plane=null;angleX=0;angleY=0;angleZ=0;direction=1;normal=new N(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;dragStartCenter=null;idleOpacity=0;hoverOpacity=.05;transformControl=null;transformAnchor=null;transformHelper=null;rotateControl=null;rotateAnchor=null;rotateHelper=null;rotatePivot=null;isSyncingTransformControl=!1;isSyncingRotateControl=!1;activeControlMode=null;moveEpsilon=1e-5;transformHandleSize=1.15;rotateHandleSize=.8;transformHandleColor=255;transformHandleHoverColor=16776960;mobileLongPressDelay=2e3;mobileLongPressMoveTolerance=10;touchLongPressTimer=null;touchLongPressActive=!1;touchStartPosition=null;touchLatestEvent=null;handleNativePointerDown=e=>{if(e.button!==0||!this.isActive)return;this.transformControl?.dragging!==!0&&this.rotateControl?.dragging!==!0&&this.releaseControlModeLock();const t=this.pickControlModeFromPointer(e);t&&this.lockControlMode(t)};handleNativePointerUp=()=>{window.setTimeout(()=>{this.transformControl?.dragging===!0||this.rotateControl?.dragging===!0||this.releaseControlModeLock()},0)};handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),n=t.intersectObjects(this.getInteractiveMeshes(),!1);n.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:n}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),n=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:n})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};handleNativeTouchStart=e=>{if(!this.isActive||e.touches.length!==1||!this.isMobileDevice()){this.resetTouchLongPressState();return}const t=this.createMouseEventFromTouch(e);if(!t)return;if(this.createRaycasterFromMouseEvent(t).intersectObjects(this.getInteractiveMeshes(),!1).length===0){this.resetTouchLongPressState();return}e.preventDefault(),e.stopImmediatePropagation(),this.resetTouchLongPressState(),this.touchLatestEvent=t,this.touchStartPosition=this.getTouchPoint(e),this.touchLongPressTimer=window.setTimeout(()=>{const o=this.touchLatestEvent;if(!o||!this.isActive)return;const r=this.createRaycasterFromMouseEvent(o),A=r.intersectObjects(this.getInteractiveMeshes(),!1);A.length!==0&&(this.touchLongPressActive=!0,this.handleMouseDown({button:0,raycaster:r,intersects:A}))},this.mobileLongPressDelay)};handleNativeTouchMove=e=>{if(!this.isMobileDevice())return;if(e.touches.length!==1){this.resetTouchLongPressState();return}const t=this.createMouseEventFromTouch(e);if(!t)return;this.touchLatestEvent=t;const n=this.getTouchPoint(e);if(!this.touchLongPressActive&&this.touchStartPosition&&n&&this.touchStartPosition.distanceTo(n)>this.mobileLongPressMoveTolerance&&this.clearTouchLongPressTimer(),!this.touchLongPressActive)return;e.preventDefault(),e.stopImmediatePropagation();const s=this.createRaycasterFromMouseEvent(t),o=s.intersectObjects(this.getInteractiveMeshes(),!1);this.handleMouseMove({raycaster:s,intersects:o})};handleNativeTouchEnd=e=>{this.isMobileDevice()&&(this.clearTouchLongPressTimer(),this.touchLongPressActive&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:0})),this.resetTouchLongPressState())};handleNativeKeyDown=e=>{e.key==="Control"&&(this.isCtrlDown=!0)};handleNativeKeyUp=e=>{e.key==="Control"&&(this.isCtrlDown=!1,this.isDrag&&this.handleMouseUp({button:0}),this.resetMeshOpacity())};handleTransformObjectChange=()=>{if(this.isSyncingTransformControl||this.activeControlMode==="rotate"||this.rotateControl?.dragging===!0||!this.transformAnchor||!this.center||!this.current_center)return;const e=this.normal.clone().normalize(),t=this.getEffectiveNormal(e),n=this.getDistanceRange(e),s=this.getTransformHandleOffset(),o=this.current_center.clone().sub(this.center).dot(e),r=this.transformAnchor.position.clone().sub(this.center).dot(e)-s*this.getDirectionSign(),A=Math.min(n.max,Math.max(n.min,r));if(Math.abs(A-Number(this.distance))>this.moveEpsilon){const a=this.current_center.clone().add(e.clone().multiplyScalar(A-o));this.updata_face(A,a)}else Math.abs(r-A)>this.moveEpsilon&&this.updateTransformControl(t)};handleRotateObjectChange=()=>{if(this.isSyncingRotateControl||this.activeControlMode==="translate"||this.transformControl?.dragging===!0||!this.rotateAnchor||!this.center||!this.current_center)return;const t=new N(0,0,1).applyQuaternion(this.rotateAnchor.quaternion).normalize().multiplyScalar(this.getDirectionSign()).normalize(),n=(this.rotatePivot??this.rotateAnchor.position??this.current_center).clone(),s=n.clone().sub(this.center).dot(t);t.lengthSq()<=this.moveEpsilon||(this.normal.copy(t),this.updata_face(s,n))};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){this.isActive!=!0&&(this.isActive=!0,this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.attachListeners(),this.ensureTransformControl(),this.ensureRotateControl(),this.setTransformControlVisible(!0),this.applyClippingToModelMeshes(),this.init())}disActive(){this.init(),this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.clearClippingFaceFill();const e=this.engine.sectionPlane.find(t=>t.name=="face");e&&(e.constant=1e5),this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(n=>{n.name.includes("face")&&(n.visible=!1)})})}init(e){const t=this.engine.octreeBox.getBoundingBox();this.box=t,this.distance=0,this.center=new N((t.min.x+t.max.x)/2,(t.min.y+t.max.y)/2,(t.min.z+t.max.z)/2),this.current_center=this.center.clone(),!e&&this.updata_face(0)}disabled(){this.isActive=!1,this.detachListeners(),this.handleMouseUp({button:0},!1),this.setTransformControlVisible(!1),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!1)})})}recover(){this.isActive||(this.attachListeners(),this.setTransformControlVisible(!0),this.engine.scene.children.filter(e=>e.type=="Group"&&e.name=="ClippingBox").forEach(e=>{e.children.forEach(t=>{t.name.includes("face")&&(t.visible=!0)})}),this.isActive=!0)}setFaceAngle(e,t,n){this.angleX=e,this.angleY=t,this.angleZ=n,this.distance=0,this.normal=new N(0,1,0).applyAxisAngle(new N(1,0,0),e).applyAxisAngle(new N(0,0,1),t).applyAxisAngle(new N(0,1,0),n).normalize(),this.updata_face(0),this.updateClippingFaceFill()}setFaceNormal(e,t=0){this.normal=e.clone().normalize(),this.distance=t,this.updata_face(t),this.updateClippingFaceFill()}setFaceNormalPlaneOnly(e,t){if(this.normal=e.clone().normalize(),this.distance=t,!this.center||!this.box)return;const n=this.engine.sectionPlane?.find(s=>s.name==="face");if(n){const s=this.center.clone().add(this.normal.clone().multiplyScalar(t));n.setFromNormalAndCoplanarPoint(this.getEffectiveNormal(),s)}this.updateClippingFaceFill()}activateClippingOnly(){this.isActive||(this.isActive=!0,this.applyClippingToModelMeshes())}reverse(){this.direction=-this.getDirectionSign(),this.applyClippingToModelMeshes(),this.updata_face(this.distance),this.updateClippingFaceFill(),this.requestShadowRefresh()}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e,t){if(!this.box)return;this.distance=e;let n=this.engine.scene.children.find(M=>M.type=="Group"&&M.name=="ClippingBox");n==null&&(n=new qn,n.name="ClippingBox",this.engine.scene.add(n));const s=this.normal.clone().normalize(),o=this.getEffectiveNormal(s),r=this.center??new N((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2);this.center=r.clone();const A=t?.clone()??r.clone().add(s.clone().multiplyScalar(e)),{tangent:a,bitangent:l}=this.getPlaneBasis(s),c=this.getBoxCorners(this.box),h=this.box.min.distanceTo(this.box.max),d=Math.max(h*.02,.01);let g=1/0,u=-1/0,p=1/0,m=-1/0;c.forEach(M=>{const D=M.clone().sub(A),Q=D.dot(a),b=D.dot(l);g=Math.min(g,Q),u=Math.max(u,Q),p=Math.min(p,b),m=Math.max(m,b)}),g-=d,u+=d,p-=d,m+=d;const I=A.clone().add(a.clone().multiplyScalar(g)).add(l.clone().multiplyScalar(p)),B=A.clone().add(a.clone().multiplyScalar(u)).add(l.clone().multiplyScalar(p)),y=A.clone().add(a.clone().multiplyScalar(u)).add(l.clone().multiplyScalar(m)),w=A.clone().add(a.clone().multiplyScalar(g)).add(l.clone().multiplyScalar(m));this.current_center=A.clone(),this.createFace(n,[I,B,y,w],s,"face"),this.updateTransformControl(o),this.updateRotateControl(o)}createFace(e,t,n,s){const o=new mi,r=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z]),A=this.getEffectiveNormal(n),a=this.getDirectionSign()===1?[0,1,2,0,2,3]:[0,2,1,0,3,2];o.setAttribute("position",new Bs(r,3)),o.setIndex(a),o.computeVertexNormals();let l=this.meshs.find(p=>p.name==s);if(l==null){const p=new Ji({color:65280,transparent:!0,opacity:this.idleOpacity,side:An});p.polygonOffset=!0,p.polygonOffsetFactor=1,p.polygonOffsetUnits=4,l=new lt(o,p),l.name=s,e.add(l),this.meshs.push(l)}else l.geometry=o;l.normal=A.clone(),l.userData.excludeFromAmbientOcclusion=!0;const c=new Float32Array([t[0].x,t[0].y,t[0].z,t[1].x,t[1].y,t[1].z,t[2].x,t[2].y,t[2].z,t[3].x,t[3].y,t[3].z,t[0].x,t[0].y,t[0].z]),h=new bo({color:255}),d=new mi;d.setAttribute("position",new Bs(c,3));let g=this.meshs.find(p=>p.name==s+"Line");g==null?(g=new uA(d,h),g.name=s+"Line",e.add(g),this.meshs.push(g)):(g.geometry=d,g.material=h);const u=this.engine.sectionPlane.find(p=>p.name==s);u&&this.current_center&&u.setFromNormalAndCoplanarPoint(A,this.current_center)}getDirectionSign(){return Number(this.direction)===-1?-1:1}getEffectiveNormal(e=this.normal){return e.clone().normalize().multiplyScalar(this.getDirectionSign())}applyClippingToModelMeshes(){const e=this.engine.sectionPlane?.find?.(t=>t.name==="face");b7(this.engine).forEach(t=>{this.applyClippingToMaterial(t.material),this.engine.clipping.clippingStencil?.addMesh(e,t)}),this.requestShadowRefresh()}applyClippingToMaterial(e){if(Array.isArray(e)){e.forEach(t=>this.applyClippingToMaterial(t));return}e&&(e.clippingPlanes=this.engine.sectionPlane,e.clipShadows=!0,e.shadowSide=An,e.needsUpdate=!0)}requestShadowRefresh(){const e=this.engine?.renderer?.shadowMap;e&&(e.needsUpdate=!0);const t=this.engine?.scene?.dirLight;t?.shadow&&(t.shadow.needsUpdate=!0)}lockControlMode(e){this.activeControlMode=e,this.applyControlModeLock()}releaseControlModeLock(){this.activeControlMode=null,this.applyControlModeLock()}applyControlModeLock(){this.transformControl&&(this.transformControl.enabled=this.isActive&&this.activeControlMode!=="rotate"),this.rotateControl&&(this.rotateControl.enabled=this.isActive&&this.activeControlMode!=="translate")}pickControlModeFromPointer(e){const t=this.raycastTransformControlPicker(this.transformControl,e),n=this.raycastTransformControlPicker(this.rotateControl,e);return t&&n?n.distance<=t.distance?"rotate":"translate":n?"rotate":t?"translate":null}raycastTransformControlPicker(e,t){if(!e||!e.object||!this.engine?.camera||!this.engine?.renderer?.domElement)return null;const n=e._gizmo?.picker?.[e.mode];if(!n)return null;const s=this.engine.renderer.domElement.getBoundingClientRect(),o=new Ne((t.clientX-s.left)/s.width*2-1,-((t.clientY-s.top)/s.height)*2+1),r=new Ao;return r.setFromCamera(o,this.engine.camera),r.intersectObject(n,!0).find(a=>a.object.visible)??null}getPlaneBasis(e){const t=new N(1,0,0),n=new N(0,1,0),s=new N(0,0,1),o=Math.abs(e.dot(t)),r=Math.abs(e.dot(n)),A=Math.abs(e.dot(s));let a=t;r<=o&&r<=A?a=n:A<=o&&A<=r&&(a=s),a=a.clone().sub(e.clone().multiplyScalar(a.dot(e))).normalize();const l=new N().crossVectors(e,a).normalize();return{tangent:a,bitangent:l}}getBoxCorners(e){return[new N(e.min.x,e.min.y,e.min.z),new N(e.min.x,e.min.y,e.max.z),new N(e.min.x,e.max.y,e.min.z),new N(e.min.x,e.max.y,e.max.z),new N(e.max.x,e.min.y,e.min.z),new N(e.max.x,e.min.y,e.max.z),new N(e.max.x,e.max.y,e.min.z),new N(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const t=this.center??new N((this.box.min.x+this.box.max.x)/2,(this.box.min.y+this.box.max.y)/2,(this.box.min.z+this.box.max.z)/2),n=this.getBoxCorners(this.box);let s=1/0,o=-1/0;return n.forEach(r=>{const A=r.clone().sub(t).dot(e);s=Math.min(s,A),o=Math.max(o,A)}),{min:s,max:o}}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}getTransformHandleOffset(){if(!this.box)return .06;const e=this.box.min.distanceTo(this.box.max);return Math.max(e*.015,.06)}getPlaneQuaternion(e){const{tangent:t,bitangent:n}=this.getPlaneBasis(e),s=new nt().makeBasis(t,n,e.clone().normalize());return new nn().setFromRotationMatrix(s)}keepSingleDirectionArrow(e,t="X"){const n=e.getHelper(),s=[];n.traverse(o=>{if(o?.name!==t||!o.geometry)return;const r=o.geometry;r.boundingBox||r.computeBoundingBox();const A=r.boundingBox;if(!A)return;const a=A.getCenter(new N);if(!(t==="X"&&a.x<0||t==="Y"&&a.y<0||t==="Z"&&a.z<0))return;const c=r.parameters,h=c&&c.radiusTop===0&&c.radiusBottom===.04&&c.height===.1,d=c&&c.radiusTop===.2&&c.radiusBottom===0&&c.height===.6;(h||d)&&s.push(o)}),s.forEach(o=>{o.parent?.remove(o)})}ensureTransformControl(){if(this.transformControl&&this.transformAnchor)return;const e=this.engine.renderer?.domElement,t=this.engine.camera;if(!e||!t)return;const n=new Wn;n.name="SectionFaceTransformAnchor",n.visible=this.isActive,this.engine.scene.add(n);const s=new rS(t,e);s.name="SectionFaceTransformControl",s.setMode("translate"),s.setSpace("local"),s.showX=!0,s.showY=!1,s.showZ=!1,s.size=this.transformHandleSize,s.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),s.enabled=this.isActive,s.attach(n),this.keepSingleDirectionArrow(s,"X"),s.addEventListener("dragging-changed",r=>{this.engine.controls.enabled=!r.value,r.value===!0?(this.lockControlMode("translate"),this.clearClippingFaceFill()):(this.updateClippingFaceFill(),this.releaseControlModeLock())}),s.addEventListener("objectChange",this.handleTransformObjectChange);const o=s.getHelper();o.userData.excludeFromAmbientOcclusion=!0,o.visible=this.isActive,this.engine.scene.add(o),this.transformAnchor=n,this.transformControl=s,this.transformHelper=o}ensureRotateControl(){if(this.rotateControl&&this.rotateAnchor)return;const e=this.engine.renderer?.domElement,t=this.engine.camera;if(!e||!t)return;const n=new Wn;n.name="SectionFaceRotateAnchor",n.visible=this.isActive,this.engine.scene.add(n);const s=new rS(t,e);s.name="SectionFaceRotateControl",s.setMode("rotate"),s.setSpace("local"),s.showX=!0,s.showY=!0,s.showZ=!1,s.size=this.rotateHandleSize,s.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),s.enabled=this.isActive,s.attach(n),s.addEventListener("dragging-changed",r=>{this.engine.controls.enabled=!r.value,r.value===!0?(this.lockControlMode("rotate"),this.rotatePivot=(this.current_center??this.rotateAnchor?.position??null)?.clone?.()??null,this.clearClippingFaceFill()):(this.rotatePivot=null,this.updateClippingFaceFill(),this.releaseControlModeLock())}),s.addEventListener("objectChange",this.handleRotateObjectChange);const o=s.getHelper();o.userData.excludeFromAmbientOcclusion=!0,o.visible=this.isActive,this.engine.scene.add(o),this.rotateAnchor=n,this.rotateControl=s,this.rotateHelper=o}setTransformControlVisible(e){this.ensureTransformControl(),this.ensureRotateControl(),e||(this.activeControlMode=null),this.transformControl&&(this.transformControl.enabled=e&&this.activeControlMode!=="rotate"),this.transformHelper&&(this.transformHelper.visible=e),this.transformAnchor&&(this.transformAnchor.visible=e),this.rotateControl&&(this.rotateControl.enabled=e&&this.activeControlMode!=="translate"),this.rotateHelper&&(this.rotateHelper.visible=e),this.rotateAnchor&&(this.rotateAnchor.visible=e),e||(this.engine.controls.enabled=!0)}updateTransformControl(e){if(this.ensureTransformControl(),!this.transformControl||!this.transformAnchor||!this.current_center)return;const t=this.getTransformHandleOffset(),n=this.current_center.clone().add(e.clone().setLength(t)),s=new nn().setFromUnitVectors(new N(1,0,0),e.clone().normalize().multiplyScalar(-1));this.isSyncingTransformControl=!0,this.transformAnchor.position.copy(n),this.transformAnchor.quaternion.copy(s),this.transformAnchor.visible=this.isActive,this.transformControl.object!==this.transformAnchor&&this.transformControl.attach(this.transformAnchor),this.applyControlModeLock(),this.transformHelper&&(this.transformHelper.visible=this.isActive),this.isSyncingTransformControl=!1}updateRotateControl(e){this.ensureRotateControl(),!(!this.rotateControl||!this.rotateAnchor||!this.current_center)&&(this.isSyncingRotateControl=!0,this.rotateAnchor.position.copy(this.current_center),this.rotateAnchor.quaternion.copy(this.getPlaneQuaternion(e)),this.rotateAnchor.visible=this.isActive,this.rotateControl.object!==this.rotateAnchor&&this.rotateControl.attach(this.rotateAnchor),this.applyControlModeLock(),this.rotateHelper&&(this.rotateHelper.visible=this.isActive),this.isSyncingRotateControl=!1)}createRaycasterFromMouseEvent(e){const t=new Ao,n=new Ne,s=this.engine.renderer.domElement.clientWidth,o=this.engine.renderer.domElement.clientHeight;return n.x=e.offsetX/s*2-1,n.y=-(e.offsetY/o)*2+1,t.setFromCamera(n,this.engine.camera),t}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getTouchPoint(e){const t=e.touches[0]||e.changedTouches[0];return t?new Ne(t.clientX,t.clientY):null}createMouseEventFromTouch(e){const t=e.touches[0]||e.changedTouches[0],n=this.engine.renderer?.domElement;if(!t||!n)return null;const s=n.getBoundingClientRect();return{offsetX:t.clientX-s.left,offsetY:t.clientY-s.top,clientX:t.clientX,clientY:t.clientY,button:0}}clearTouchLongPressTimer(){this.touchLongPressTimer!=null&&(clearTimeout(this.touchLongPressTimer),this.touchLongPressTimer=null)}resetTouchLongPressState(){this.clearTouchLongPressTimer(),this.touchLongPressActive=!1,this.touchStartPosition=null,this.touchLatestEvent=null}attachListeners(){if(this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.addEventListener("pointerdown",this.handleNativePointerDown,!0),e.addEventListener("pointerup",this.handleNativePointerUp,!0),e.addEventListener("pointercancel",this.handleNativePointerUp,!0),e.addEventListener("pointerleave",this.handleNativePointerUp,!0),e.addEventListener("mousedown",this.handleNativeMouseDown,!0),e.addEventListener("mousemove",this.handleNativeMouseMove,!0),e.addEventListener("mouseup",this.handleNativeMouseUp,!0),e.addEventListener("touchstart",this.handleNativeTouchStart,{capture:!0,passive:!1}),e.addEventListener("touchmove",this.handleNativeTouchMove,{capture:!0,passive:!1}),e.addEventListener("touchend",this.handleNativeTouchEnd,{capture:!0,passive:!1}),e.addEventListener("touchcancel",this.handleNativeTouchEnd,{capture:!0,passive:!1}),window.addEventListener("keydown",this.handleNativeKeyDown),window.addEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!0)}detachListeners(){if(!this.listenersAttached)return;const e=this.engine.renderer?.domElement;e&&(e.removeEventListener("pointerdown",this.handleNativePointerDown,!0),e.removeEventListener("pointerup",this.handleNativePointerUp,!0),e.removeEventListener("pointercancel",this.handleNativePointerUp,!0),e.removeEventListener("pointerleave",this.handleNativePointerUp,!0),e.removeEventListener("mousedown",this.handleNativeMouseDown,!0),e.removeEventListener("mousemove",this.handleNativeMouseMove,!0),e.removeEventListener("mouseup",this.handleNativeMouseUp,!0),e.removeEventListener("touchstart",this.handleNativeTouchStart,!0),e.removeEventListener("touchmove",this.handleNativeTouchMove,!0),e.removeEventListener("touchend",this.handleNativeTouchEnd,!0),e.removeEventListener("touchcancel",this.handleNativeTouchEnd,!0)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1,this.releaseControlModeLock(),this.resetTouchLongPressState()}resetMeshOpacity(){this.getInteractiveMeshes().forEach(e=>{e.material&&(e.material.opacity=this.idleOpacity)})}updateClippingFaceFill(){const e=this.engine.sectionPlane?.find?.(t=>t.name==="face");if(e){this.engine.clipping?.clippingCSGSimple?.updataFace?.(e);return}this.clearClippingFaceFill()}clearClippingFaceFill(){this.engine.clipping?.clippingCSGSimple?.clear?.()}handleMouseDown(e){const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);if(t!=null&&t.length>0){this.clearClippingFaceFill();const n=t[0],s=n.point.clone();this.isDrag=!0,this.pickPoint=s;const r=(n.face?.normal?.clone()??this.normal.clone()).clone(),A=this.getEffectiveNormal();if(r.dot(A)<0&&r.multiplyScalar(-1),r.normalize(),this.pickNormal=r,this.engine.controls.enabled=!1,this.dragStartDistance=Number(this.distance)||0,this.dragStartCenter=this.current_center?.clone()??null,r.y==0){const a=new Fn;a.setFromNormalAndCoplanarPoint(new N(0,1,0),s),this.plane=a}else{const a=new N(this.engine.camera.position.x,s.y,this.engine.camera.position.z),l=new Fn;l.setFromNormalAndCoplanarPoint(a.clone().sub(s.clone()).setLength(1),s),this.plane=l}}else this.isDrag=!1}handleMouseUp(e,t=!0){this.isDrag=!1,this.pickPoint=null,this.pickNormal=null,this.plane=null,this.dragStartCenter=null,this.engine.controls.enabled=!0,t&&this.updateClippingFaceFill()}handleMouseMove(e){this.resetMeshOpacity();const t=e.intersects??e.raycaster.intersectObjects(this.getInteractiveMeshes(),!1);t!=null&&t.length>0&&(t[0].object.material.opacity=this.hoverOpacity);const n=this.pickPoint,s=this.pickNormal,o=this.plane;if(n!=null&&s!=null&&o!=null){const r=new N;if(e.raycaster.ray.intersectPlane(o,r)){const A=r.clone().sub(n.clone()).dot(s.clone()),a=this.getDistanceRange(this.normal.clone().normalize()),l=s.dot(this.normal.clone().normalize())>=0?1:-1,c=this.dragStartDistance+A*l;this.distance=Math.min(a.max,Math.max(a.min,c));const h=(this.dragStartCenter??this.current_center)?.clone().add(this.normal.clone().normalize().multiplyScalar(this.distance-this.dragStartDistance));this.updata_face(this.distance,h)}}}}class JSe{engine;callback_;isActive;constructor(e){this.engine=e}init(){this.isActive=!0,this.engine.handelBehaved.init(this,{showCatch:!0}),this.engine.handelBehaved.active()}cancel(){this.isActive&&(this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.isActive=!1)}catch_face(e){this.callback_=e}handleMouseMove(e){}handleMouseClick(e){if(e.catch?.normal==null&&(e.catch.normal=e.catch.face?.normal),!e.catch?.normal||!e.catch?.point)return;let t=e.catch.normal.setLength(-1);this.engine.handelBehaved.disActive(),this.engine.interactionModule.init(),this.engine.interactionModule.active(),this.isActive=!1,this.callback_({dir:t,position:e.catch.point})}}function zSe(i){const e=Object.create(i);return e.scene=i.composerModule?.postProcessingOverlayScene??i.scene,e}function HSe(i){i.getObjectByName("ClippingBox")?.traverse(t=>{t.castShadow=!1,t.receiveShadow=!1,t.userData.excludeFromAmbientOcclusion=!0,(Array.isArray(t.material)?t.material:t.material?[t.material]:[]).forEach(s=>{s.depthWrite=!1,s.depthTest=!1,s.toneMapped=!1,s.needsUpdate=!0})})}class BMt{planes;mode="";fillCutFace=!0;engine;constructor(e,t){this.engine=e,this.planes=t}apply(){const e=this.getActivePlanes(),t=[],n=new Set;this.engine.scene.traverse(s=>{!s.isGroup||s===this.engine.scene||n.has(s.uuid)||(s.userData?.__isModelUrlGroup===!0||this.engine.models?.some(o=>o.group===s))&&(n.add(s.uuid),t.push(s))}),t.forEach(s=>{const o=zR(s,e);o.clipShadows=!0}),this.engine.composerModule?.markSceneDirty?.(),this.engine.requestComposerRender?.()}clear(){this.mode="",this.planes.forEach(e=>e.constant=1e5),this.apply()}getActivePlanes(){return this.mode==="box"||this.mode==="viewRange"?this.planes.slice(0,6):this.mode==="x"||this.mode==="y"||this.mode==="z"||this.mode==="face"?[this.planes[6]]:[]}}class yMt extends VSe{webgpuState;interactionScene;constructor(e,t){const n=zSe(e);super(n),this.webgpuState=t,this.interactionScene=n.scene}updata_face(e){super.updata_face(e),HSe(this.interactionScene),this.webgpuState.apply()}dispose(){this.disActive(),this.transformControls?.forEach(r=>r.dispose?.());const t=this.engine?.scene;t?.getObjectByName("ClippingBox")?.removeFromParent();const n=this.transformHelpers,s=this.transformAnchors;n?.forEach(r=>r.removeFromParent()),s?.forEach(r=>r.removeFromParent());const o=[];t?.traverse(r=>{(r.name.startsWith("SectionBoxTransformAnchor_")||r.name.startsWith("SectionBoxTransformControl_"))&&o.push(r)}),o.forEach(r=>r.removeFromParent()),this.webgpuState.apply()}}class wMt extends ZSe{webgpuState;interactionScene;constructor(e,t){const n=zSe(e);super(n),this.webgpuState=t,this.interactionScene=n.scene}updata_face(e,t){super.updata_face(e,t),HSe(this.interactionScene),this.webgpuState.apply()}dispose(){this.disActive(),this.transformControl?.dispose?.(),this.rotateControl?.dispose?.();const e=this.engine?.scene;e?.getObjectByName("ClippingBox")?.removeFromParent(),this.transformHelper?.removeFromParent?.(),this.rotateHelper?.removeFromParent?.(),this.transformAnchor?.removeFromParent?.(),this.rotateAnchor?.removeFromParent?.();const t=[];e?.traverse(n=>{(n.name==="SectionFaceTransformAnchor"||n.name==="SectionFaceRotateAnchor"||n.name==="SectionFaceTransformControl"||n.name==="SectionFaceRotateControl")&&t.push(n)}),t.forEach(n=>n.removeFromParent()),this.webgpuState.apply()}}class bMt extends JSe{}function QMt(){return{clear(){},updataFace(){},updataFaces(){}}}let MMt=class{engine;state;viewRangePlanes=null;sectionPlane;sectionBox;sectionFace;clippingStencil=null;clippingCSGSimple;currentClippingMode="";sectionCatchFace;fillCutFace=!0;constructor(e){this.engine=e,this.sectionPlane=[new Fn(new N(1,0,0),1e5),new Fn(new N(-1,0,0),1e5),new Fn(new N(0,1,0),1e5),new Fn(new N(0,-1,0),1e5),new Fn(new N(0,0,1),1e5),new Fn(new N(0,0,-1),1e5),new Fn(new N(0,0,1),1e5)],this.sectionPlane.forEach((t,n)=>{t.name=["前","左","后","右","顶","底","face"][n]}),this.engine.sectionPlane=this.sectionPlane,this.state=new BMt(e,this.sectionPlane),this.engine.__getActiveWebGPUClippingPlanes=()=>this.state.getActivePlanes(),this.sectionBox=new yMt(e,this.state),this.sectionFace=new wMt(e,this.state),this.sectionCatchFace=new bMt(e),this.clippingCSGSimple=QMt()}init(){this.state.apply()}scaleBox(){const e=this.engine.octreeBox?.getBoundingBox?.();e&&this.sectionBox.setBox(e)}setFillCutFace(e){this.fillCutFace=e,this.state.fillCutFace=e}getFillCutFace(){return this.fillCutFace}clippingModel(e){const t=(e??[]).flatMap(s=>{const o=this.engine.models?.find(r=>r.url===s.url);return(s.ids??[]).flatMap(r=>o?.nodesMap?.get(r)?.infos?.map(A=>A.box)??[])});if(!t.length)return;const n=new Wt;t.forEach(s=>{s?.min&&s?.max&&n.union(new Wt(new N(s.min.x,s.min.y,s.min.z),new N(s.max.x,s.max.y,s.max.z)))}),n.isEmpty()||(n.expandByScalar(.1),this.active("box"),this.sectionBox.setBox(n))}updateClippingValue(e){const t=this.sectionBox.maxBox;!t||!e||this.sectionBox.setboxXyz({minX:Ai.lerp(t.min.x,t.max.x,e.x.min*.01),minY:Ai.lerp(t.min.y,t.max.y,e.y.min*.01),minZ:Ai.lerp(t.min.z,t.max.z,e.z.min*.01),maxX:Ai.lerp(t.min.x,t.max.x,e.x.max*.01),maxY:Ai.lerp(t.min.y,t.max.y,e.y.max*.01),maxZ:Ai.lerp(t.min.z,t.max.z,e.z.max*.01)})}active(e){if(this.sectionCatchFace.cancel(),this.sectionBox.disActive(),this.sectionFace.disActive(),this.currentClippingMode=e,this.state.mode=e,this.engine.engineStatus&&(this.engine.engineStatus.isForceFree=!0),e==="box")this.sectionBox.active();else if(e==="x"||e==="y"||e==="z"){this.sectionFace.direction=1;const t={x:new N(-1,0,0),y:new N(0,0,-1),z:new N(0,-1,0)};this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(t[e])}else e==="face"&&(this.sectionFace.direction=1,this.sectionCatchFace.init(),this.sectionCatchFace.catch_face(t=>{const s=this.engine.octreeBox?.getBoundingBox?.()?.getCenter?.(new N)??new N,o=t.position.clone().sub(s).dot(t.dir);this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(t.dir,o),this.currentClippingMode="face",this.state.mode="face"}));this.state.apply()}disabled(){this.currentClippingMode==="viewRange"?this.state.clear():this.currentClippingMode==="box"?(this.sectionBox.disabled(),this.state.clear()):(this.sectionFace.disabled(),this.state.clear()),this.engine.engineStatus&&(this.engine.engineStatus.isForceFree=!1)}recover(){if(this.currentClippingMode==="viewRange"&&this.viewRangePlanes){this.viewRangePlanes.forEach((e,t)=>this.sectionPlane[t].copy(e)),this.state.mode="viewRange",this.state.apply();return}this.state.mode=this.currentClippingMode,this.state.apply(),this.currentClippingMode==="box"?this.sectionBox.recover():this.currentClippingMode&&this.sectionFace.recover()}reverse(){["x","y","z","face"].includes(this.currentClippingMode)&&this.sectionFace.reverse()}disActive(){this.sectionBox.disActive(),this.sectionFace.disActive(),this.sectionCatchFace.cancel(),this.viewRangePlanes=null,this.state.clear(),this.currentClippingMode="",this.engine.engineStatus&&(this.engine.engineStatus.isForceFree=!1)}dispose(){this.disActive(),this.sectionBox.dispose(),this.sectionFace.dispose(),this.engine.__getActiveWebGPUClippingPlanes&&delete this.engine.__getActiveWebGPUClippingPlanes}isPointInClippingRange(e,t=1e-4){return e?this.state.getActivePlanes().every(n=>n.distanceToPoint(e)>=-t):!1}filterIntersectionsByClipping(e,t=1e-4){return(e??[]).filter(n=>this.isPointInClippingRange(n.point,t))}doesBoxIntersectClippingRange(e,t=1e-4){const n=this.toBox3(e);return!n||n.isEmpty()?!1:this.state.getActivePlanes().every(s=>{const o=new N(s.normal.x>=0?n.max.x:n.min.x,s.normal.y>=0?n.max.y:n.min.y,s.normal.z>=0?n.max.z:n.min.z);return s.distanceToPoint(o)>=-t})}getClippedBoundingBox(e){const t=this.toBox3(e??this.engine.octreeBox?.getBoundingBox?.());if(!t||t.isEmpty())return null;const n=this.state.getActivePlanes();if(!n.length)return t.clone();const s=this.getBoxBoundaryPlanes(t).concat(n),o=[];for(let r=0;r<s.length-2;r+=1)for(let A=r+1;A<s.length-1;A+=1)for(let a=A+1;a<s.length;a+=1){const l=this.intersectThreePlanes(s[r],s[A],s[a]);l&&s.every(c=>c.distanceToPoint(l)>=-1e-6)&&o.push(l)}return o.length?new Wt().setFromPoints(o):null}setSectionByView(e,t){const n=this.engine.octreeBox?.getBoundingBox?.();if(!n)return;this.sectionBox.disActive(),this.sectionFace.disActive(),this.scaleBox();const s=n.getCenter(new N),o=new N(t.x,t.y,t.z).normalize().negate(),r=new N(e.x,e.y,e.z).sub(s).dot(o);this.sectionFace.init(!0),this.sectionFace.setFaceNormalPlaneOnly(o,r),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face",this.state.mode="face"}setSectionPlanesByViewRange(e){!Array.isArray(e)||e.length!==6||(this.sectionBox.disActive(),this.sectionFace.disActive(),this.sectionCatchFace.cancel(),this.viewRangePlanes=e.map(t=>t.clone()),this.viewRangePlanes.forEach((t,n)=>this.sectionPlane[n].copy(t)),this.sectionPlane[6].constant=1e5,this.currentClippingMode="viewRange",this.state.mode="viewRange",this.state.apply(),this.engine.engineStatus&&(this.engine.engineStatus.isForceFree=!0))}toBox3(e){return!e?.min||!e?.max?null:e instanceof Wt?e.clone():new Wt(new N(e.min.x,e.min.y,e.min.z),new N(e.max.x,e.max.y,e.max.z))}getBoxBoundaryPlanes(e){return[new Fn(new N(1,0,0),-e.min.x),new Fn(new N(-1,0,0),e.max.x),new Fn(new N(0,1,0),-e.min.y),new Fn(new N(0,-1,0),e.max.y),new Fn(new N(0,0,1),-e.min.z),new Fn(new N(0,0,-1),e.max.z)]}intersectThreePlanes(e,t,n){const s=new N().crossVectors(e.normal,t.normal),o=s.dot(n.normal);return Math.abs(o)<1e-8?null:new N().crossVectors(t.normal,n.normal).multiplyScalar(-e.constant).add(new N().crossVectors(n.normal,e.normal).multiplyScalar(-t.constant)).add(s.multiplyScalar(-n.constant)).divideScalar(o)}},DMt=class{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return(this.engine?.models??[]).forEach(n=>{e.push({children:n.modelTree?.modelTreeLevel,name:n.baseInfo?.name,url:n.url})}),e}getTypeTreeData(){let e=[];return(this.engine?.models??[]).forEach(n=>{e.push({children:n.modelTree?.modelTreeType,name:n.baseInfo?.name,url:n.url})}),e}getMajorTreeData(){let e=[];return(this.engine?.models??[]).forEach(n=>{e.push({children:n.modelTree?.modelTreeMajor,name:n.baseInfo?.name,url:n.url})}),e}},SMt=class{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,n=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(s=>{if(s instanceof lt){const o=s.geometry;if(o&&o.attributes){const r=o.attributes.position;if(r){const A=r.count;e+=A;let a=0;o.index?a=o.index.count/3:a=A/3,t+=a}}}}),(this.engine?.models??[]).forEach(s=>{n=n+s.nodesMap.size}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:n})}};const xMt='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" aria-hidden="true"><circle cx="10.8" cy="10.8" r="6.5" stroke="currentColor" stroke-width="2"/><path d="m16 16 4.3 4.3" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';let TMt=class{manager;wrapper;input;status;list;pagination;results=[];activeIndex=-1;currentPage=1;pageSize=20;debounceTimer=null;constructor(e,t){this.manager=t,this.wrapper=document.createElement("div"),this.wrapper.className="engine-3d-search",this.wrapper.innerHTML=`
4933
4933
  <section class="engine-3d-search__box" role="dialog" aria-label="模型检索">
4934
4934
  <div class="engine-3d-search__input-row">
4935
4935
  <span class="engine-3d-search__icon">${xMt}</span>
@@ -5956,7 +5956,7 @@ void main() {
5956
5956
  #include <premultiplied_alpha_fragment>
5957
5957
 
5958
5958
  }
5959
- `};class _X extends nr{constructor(e){super({type:"LineMaterial",uniforms:Oc.clone(sg.line.uniforms),vertexShader:sg.line.vertexShader,fragmentShader:sg.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0!==this.worldUnits&&(this.needsUpdate=!0),e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}}const Pne=new ji,B_e=new N,y_e=new N,Yh=new ji,Gh=new ji,QC=new ji,_ne=new N,Fne=new nt,jh=new Wg,w_e=new N,FX=new Wt,vX=new ta,MC=new ji;let DC,MS;function b_e(i,e,t){return MC.set(0,0,-e,1).applyMatrix4(i.projectionMatrix),MC.multiplyScalar(1/MC.w),MC.x=MS/t.width,MC.y=MS/t.height,MC.applyMatrix4(i.projectionMatrixInverse),MC.multiplyScalar(1/MC.w),Math.abs(Math.max(MC.x,MC.y))}function RFt(i,e){const t=i.matrixWorld,n=i.geometry,s=n.attributes.instanceStart,o=n.attributes.instanceEnd,r=Math.min(n.instanceCount,s.count);for(let A=0,a=r;A<a;A++){jh.start.fromBufferAttribute(s,A),jh.end.fromBufferAttribute(o,A),jh.applyMatrix4(t);const l=new N,c=new N;DC.distanceSqToSegment(jh.start,jh.end,c,l),c.distanceTo(l)<MS*.5&&e.push({point:c,pointOnLine:l,distance:DC.origin.distanceTo(c),object:i,face:null,faceIndex:A,uv:null,uv1:null})}}function NFt(i,e,t){const n=e.projectionMatrix,o=i.material.resolution,r=i.matrixWorld,A=i.geometry,a=A.attributes.instanceStart,l=A.attributes.instanceEnd,c=Math.min(A.instanceCount,a.count),h=-e.near;DC.at(1,QC),QC.w=1,QC.applyMatrix4(e.matrixWorldInverse),QC.applyMatrix4(n),QC.multiplyScalar(1/QC.w),QC.x*=o.x/2,QC.y*=o.y/2,QC.z=0,_ne.copy(QC),Fne.multiplyMatrices(e.matrixWorldInverse,r);for(let d=0,g=c;d<g;d++){if(Yh.fromBufferAttribute(a,d),Gh.fromBufferAttribute(l,d),Yh.w=1,Gh.w=1,Yh.applyMatrix4(Fne),Gh.applyMatrix4(Fne),Yh.z>h&&Gh.z>h)continue;if(Yh.z>h){const y=Yh.z-Gh.z,w=(Yh.z-h)/y;Yh.lerp(Gh,w)}else if(Gh.z>h){const y=Gh.z-Yh.z,w=(Gh.z-h)/y;Gh.lerp(Yh,w)}Yh.applyMatrix4(n),Gh.applyMatrix4(n),Yh.multiplyScalar(1/Yh.w),Gh.multiplyScalar(1/Gh.w),Yh.x*=o.x/2,Yh.y*=o.y/2,Gh.x*=o.x/2,Gh.y*=o.y/2,jh.start.copy(Yh),jh.start.z=0,jh.end.copy(Gh),jh.end.z=0;const p=jh.closestPointToPointParameter(_ne,!0);jh.at(p,w_e);const m=Ai.lerp(Yh.z,Gh.z,p),I=m>=-1&&m<=1,B=_ne.distanceTo(w_e)<MS*.5;if(I&&B){jh.start.fromBufferAttribute(a,d),jh.end.fromBufferAttribute(l,d),jh.start.applyMatrix4(r),jh.end.applyMatrix4(r);const y=new N,w=new N;DC.distanceSqToSegment(jh.start,jh.end,w,y),t.push({point:w,pointOnLine:y,distance:DC.origin.distanceTo(w),object:i,face:null,faceIndex:d,uv:null,uv1:null})}}}class YFt extends lt{constructor(e=new E_e,t=new _X({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,n=e.attributes.instanceEnd,s=new Float32Array(2*t.count);for(let r=0,A=0,a=t.count;r<a;r++,A+=2)B_e.fromBufferAttribute(t,r),y_e.fromBufferAttribute(n,r),s[A]=A===0?0:s[A-1],s[A+1]=s[A]+B_e.distanceTo(y_e);const o=new Vv(s,2,1);return e.setAttribute("instanceDistanceStart",new cd(o,1,0)),e.setAttribute("instanceDistanceEnd",new cd(o,1,1)),this}raycast(e,t){const n=this.material.worldUnits,s=e.camera;if(s===null&&!n&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.'),n===!1&&(this.material.resolution.x===0||this.material.resolution.y===0))return;const o=e.params.Line2!==void 0&&e.params.Line2.threshold||0;DC=e.ray;const r=this.matrixWorld,A=this.geometry,a=this.material;MS=a.linewidth+o,A.boundingSphere===null&&A.computeBoundingSphere(),vX.copy(A.boundingSphere).applyMatrix4(r);let l;if(n)l=MS*.5;else{const h=Math.max(s.near,vX.distanceToPoint(DC.origin));l=b_e(s,h,a.resolution)}if(vX.radius+=l,DC.intersectsSphere(vX)===!1)return;A.boundingBox===null&&A.computeBoundingBox(),FX.copy(A.boundingBox).applyMatrix4(r);let c;if(n)c=MS*.5;else{const h=Math.max(s.near,FX.distanceToPoint(DC.origin));c=b_e(s,h,a.resolution)}FX.expandByScalar(c),DC.intersectsBox(FX)!==!1&&(n?RFt(this,t):NFt(this,s,t))}onBeforeRender(e){const t=this.material.uniforms;t&&t.resolution&&(e.getViewport(Pne),this.material.uniforms.resolution.value.set(Pne.z,Pne.w))}}class vne extends E_e{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){const t=e.length-3,n=new Float32Array(2*t);for(let s=0;s<t;s+=3)n[2*s]=e[s],n[2*s+1]=e[s+1],n[2*s+2]=e[s+2],n[2*s+3]=e[s+3],n[2*s+4]=e[s+4],n[2*s+5]=e[s+5];return super.setPositions(n),this}setColors(e){const t=e.length-3,n=new Float32Array(2*t);for(let s=0;s<t;s+=3)n[2*s]=e[s],n[2*s+1]=e[s+1],n[2*s+2]=e[s+2],n[2*s+3]=e[s+3],n[2*s+4]=e[s+4],n[2*s+5]=e[s+5];return super.setColors(n),this}setFromPoints(e){const t=e.length-1,n=new Float32Array(6*t);for(let s=0;s<t;s++)n[6*s]=e[s].x,n[6*s+1]=e[s].y,n[6*s+2]=e[s].z||0,n[6*s+3]=e[s+1].x,n[6*s+4]=e[s+1].y,n[6*s+5]=e[s+1].z||0;return super.setPositions(n),this}fromLine(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}}class Q_e extends YFt{constructor(e=new vne,t=new _X({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type="Line2"}}const RX={lineType:"bezier",lineColor:"#22c55e",previewColor:"#f59e0b",pointColor:"#ffffff",selectedPointColor:"#f59e0b",pointSize:.34,lineWidth:4,sampleCount:64,roundedRadius:1,historyLimit:100},GFt={bezier:"贝塞尔曲线",straight:"直线",rounded:"圆角直线"},jFt={bezier:"∿",straight:"╱",rounded:"⌁"};let UFt=class{type="path-draw";engine;root=new qn;pointsGroup=new qn;points=[];history=[];options={...RX};lineType=RX.lineType;roundedRadius=RX.roundedRadius;line=null;previewLine=null;previewMarker=null;transformControl=null;transformHelper=null;selectedPointId=null;panel=null;pointsList=null;statusElement=null;addButton=null;completeButton=null;radiusInput=null;mode="editing";active=!1;closing=!1;transformDragging=!1;suppressNextCanvasClick=!1;controlsEnabledBeforeDrag=!0;pointSequence=0;pathId="";onKeyDown;constructor(e){this.engine=e,this.root.name="PathDrawRoot",this.pointsGroup.name="PathDrawPoints",this.root.add(this.pointsGroup),this.onKeyDown=this.handleKeyDown.bind(this)}open(e={}){this.active&&this.close(),this.options={...RX,...e},this.pathId=e.id??`path-${Date.now()}`,this.lineType=this.options.lineType,this.roundedRadius=Math.max(0,this.options.roundedRadius),this.active=!0,this.mode="editing",this.engine.scene?.add(this.root),this.ensureTransformControl(),this.createPanel(),this.activateBehavior(),window.addEventListener("keydown",this.onKeyDown,!0),this.refreshAll()}startAddPoint(){return!this.active||this.transformDragging?!1:(this.mode="picking",this.clearSelection(),this.setStatus("请在模型上拾取位置"),this.addButton&&(this.addButton.dataset.active="true"),!0)}setLineType(e){!this.active||this.lineType===e||(this.saveHistory(),this.lineType=e,this.refreshAll(),this.emitChange())}undo(){const e=this.history.pop();return e?(this.restoreSnapshot(e),this.mode="editing",this.clearPreview(),this.refreshAll(),this.emitChange(),!0):!1}clear(){this.points.length!==0&&(this.saveHistory(),this.clearPointRecords(),this.mode="editing",this.clearPreview(),this.refreshAll(),this.emitChange())}getPathData(){if(this.points.length<2)return null;const e=this.buildSamplePoints(this.points.map(t=>t.position));return{version:1,id:this.pathId,lineType:this.lineType,coordinateSystem:"world",closed:!1,roundedRadius:this.roundedRadius,points:this.points.map((t,n)=>({id:t.id,order:n,role:this.getPointRole(n),position:this.toPlainVector(t.position)})),samples:e.map(t=>this.toPlainVector(t)),length:this.calculateLength(e)}}complete(){const e=this.getPathData();if(!e)return null;try{this.options.onComplete?.(e)}finally{this.close()}return e}isActive(){return this.active}close(){this.closeInternal(!0)}closeInternal(e){!this.active&&!this.panel||this.closing||(this.closing=!0,this.active=!1,window.removeEventListener("keydown",this.onKeyDown,!0),this.clearPreview(),this.clearPointRecords(),this.disposeLine("line"),this.detachTransformControl(),this.panel?.remove(),this.panel=null,this.pointsList=null,this.statusElement=null,this.addButton=null,this.completeButton=null,this.radiusInput=null,this.history.length=0,this.selectedPointId=null,this.root.parent?.remove(this.root),e&&this.restoreDefaultBehavior(),this.closing=!1)}dispose(){this.closeInternal(!1),this.transformControl?.dispose(),this.transformControl=null,this.transformHelper=null}update(){!this.active||!this.engine.camera||(this.transformControl&&this.transformControl.camera!==this.engine.camera&&(this.transformControl.camera=this.engine.camera),this.syncLineResolution(this.line),this.syncLineResolution(this.previewLine))}disActive(){this.closing||this.closeInternal(!1)}handleMouseMove(e){if(!this.active||this.mode!=="picking")return;const t=this.getCatchPoint(e?.catch);if(!t){this.clearPreview();return}this.updatePreview(t)}handleMouseClick(e){if(!this.active)return;if(this.suppressNextCanvasClick){this.suppressNextCanvasClick=!1;return}if(this.mode==="picking"){const n=this.getCatchPoint(e?.catch);if(!n)return;this.saveHistory();const s=this.createPointRecord(n);this.points.push(s),this.pointsGroup.add(s.mesh),this.mode="editing",this.clearPreview(),this.selectPoint(s.id),this.refreshAll(),this.emitChange();return}const t=this.pickPointMesh(e);t?this.selectPoint(t.userData.pathDrawPointId):this.clearSelection()}handelKeyEscDown(){if(this.mode==="picking"){this.mode="editing",this.clearPreview(),this.refreshPanel();return}this.clearSelection()}activateBehavior(){const e=this.engine.handelBehaved;e?.init?.(this,{showCatch:!0}),e?.active?.()}restoreDefaultBehavior(){const e=this.engine.handelBehaved;e?.self===this&&(e.disActive?.(),this.engine.interactionModule?.init?.(),this.engine.interactionModule?.active?.(),this.engine.catchSvg&&(this.engine.catchSvg.innerHTML=""))}ensureTransformControl(){if(this.transformControl){this.transformHelper&&!this.transformHelper.parent&&this.engine.scene?.add(this.transformHelper);return}!this.engine.camera||!this.engine.renderer||!this.engine.scene||(this.transformControl=new rS(this.engine.camera,this.engine.renderer.domElement),this.transformControl.setMode("translate"),this.transformControl.size=.72,this.transformControl.addEventListener("dragging-changed",e=>{if(this.transformDragging=!!e.value,this.transformDragging){this.saveHistory(),this.controlsEnabledBeforeDrag=this.engine.controls?.enabled!==!1,this.engine.controls&&(this.engine.controls.enabled=!1);return}this.engine.controls&&(this.engine.controls.enabled=this.controlsEnabledBeforeDrag),this.suppressNextCanvasClick=!0,requestAnimationFrame(()=>{this.suppressNextCanvasClick=!1}),this.refreshAll(),this.emitChange()}),this.transformControl.addEventListener("objectChange",()=>{const e=this.getSelectedPoint();e&&(e.position.copy(e.mesh.position),this.refreshLine(),this.refreshPanel(),this.emitChange())}),this.transformHelper=this.transformControl.getHelper(),this.transformHelper.visible=!1,this.engine.scene.add(this.transformHelper))}detachTransformControl(){this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1,this.transformHelper.parent?.remove(this.transformHelper))}createPointRecord(e,t){const n=new Wc(this.options.pointSize,18,12),s=new Ji({color:this.options.pointColor,depthTest:!1,depthWrite:!1}),o=new lt(n,s),r=t??`path-point-${++this.pointSequence}`;return o.name=r,o.position.copy(e),o.renderOrder=1002,o.userData.pathDrawPointId=r,{id:r,position:e.clone(),mesh:o}}selectPoint(e){const t=this.points.find(n=>n.id===e);!t||!this.transformControl||!this.transformHelper||(this.selectedPointId=e,this.points.forEach(n=>n.mesh.material.color.set(n.id===e?this.options.selectedPointColor:this.options.pointColor)),this.transformControl.attach(t.mesh),this.transformHelper.visible=!0,this.refreshPanel())}clearSelection(){this.selectedPointId=null,this.points.forEach(e=>e.mesh.material.color.set(this.options.pointColor)),this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1),this.refreshPanel()}getSelectedPoint(){return this.points.find(e=>e.id===this.selectedPointId)??null}getCatchPoint(e){return e?.point instanceof N?e.point.clone():null}pickPointMesh(e){if(!this.engine.camera||!this.engine.renderer)return null;const t=this.engine.renderer.domElement.clientWidth,n=this.engine.renderer.domElement.clientHeight;if(!t||!n)return null;const s=new Ne(e.offsetX/t*2-1,-(e.offsetY/n)*2+1),o=new Ao;return o.setFromCamera(s,this.engine.camera),o.intersectObjects(this.pointsGroup.children,!1)[0]?.object??null}updatePreview(e){this.previewMarker||(this.previewMarker=new lt(new Wc(this.options.pointSize*.72,14,10),new Ji({color:this.options.previewColor,depthTest:!1,depthWrite:!1})),this.previewMarker.renderOrder=1003,this.root.add(this.previewMarker)),this.previewMarker.position.copy(e),this.previewMarker.visible=!0;const t=[...this.points.map(s=>s.position),e];if(t.length<2){this.disposeLine("previewLine");return}const n=this.buildSamplePoints(t);this.previewLine=this.updateLineObject(this.previewLine,n,!0)}clearPreview(){this.disposeLine("previewLine"),this.previewMarker&&(this.previewMarker.geometry.dispose(),this.previewMarker.material.dispose(),this.previewMarker.parent?.remove(this.previewMarker),this.previewMarker=null)}refreshAll(){this.refreshLine(),this.refreshPanel(),this.requestRender()}refreshLine(){if(this.points.length<2){this.disposeLine("line");return}const e=this.buildSamplePoints(this.points.map(t=>t.position));this.line=this.updateLineObject(this.line,e,!1)}updateLineObject(e,t,n){const s=new vne;if(s.setPositions(t.flatMap(A=>[A.x,A.y,A.z])),e)return e.geometry.dispose(),e.geometry=s,e.computeLineDistances(),this.syncLineResolution(e),this.requestRender(),e;const o=new _X({color:n?this.options.previewColor:this.options.lineColor,linewidth:this.options.lineWidth,dashed:n,dashSize:.32,gapSize:.2,depthTest:!1,transparent:n,opacity:n?.82:1}),r=new Q_e(s,o);return r.name=n?"PathDrawPreviewLine":"PathDrawLine",r.renderOrder=n?1001:1e3,r.computeLineDistances(),this.syncLineResolution(r),this.root.add(r),this.requestRender(),r}syncLineResolution(e){const t=e?.material,n=this.engine.renderer?.domElement;!t||!n||t.resolution.set(n.clientWidth,n.clientHeight)}disposeLine(e){const t=this[e];if(!t)return;t.parent?.remove(t),t.geometry.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(s=>s.dispose()),this[e]=null}buildSamplePoints(e){return e.length<2?e.map(t=>t.clone()):this.lineType==="straight"?e.map(t=>t.clone()):this.lineType==="rounded"?this.sampleRoundedPolyline(e):this.sampleBezier(e)}sampleBezier(e){const t=Math.max(2,this.options.sampleCount);return Array.from({length:t+1},(n,s)=>{const o=e.map(A=>A.clone()),r=s/t;for(let A=o.length-1;A>0;A-=1)for(let a=0;a<A;a+=1)o[a].lerp(o[a+1],r);return o[0]})}sampleRoundedPolyline(e){if(e.length<3||this.roundedRadius<=0)return e.map(s=>s.clone());const t=[e[0].clone()],n=Math.max(4,Math.round(this.options.sampleCount/Math.max(1,e.length-2)));for(let s=1;s<e.length-1;s+=1){const o=e[s-1],r=e[s],A=e[s+1],a=o.distanceTo(r),l=r.distanceTo(A);if(a<1e-8||l<1e-8){t.push(r.clone());continue}const c=Math.min(this.roundedRadius,a*.5,l*.5),h=r.clone().lerp(o,c/a),d=r.clone().lerp(A,c/l);t.push(h);for(let g=1;g<=n;g+=1){const u=g/n,p=1-u;t.push(new N().addScaledVector(h,p*p).addScaledVector(r,2*p*u).addScaledVector(d,u*u))}}return t.push(e[e.length-1].clone()),t}calculateLength(e){let t=0;for(let n=1;n<e.length;n+=1)t+=e[n-1].distanceTo(e[n]);return t}getPointRole(e){return e===0?"start":e===this.points.length-1?"end":"control"}getRoleLabel(e){const t=this.getPointRole(e);return t==="start"?"起点":t==="end"?"终点":`控制点 ${e}`}saveHistory(){this.history.push(this.createSnapshot()),this.history.length>this.options.historyLimit&&this.history.shift()}createSnapshot(){return{lineType:this.lineType,roundedRadius:this.roundedRadius,points:this.points.map(e=>({id:e.id,position:e.position.toArray()}))}}restoreSnapshot(e){this.clearPointRecords(),this.lineType=e.lineType,this.roundedRadius=e.roundedRadius,e.points.forEach(t=>{const n=this.createPointRecord(new N(...t.position),t.id);this.points.push(n),this.pointsGroup.add(n.mesh)})}clearPointRecords(){this.clearSelection(),this.points.forEach(e=>{e.mesh.parent?.remove(e.mesh),e.mesh.geometry.dispose(),e.mesh.material.dispose()}),this.points.length=0}removePoint(e){const t=this.points.findIndex(s=>s.id===e);if(t<0)return;this.saveHistory();const[n]=this.points.splice(t,1);n.mesh.parent?.remove(n.mesh),n.mesh.geometry.dispose(),n.mesh.material.dispose(),this.selectedPointId===e&&this.clearSelection(),this.refreshAll(),this.emitChange()}updatePointCoordinate(e,t,n){const s=this.points.find(o=>o.id===e);!s||!Number.isFinite(n)||s.position[t]===n||(this.saveHistory(),s.position[t]=n,s.mesh.position[t]=n,this.refreshAll(),this.emitChange())}createPanel(){const e=document.createElement("div");e.dataset.pathDrawPanel="true",Object.assign(e.style,{position:"absolute",top:"56px",right:"16px",width:"310px",maxHeight:"calc(100% - 72px)",display:"flex",flexDirection:"column",background:"rgba(255, 255, 255, 0.98)",color:"#111827",border:"1px solid #d1d5db",borderRadius:"6px",boxShadow:"0 12px 28px rgba(15,23,42,0.18)",fontFamily:"Arial, sans-serif",fontSize:"12px",zIndex:"1200",overflow:"hidden"});const t=document.createElement("div");Object.assign(t.style,{display:"flex",alignItems:"center",minHeight:"40px",padding:"0 8px 0 12px",borderBottom:"1px solid #e5e7eb"});const n=document.createElement("strong");n.textContent="路径绘制",n.style.flex="1";const s=document.createElement("span");Object.assign(s.style,{color:"#64748b",marginRight:"8px"});const o=this.createIconButton("×","关闭路径绘制",()=>this.close());t.append(n,s,o),e.appendChild(t),this.statusElement=s;const r=document.createElement("div");Object.assign(r.style,{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:"4px",padding:"8px"}),["bezier","straight","rounded"].forEach(m=>{const I=this.createIconButton(jFt[m],GFt[m],()=>this.setLineType(m));I.dataset.lineType=m,I.style.width="100%",I.style.fontSize="18px",r.appendChild(I)}),e.appendChild(r);const A=document.createElement("label");A.dataset.radiusRow="true",Object.assign(A.style,{display:"none",alignItems:"center",gap:"8px",padding:"0 10px 8px",color:"#475569"});const a=document.createElement("span");a.textContent="圆角";const l=document.createElement("input");l.type="number",l.min="0",l.step="0.1",Object.assign(l.style,{flex:"1",minWidth:"0",height:"26px",padding:"0 7px",color:"#111827",background:"#ffffff",border:"1px solid #cbd5e1",borderRadius:"4px"}),l.addEventListener("change",()=>{const m=Number(l.value);if(!Number.isFinite(m)||m<0||m===this.roundedRadius){l.value=String(this.roundedRadius);return}this.saveHistory(),this.roundedRadius=m,this.refreshAll(),this.emitChange()}),A.append(a,l),e.appendChild(A),this.radiusInput=l;const c=document.createElement("div");Object.assign(c.style,{flex:"1",minHeight:"72px",maxHeight:"200px",overflowY:"auto",overflowX:"hidden",borderTop:"1px solid #e5e7eb"}),e.appendChild(c),this.pointsList=c;const h=document.createElement("div");Object.assign(h.style,{display:"grid",gridTemplateColumns:"1fr auto auto auto",gap:"6px",padding:"8px",borderTop:"1px solid #e5e7eb"});const d=this.createIconButton("+","添加点",()=>this.startAddPoint());d.style.width="100%";const g=this.createIconButton("↶","撤销 Ctrl+Z",()=>this.undo());g.dataset.undoButton="true";const u=this.createIconButton("⌫","清空路径",()=>this.clear());u.dataset.clearButton="true";const p=this.createIconButton("✓","完成并返回路径",()=>this.complete());p.dataset.primary="true",h.append(d,g,u,p),e.appendChild(h),this.addButton=d,this.completeButton=p,this.engine.container?.appendChild(e),this.panel=e}createIconButton(e,t,n){const s=document.createElement("button");return s.type="button",s.textContent=e,s.title=t,s.setAttribute("aria-label",t),Object.assign(s.style,{width:"32px",height:"30px",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0",border:"1px solid #d1d5db",borderRadius:"4px",background:"#f8fafc",color:"#334155",cursor:"pointer",fontSize:"15px"}),s.addEventListener("click",n),s}refreshPanel(){if(!this.panel||!this.pointsList)return;this.setStatus(this.mode==="picking"?"拾取中":`${this.points.length} 个点`),this.addButton&&(this.addButton.dataset.active=String(this.mode==="picking"),this.addButton.style.background=this.mode==="picking"?"#ffedd5":"#f8fafc",this.addButton.style.borderColor=this.mode==="picking"?"#f97316":"#d1d5db",this.addButton.style.color=this.mode==="picking"?"#9a3412":"#334155"),this.panel.querySelectorAll("[data-line-type]").forEach(s=>{const o=s.dataset.lineType===this.lineType;s.style.background=o?"#dcfce7":"#f8fafc",s.style.borderColor=o?"#22c55e":"#d1d5db",s.style.color=o?"#166534":"#334155"});const e=this.panel.querySelector("[data-radius-row]");e&&(e.style.display=this.lineType==="rounded"?"flex":"none"),this.radiusInput&&(this.radiusInput.value=String(this.roundedRadius));const t=this.panel.querySelector("[data-undo-button]"),n=this.panel.querySelector("[data-clear-button]");this.setButtonDisabled(t,this.history.length===0),this.setButtonDisabled(n,this.points.length===0),this.setButtonDisabled(this.completeButton,this.points.length<2),this.renderPointRows()}renderPointRows(){if(this.pointsList){if(this.pointsList.innerHTML="",this.points.length===0){const e=document.createElement("div");e.textContent="暂无点位",Object.assign(e.style,{padding:"24px 12px",textAlign:"center",color:"#94a3b8"}),this.pointsList.appendChild(e);return}this.points.forEach((e,t)=>{const n=document.createElement("div");Object.assign(n.style,{display:"grid",gridTemplateColumns:"64px repeat(3, minmax(0, 1fr)) 28px",gap:"4px",alignItems:"center",height:"40px",boxSizing:"border-box",padding:"5px 8px",cursor:"pointer",background:e.id===this.selectedPointId?"#fef3c7":"#ffffff",borderBottom:"1px solid #eef2f7"}),n.addEventListener("click",()=>this.selectPoint(e.id));const s=document.createElement("span");s.textContent=this.getRoleLabel(t),s.title=s.textContent,Object.assign(s.style,{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#334155"}),n.appendChild(s),["x","y","z"].forEach(r=>{const A=document.createElement("input");A.type="number",A.step="0.001",A.value=e.position[r].toFixed(3),A.title=r.toUpperCase(),Object.assign(A.style,{width:"100%",minWidth:"0",height:"25px",padding:"0 4px",boxSizing:"border-box",color:"#1f2937",background:"#ffffff",border:"1px solid #cbd5e1",borderRadius:"3px",fontSize:"11px"}),A.addEventListener("click",a=>a.stopPropagation()),A.addEventListener("change",()=>this.updatePointCoordinate(e.id,r,Number(A.value))),n.appendChild(A)});const o=this.createIconButton("×",`删除${this.getRoleLabel(t)}`,()=>this.removePoint(e.id));o.style.width="28px",o.style.height="25px",o.addEventListener("click",r=>r.stopPropagation()),n.appendChild(o),this.pointsList?.appendChild(n)})}}setButtonDisabled(e,t){e&&(e.disabled=t,e.style.opacity=t?"0.4":"1",e.style.cursor=t?"not-allowed":"pointer",e.dataset.primary==="true"&&(e.style.background=t?"#f1f5f9":"#16a34a",e.style.color=t?"#94a3b8":"#ffffff",e.style.borderColor=t?"#d1d5db":"#15803d"))}setStatus(e){this.statusElement&&(this.statusElement.textContent=e)}handleKeyDown(e){if(!(!this.active||this.isTextInputTarget(e))){if((e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="z"){if(this.history.length===0)return;e.preventDefault(),e.stopImmediatePropagation(),this.undo();return}e.key==="Escape"&&this.handelKeyEscDown()}}isTextInputTarget(e){const t=e.target;return!!(t?.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(t?.tagName??""))}emitChange(){this.options.onChange?.(this.getPathData()),this.requestRender()}requestRender(){this.engine.requestComposerRender?.()}toPlainVector(e){return{x:e.x,y:e.y,z:e.z}}};class kFt{engine;constructor(e){this.engine=e}}class WFt{engine;constructor(e){this.engine=e}}class OFt{engine;constructor(e){this.engine=e}getQuantityData(){return[{id:"1",name:"Model 1",type:"Model"}]}}class LFt{engine;constructor(e){this.engine=e}}const SC={version:"4.0.9"}.version;let KFt=class Tfe{engine;overlayMaterial;overlayMeshes=[];animState="idle";animStartTime=0;static FADE_IN_MS=200;static FADE_OUT_MS=150;tagDiv;constructor(e){this.engine=e,this.init();const t=document.createElement("div");this.tagDiv=t,t.className="tagDiv",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.borderRadius="10px",t.style.pointerEvents="none",this.engine.container.appendChild(this.tagDiv)}showModelNameTag(e,t){if(e==null){this.tagDiv.style.display="none";return}let n=this.engine.models.find(A=>A.url==e.url);if(n==null){this.tagDiv.style.display="none";return}let s=n.nodesMap.get(e.ids[0]);if(s.infos&&s.infos.length>0){let A=s.infos[0].name.replace(/\s*\[[a-f0-9-]+\]$/,"");this.tagDiv.innerHTML=A}const r=this.engine.worldToScreen.worldToScreen(t);this.tagDiv?(this.tagDiv.style.left=r.x+10+this.engine.reactBoundingClientRect.left+"px",this.tagDiv.style.top=r.y-10+this.engine.reactBoundingClientRect.top+"px",this.tagDiv.style.display="block"):this.tagDiv&&(this.tagDiv.style.display="none")}init(){this.overlayMaterial=new Ji({color:16777215,transparent:!0,opacity:0,blending:F0,depthWrite:!1}),this.overlayMaterial.clippingPlanes=this.engine.sectionPlane}hightMesh(e,t=16777215,n=.15){this.animState==="fadeOut"&&this.removeOverlayMeshes();const s=(Array.isArray(e)?e:e?[e]:[]).filter(o=>o?.geometry);if(s.length===0){this.clearHighlight();return}this.overlayMaterial.color.set(t),this.overlayMaterial.opacity=0,this.overlayMaterial.userData.targetOpacity=n;for(const o of s){let r=o.geometry.clone();r.computeVertexNormals();const A=new lt(r,this.overlayMaterial);o.updateWorldMatrix(!0,!1),A.matrix.copy(o.matrixWorld),A.matrixAutoUpdate=!1,this.engine.scene.add(A),this.overlayMeshes.push(A)}this.animState="fadeIn",this.animStartTime=performance.now(),this.setAnimationFrameRateExempt(!0)}clearHighlight(){this.overlayMeshes.length===0||this.animState==="fadeOut"||(this.animState="fadeOut",this.animStartTime=performance.now(),this.setAnimationFrameRateExempt(!0))}update(){if(this.animState==="idle"||this.overlayMeshes.length===0)return;const e=performance.now()-this.animStartTime,t=this.overlayMaterial.userData.targetOpacity??.35;if(this.animState==="fadeIn"){const n=Math.min(e/Tfe.FADE_IN_MS,1);this.overlayMaterial.opacity=this.easeOutQuad(n)*t,n>=1&&(this.animState="idle",this.setAnimationFrameRateExempt(!1))}else if(this.animState==="fadeOut"){const n=Math.min(e/Tfe.FADE_OUT_MS,1);this.overlayMaterial.opacity=(1-this.easeOutQuad(n))*t,n>=1&&(this.removeOverlayMeshes(),this.animState="idle",this.setAnimationFrameRateExempt(!1))}}setAnimationFrameRateExempt(e){this.engine.setIdleFrameRateExempt?.("hover-highlight-animation",e)}removeOverlayMeshes(){for(const e of this.overlayMeshes)this.engine.scene.remove(e),e.geometry?.dispose?.();this.overlayMeshes=[]}easeOutQuad(e){return 1-(1-e)*(1-e)}dispose(){this.setAnimationFrameRateExempt(!1),this.removeOverlayMeshes(),this.overlayMaterial.dispose(),this.tagDiv?.remove?.(),this.tagDiv=null,this.animState="idle"}};function Rne(){const i=globalThis.crypto?.subtle;if(!i)throw new Error("[BimEngine] Web Crypto API is required for secure sdkAuth credentials mode");return i}function _Y(i){return new TextEncoder().encode(i)}function FY(i){return i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)}function M_e(i){let e="";return i.forEach(t=>{e+=String.fromCharCode(t)}),btoa(e)}function XFt(i){const e=i.getUTCFullYear(),t=String(i.getUTCMonth()+1).padStart(2,"0"),n=String(i.getUTCDate()).padStart(2,"0");return`${e}${t}${n}`}async function VFt(i){const e=await Rne().digest("SHA-256",FY(_Y(i)));return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function ZFt(i,e){const t=Rne(),n=await t.importKey("raw",FY(i),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return t.sign("HMAC",n,FY(_Y(e)))}function JFt(i){return _Y([i.appId,i.engineType,i.requestDate,String(i.timestamp),i.nonce].join("|"))}async function zFt(i){const e=Rne(),t=new Date,n=t.getTime(),s=XFt(t),o=globalThis.crypto.randomUUID(),r=globalThis.crypto.getRandomValues(new Uint8Array(12)),A=await VFt(i.appSecret),a=await ZFt(_Y(A),s),l=await e.importKey("raw",a,"AES-GCM",!1,["encrypt"]),c=JSON.stringify({appKey:i.appKey,appSecret:i.appSecret}),h=await e.encrypt({name:"AES-GCM",iv:r,additionalData:FY(JFt({appId:i.appId,engineType:i.engineType,requestDate:s,timestamp:n,nonce:o})),tagLength:128},l,FY(_Y(c)));return{appId:i.appId,engineType:i.engineType,requestDate:s,timestamp:n,nonce:o,iv:M_e(r),cipherText:M_e(new Uint8Array(h)),sdkVersion:i.sdkVersion,origin:i.origin,product:i.product}}const Nne=new Map;function NX(i){return i.replace(/\/+$/,"")}function YX(i){if(i)return i;if(typeof window<"u"&&typeof window.location?.origin=="string")return window.location.origin}function HFt(i,e){return JSON.stringify({endpoint:NX(i.endpoint),token:i.token??"",appId:i.appId??"",appKey:i.appKey??"",appSecret:i.appSecret??"",origin:YX(i.origin)??"",product:i.product??"",engineType:e,sdkVersion:SC})}async function Yne(i,e,t){const n=typeof AbortController<"u"?new AbortController:void 0,s=n?setTimeout(()=>n.abort(),t):void 0;try{const o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:n?.signal}),r=await o.json().catch(()=>({}));if(!o.ok){const A=r?.error?.message??r?.message??`SDK authentication failed with status ${o.status}`;throw new Error(A)}return r}finally{s!=null&&clearTimeout(s)}}async function qFt(i,e){const t=await Yne(`${NX(i.endpoint)}/oauth/sdk-verify`,{sdkToken:i.token,engineType:e,sdkVersion:SC,origin:YX(i.origin),product:i.product},i.timeoutMs??8e3);return t.sdkToken=i.token,t}async function $Ft(i,e){const t=await zFt({appId:i.appId,appKey:i.appKey,appSecret:i.appSecret,engineType:e,sdkVersion:SC,origin:YX(i.origin),product:i.product}),n=await Yne(`${NX(i.endpoint)}/oauth/sdk-token/secure`,t,i.timeoutMs??8e3),s=await Yne(`${NX(i.endpoint)}/oauth/sdk-verify`,{sdkToken:n.sdkToken,engineType:e,sdkVersion:SC,origin:YX(i.origin),product:i.product},i.timeoutMs??8e3);return s.sdkToken=n.sdkToken,s}async function evt(i,e){const t=i?.sdkAuth;if(!t)return null;if(!t.endpoint)throw new Error("[BimEngine] sdkAuth.endpoint is required");if(!t.token&&!(t.appId&&t.appKey&&t.appSecret))return null;const n=HFt(t,e),s=Nne.get(n);if(s){const r=await s;return i&&(i.__sdkAuthSession=r),r}const o=(t.token?qFt(t,e):$Ft(t,e)).then(r=>{if(r.authorized!==!0)throw new Error("[BimEngine] SDK authorization rejected");return i&&(i.__sdkAuthSession=r),r}).catch(r=>{throw Nne.delete(n),r});return Nne.set(n,o),o}var Gne,D_e;function ao(){return D_e||(D_e=1,Gne={options:{usePureJavaScript:!1}}),Gne}var jne={exports:{}},Une,S_e;function tvt(){if(S_e)return Une;S_e=1;var i={};Une=i;var e={};i.encode=function(n,s,o){if(typeof s!="string")throw new TypeError('"alphabet" must be a string.');if(o!==void 0&&typeof o!="number")throw new TypeError('"maxline" must be a number.');var r="";if(!(n instanceof Uint8Array))r=t(n,s);else{var A=0,a=s.length,l=s.charAt(0),c=[0];for(A=0;A<n.length;++A){for(var h=0,d=n[A];h<c.length;++h)d+=c[h]<<8,c[h]=d%a,d=d/a|0;for(;d>0;)c.push(d%a),d=d/a|0}for(A=0;n[A]===0&&A<n.length-1;++A)r+=l;for(A=c.length-1;A>=0;--A)r+=s[c[A]]}if(o){var g=new RegExp(".{1,"+o+"}","g");r=r.match(g).join(`\r
5959
+ `};class _X extends nr{constructor(e){super({type:"LineMaterial",uniforms:Oc.clone(sg.line.uniforms),vertexShader:sg.line.vertexShader,fragmentShader:sg.line.fragmentShader,clipping:!0}),this.isLineMaterial=!0,this.setValues(e)}get color(){return this.uniforms.diffuse.value}set color(e){this.uniforms.diffuse.value=e}get worldUnits(){return"WORLD_UNITS"in this.defines}set worldUnits(e){e===!0!==this.worldUnits&&(this.needsUpdate=!0),e===!0?this.defines.WORLD_UNITS="":delete this.defines.WORLD_UNITS}get linewidth(){return this.uniforms.linewidth.value}set linewidth(e){this.uniforms.linewidth&&(this.uniforms.linewidth.value=e)}get dashed(){return"USE_DASH"in this.defines}set dashed(e){e===!0!==this.dashed&&(this.needsUpdate=!0),e===!0?this.defines.USE_DASH="":delete this.defines.USE_DASH}get dashScale(){return this.uniforms.dashScale.value}set dashScale(e){this.uniforms.dashScale.value=e}get dashSize(){return this.uniforms.dashSize.value}set dashSize(e){this.uniforms.dashSize.value=e}get dashOffset(){return this.uniforms.dashOffset.value}set dashOffset(e){this.uniforms.dashOffset.value=e}get gapSize(){return this.uniforms.gapSize.value}set gapSize(e){this.uniforms.gapSize.value=e}get opacity(){return this.uniforms.opacity.value}set opacity(e){this.uniforms&&(this.uniforms.opacity.value=e)}get resolution(){return this.uniforms.resolution.value}set resolution(e){this.uniforms.resolution.value.copy(e)}get alphaToCoverage(){return"USE_ALPHA_TO_COVERAGE"in this.defines}set alphaToCoverage(e){this.defines&&(e===!0!==this.alphaToCoverage&&(this.needsUpdate=!0),e===!0?this.defines.USE_ALPHA_TO_COVERAGE="":delete this.defines.USE_ALPHA_TO_COVERAGE)}}const Pne=new ji,B_e=new N,y_e=new N,Yh=new ji,Gh=new ji,QC=new ji,_ne=new N,Fne=new nt,jh=new Wg,w_e=new N,FX=new Wt,vX=new ta,MC=new ji;let DC,MS;function b_e(i,e,t){return MC.set(0,0,-e,1).applyMatrix4(i.projectionMatrix),MC.multiplyScalar(1/MC.w),MC.x=MS/t.width,MC.y=MS/t.height,MC.applyMatrix4(i.projectionMatrixInverse),MC.multiplyScalar(1/MC.w),Math.abs(Math.max(MC.x,MC.y))}function RFt(i,e){const t=i.matrixWorld,n=i.geometry,s=n.attributes.instanceStart,o=n.attributes.instanceEnd,r=Math.min(n.instanceCount,s.count);for(let A=0,a=r;A<a;A++){jh.start.fromBufferAttribute(s,A),jh.end.fromBufferAttribute(o,A),jh.applyMatrix4(t);const l=new N,c=new N;DC.distanceSqToSegment(jh.start,jh.end,c,l),c.distanceTo(l)<MS*.5&&e.push({point:c,pointOnLine:l,distance:DC.origin.distanceTo(c),object:i,face:null,faceIndex:A,uv:null,uv1:null})}}function NFt(i,e,t){const n=e.projectionMatrix,o=i.material.resolution,r=i.matrixWorld,A=i.geometry,a=A.attributes.instanceStart,l=A.attributes.instanceEnd,c=Math.min(A.instanceCount,a.count),h=-e.near;DC.at(1,QC),QC.w=1,QC.applyMatrix4(e.matrixWorldInverse),QC.applyMatrix4(n),QC.multiplyScalar(1/QC.w),QC.x*=o.x/2,QC.y*=o.y/2,QC.z=0,_ne.copy(QC),Fne.multiplyMatrices(e.matrixWorldInverse,r);for(let d=0,g=c;d<g;d++){if(Yh.fromBufferAttribute(a,d),Gh.fromBufferAttribute(l,d),Yh.w=1,Gh.w=1,Yh.applyMatrix4(Fne),Gh.applyMatrix4(Fne),Yh.z>h&&Gh.z>h)continue;if(Yh.z>h){const y=Yh.z-Gh.z,w=(Yh.z-h)/y;Yh.lerp(Gh,w)}else if(Gh.z>h){const y=Gh.z-Yh.z,w=(Gh.z-h)/y;Gh.lerp(Yh,w)}Yh.applyMatrix4(n),Gh.applyMatrix4(n),Yh.multiplyScalar(1/Yh.w),Gh.multiplyScalar(1/Gh.w),Yh.x*=o.x/2,Yh.y*=o.y/2,Gh.x*=o.x/2,Gh.y*=o.y/2,jh.start.copy(Yh),jh.start.z=0,jh.end.copy(Gh),jh.end.z=0;const p=jh.closestPointToPointParameter(_ne,!0);jh.at(p,w_e);const m=Ai.lerp(Yh.z,Gh.z,p),I=m>=-1&&m<=1,B=_ne.distanceTo(w_e)<MS*.5;if(I&&B){jh.start.fromBufferAttribute(a,d),jh.end.fromBufferAttribute(l,d),jh.start.applyMatrix4(r),jh.end.applyMatrix4(r);const y=new N,w=new N;DC.distanceSqToSegment(jh.start,jh.end,w,y),t.push({point:w,pointOnLine:y,distance:DC.origin.distanceTo(w),object:i,face:null,faceIndex:d,uv:null,uv1:null})}}}class YFt extends lt{constructor(e=new E_e,t=new _X({color:Math.random()*16777215})){super(e,t),this.isLineSegments2=!0,this.type="LineSegments2"}computeLineDistances(){const e=this.geometry,t=e.attributes.instanceStart,n=e.attributes.instanceEnd,s=new Float32Array(2*t.count);for(let r=0,A=0,a=t.count;r<a;r++,A+=2)B_e.fromBufferAttribute(t,r),y_e.fromBufferAttribute(n,r),s[A]=A===0?0:s[A-1],s[A+1]=s[A]+B_e.distanceTo(y_e);const o=new Vv(s,2,1);return e.setAttribute("instanceDistanceStart",new cd(o,1,0)),e.setAttribute("instanceDistanceEnd",new cd(o,1,1)),this}raycast(e,t){const n=this.material.worldUnits,s=e.camera;if(s===null&&!n&&console.error('LineSegments2: "Raycaster.camera" needs to be set in order to raycast against LineSegments2 while worldUnits is set to false.'),n===!1&&(this.material.resolution.x===0||this.material.resolution.y===0))return;const o=e.params.Line2!==void 0&&e.params.Line2.threshold||0;DC=e.ray;const r=this.matrixWorld,A=this.geometry,a=this.material;MS=a.linewidth+o,A.boundingSphere===null&&A.computeBoundingSphere(),vX.copy(A.boundingSphere).applyMatrix4(r);let l;if(n)l=MS*.5;else{const h=Math.max(s.near,vX.distanceToPoint(DC.origin));l=b_e(s,h,a.resolution)}if(vX.radius+=l,DC.intersectsSphere(vX)===!1)return;A.boundingBox===null&&A.computeBoundingBox(),FX.copy(A.boundingBox).applyMatrix4(r);let c;if(n)c=MS*.5;else{const h=Math.max(s.near,FX.distanceToPoint(DC.origin));c=b_e(s,h,a.resolution)}FX.expandByScalar(c),DC.intersectsBox(FX)!==!1&&(n?RFt(this,t):NFt(this,s,t))}onBeforeRender(e){const t=this.material.uniforms;t&&t.resolution&&(e.getViewport(Pne),this.material.uniforms.resolution.value.set(Pne.z,Pne.w))}}class vne extends E_e{constructor(){super(),this.isLineGeometry=!0,this.type="LineGeometry"}setPositions(e){const t=e.length-3,n=new Float32Array(2*t);for(let s=0;s<t;s+=3)n[2*s]=e[s],n[2*s+1]=e[s+1],n[2*s+2]=e[s+2],n[2*s+3]=e[s+3],n[2*s+4]=e[s+4],n[2*s+5]=e[s+5];return super.setPositions(n),this}setColors(e){const t=e.length-3,n=new Float32Array(2*t);for(let s=0;s<t;s+=3)n[2*s]=e[s],n[2*s+1]=e[s+1],n[2*s+2]=e[s+2],n[2*s+3]=e[s+3],n[2*s+4]=e[s+4],n[2*s+5]=e[s+5];return super.setColors(n),this}setFromPoints(e){const t=e.length-1,n=new Float32Array(6*t);for(let s=0;s<t;s++)n[6*s]=e[s].x,n[6*s+1]=e[s].y,n[6*s+2]=e[s].z||0,n[6*s+3]=e[s+1].x,n[6*s+4]=e[s+1].y,n[6*s+5]=e[s+1].z||0;return super.setPositions(n),this}fromLine(e){const t=e.geometry;return this.setPositions(t.attributes.position.array),this}}class Q_e extends YFt{constructor(e=new vne,t=new _X({color:Math.random()*16777215})){super(e,t),this.isLine2=!0,this.type="Line2"}}const RX={lineType:"bezier",lineColor:"#22c55e",previewColor:"#f59e0b",pointColor:"#ffffff",selectedPointColor:"#f59e0b",pointSize:.34,lineWidth:4,sampleCount:64,roundedRadius:1,historyLimit:100},GFt={bezier:"贝塞尔曲线",straight:"直线",rounded:"圆角直线"},jFt={bezier:"∿",straight:"╱",rounded:"⌁"};let UFt=class{type="path-draw";engine;root=new qn;pointsGroup=new qn;points=[];history=[];options={...RX};lineType=RX.lineType;roundedRadius=RX.roundedRadius;line=null;previewLine=null;previewMarker=null;transformControl=null;transformHelper=null;selectedPointId=null;panel=null;pointsList=null;statusElement=null;addButton=null;completeButton=null;radiusInput=null;mode="editing";active=!1;closing=!1;transformDragging=!1;suppressNextCanvasClick=!1;controlsEnabledBeforeDrag=!0;pointSequence=0;pathId="";onKeyDown;constructor(e){this.engine=e,this.root.name="PathDrawRoot",this.pointsGroup.name="PathDrawPoints",this.root.add(this.pointsGroup),this.onKeyDown=this.handleKeyDown.bind(this)}open(e={}){this.active&&this.close(),this.options={...RX,...e},this.pathId=e.id??`path-${Date.now()}`,this.lineType=this.options.lineType,this.roundedRadius=Math.max(0,this.options.roundedRadius),this.active=!0,this.mode="editing",this.engine.scene?.add(this.root),this.ensureTransformControl(),this.createPanel(),this.activateBehavior(),window.addEventListener("keydown",this.onKeyDown,!0),this.refreshAll()}startAddPoint(){return!this.active||this.transformDragging?!1:(this.mode="picking",this.clearSelection(),this.setStatus("请在模型上拾取位置"),this.addButton&&(this.addButton.dataset.active="true"),!0)}setLineType(e){!this.active||this.lineType===e||(this.saveHistory(),this.lineType=e,this.refreshAll(),this.emitChange())}undo(){const e=this.history.pop();return e?(this.restoreSnapshot(e),this.mode="editing",this.clearPreview(),this.refreshAll(),this.emitChange(),!0):!1}clear(){this.points.length!==0&&(this.saveHistory(),this.clearPointRecords(),this.mode="editing",this.clearPreview(),this.refreshAll(),this.emitChange())}getPathData(){if(this.points.length<2)return null;const e=this.buildSamplePoints(this.points.map(t=>t.position));return{version:1,id:this.pathId,lineType:this.lineType,coordinateSystem:"world",closed:!1,roundedRadius:this.roundedRadius,points:this.points.map((t,n)=>({id:t.id,order:n,role:this.getPointRole(n),position:this.toPlainVector(t.position)})),samples:e.map(t=>this.toPlainVector(t)),length:this.calculateLength(e)}}complete(){const e=this.getPathData();if(!e)return null;try{this.options.onComplete?.(e)}finally{this.close()}return e}isActive(){return this.active}close(){this.closeInternal(!0)}closeInternal(e){!this.active&&!this.panel||this.closing||(this.closing=!0,this.active=!1,window.removeEventListener("keydown",this.onKeyDown,!0),this.clearPreview(),this.clearPointRecords(),this.disposeLine("line"),this.detachTransformControl(),this.panel?.remove(),this.panel=null,this.pointsList=null,this.statusElement=null,this.addButton=null,this.completeButton=null,this.radiusInput=null,this.history.length=0,this.selectedPointId=null,this.root.parent?.remove(this.root),e&&this.restoreDefaultBehavior(),this.closing=!1)}dispose(){this.closeInternal(!1),this.transformControl?.dispose(),this.transformControl=null,this.transformHelper=null}update(){!this.active||!this.engine.camera||(this.transformControl&&this.transformControl.camera!==this.engine.camera&&(this.transformControl.camera=this.engine.camera),this.syncLineResolution(this.line),this.syncLineResolution(this.previewLine))}disActive(){this.closing||this.closeInternal(!1)}handleMouseMove(e){if(!this.active||this.mode!=="picking")return;const t=this.getCatchPoint(e?.catch);if(!t){this.clearPreview();return}this.updatePreview(t)}handleMouseClick(e){if(!this.active)return;if(this.suppressNextCanvasClick){this.suppressNextCanvasClick=!1;return}if(this.mode==="picking"){const n=this.getCatchPoint(e?.catch);if(!n)return;this.saveHistory();const s=this.createPointRecord(n);this.points.push(s),this.pointsGroup.add(s.mesh),this.mode="editing",this.clearPreview(),this.selectPoint(s.id),this.refreshAll(),this.emitChange();return}const t=this.pickPointMesh(e);t?this.selectPoint(t.userData.pathDrawPointId):this.clearSelection()}handelKeyEscDown(){if(this.mode==="picking"){this.mode="editing",this.clearPreview(),this.refreshPanel();return}this.clearSelection()}activateBehavior(){const e=this.engine.handelBehaved;e?.init?.(this,{showCatch:!0}),e?.active?.()}restoreDefaultBehavior(){const e=this.engine.handelBehaved;e?.self===this&&(e.disActive?.(),this.engine.interactionModule?.init?.(),this.engine.interactionModule?.active?.(),this.engine.catchSvg&&(this.engine.catchSvg.innerHTML=""))}ensureTransformControl(){if(this.transformControl){this.transformHelper&&!this.transformHelper.parent&&this.engine.scene?.add(this.transformHelper);return}!this.engine.camera||!this.engine.renderer||!this.engine.scene||(this.transformControl=new rS(this.engine.camera,this.engine.renderer.domElement),this.transformControl.setMode("translate"),this.transformControl.size=.72,this.transformControl.addEventListener("dragging-changed",e=>{if(this.transformDragging=!!e.value,this.transformDragging){this.saveHistory(),this.controlsEnabledBeforeDrag=this.engine.controls?.enabled!==!1,this.engine.controls&&(this.engine.controls.enabled=!1);return}this.engine.controls&&(this.engine.controls.enabled=this.controlsEnabledBeforeDrag),this.suppressNextCanvasClick=!0,requestAnimationFrame(()=>{this.suppressNextCanvasClick=!1}),this.refreshAll(),this.emitChange()}),this.transformControl.addEventListener("objectChange",()=>{const e=this.getSelectedPoint();e&&(e.position.copy(e.mesh.position),this.refreshLine(),this.refreshPanel(),this.emitChange())}),this.transformHelper=this.transformControl.getHelper(),this.transformHelper.visible=!1,this.engine.scene.add(this.transformHelper))}detachTransformControl(){this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1,this.transformHelper.parent?.remove(this.transformHelper))}createPointRecord(e,t){const n=new Wc(this.options.pointSize,18,12),s=new Ji({color:this.options.pointColor,depthTest:!1,depthWrite:!1}),o=new lt(n,s),r=t??`path-point-${++this.pointSequence}`;return o.name=r,o.position.copy(e),o.renderOrder=1002,o.userData.pathDrawPointId=r,{id:r,position:e.clone(),mesh:o}}selectPoint(e){const t=this.points.find(n=>n.id===e);!t||!this.transformControl||!this.transformHelper||(this.selectedPointId=e,this.points.forEach(n=>n.mesh.material.color.set(n.id===e?this.options.selectedPointColor:this.options.pointColor)),this.transformControl.attach(t.mesh),this.transformHelper.visible=!0,this.refreshPanel())}clearSelection(){this.selectedPointId=null,this.points.forEach(e=>e.mesh.material.color.set(this.options.pointColor)),this.transformControl?.detach(),this.transformHelper&&(this.transformHelper.visible=!1),this.refreshPanel()}getSelectedPoint(){return this.points.find(e=>e.id===this.selectedPointId)??null}getCatchPoint(e){return e?.point instanceof N?e.point.clone():null}pickPointMesh(e){if(!this.engine.camera||!this.engine.renderer)return null;const t=this.engine.renderer.domElement.clientWidth,n=this.engine.renderer.domElement.clientHeight;if(!t||!n)return null;const s=new Ne(e.offsetX/t*2-1,-(e.offsetY/n)*2+1),o=new Ao;return o.setFromCamera(s,this.engine.camera),o.intersectObjects(this.pointsGroup.children,!1)[0]?.object??null}updatePreview(e){this.previewMarker||(this.previewMarker=new lt(new Wc(this.options.pointSize*.72,14,10),new Ji({color:this.options.previewColor,depthTest:!1,depthWrite:!1})),this.previewMarker.renderOrder=1003,this.root.add(this.previewMarker)),this.previewMarker.position.copy(e),this.previewMarker.visible=!0;const t=[...this.points.map(s=>s.position),e];if(t.length<2){this.disposeLine("previewLine");return}const n=this.buildSamplePoints(t);this.previewLine=this.updateLineObject(this.previewLine,n,!0)}clearPreview(){this.disposeLine("previewLine"),this.previewMarker&&(this.previewMarker.geometry.dispose(),this.previewMarker.material.dispose(),this.previewMarker.parent?.remove(this.previewMarker),this.previewMarker=null)}refreshAll(){this.refreshLine(),this.refreshPanel(),this.requestRender()}refreshLine(){if(this.points.length<2){this.disposeLine("line");return}const e=this.buildSamplePoints(this.points.map(t=>t.position));this.line=this.updateLineObject(this.line,e,!1)}updateLineObject(e,t,n){const s=new vne;if(s.setPositions(t.flatMap(A=>[A.x,A.y,A.z])),e)return e.geometry.dispose(),e.geometry=s,e.computeLineDistances(),this.syncLineResolution(e),this.requestRender(),e;const o=new _X({color:n?this.options.previewColor:this.options.lineColor,linewidth:this.options.lineWidth,dashed:n,dashSize:.32,gapSize:.2,depthTest:!1,transparent:n,opacity:n?.82:1}),r=new Q_e(s,o);return r.name=n?"PathDrawPreviewLine":"PathDrawLine",r.renderOrder=n?1001:1e3,r.computeLineDistances(),this.syncLineResolution(r),this.root.add(r),this.requestRender(),r}syncLineResolution(e){const t=e?.material,n=this.engine.renderer?.domElement;!t||!n||t.resolution.set(n.clientWidth,n.clientHeight)}disposeLine(e){const t=this[e];if(!t)return;t.parent?.remove(t),t.geometry.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(s=>s.dispose()),this[e]=null}buildSamplePoints(e){return e.length<2?e.map(t=>t.clone()):this.lineType==="straight"?e.map(t=>t.clone()):this.lineType==="rounded"?this.sampleRoundedPolyline(e):this.sampleBezier(e)}sampleBezier(e){const t=Math.max(2,this.options.sampleCount);return Array.from({length:t+1},(n,s)=>{const o=e.map(A=>A.clone()),r=s/t;for(let A=o.length-1;A>0;A-=1)for(let a=0;a<A;a+=1)o[a].lerp(o[a+1],r);return o[0]})}sampleRoundedPolyline(e){if(e.length<3||this.roundedRadius<=0)return e.map(s=>s.clone());const t=[e[0].clone()],n=Math.max(4,Math.round(this.options.sampleCount/Math.max(1,e.length-2)));for(let s=1;s<e.length-1;s+=1){const o=e[s-1],r=e[s],A=e[s+1],a=o.distanceTo(r),l=r.distanceTo(A);if(a<1e-8||l<1e-8){t.push(r.clone());continue}const c=Math.min(this.roundedRadius,a*.5,l*.5),h=r.clone().lerp(o,c/a),d=r.clone().lerp(A,c/l);t.push(h);for(let g=1;g<=n;g+=1){const u=g/n,p=1-u;t.push(new N().addScaledVector(h,p*p).addScaledVector(r,2*p*u).addScaledVector(d,u*u))}}return t.push(e[e.length-1].clone()),t}calculateLength(e){let t=0;for(let n=1;n<e.length;n+=1)t+=e[n-1].distanceTo(e[n]);return t}getPointRole(e){return e===0?"start":e===this.points.length-1?"end":"control"}getRoleLabel(e){const t=this.getPointRole(e);return t==="start"?"起点":t==="end"?"终点":`控制点 ${e}`}saveHistory(){this.history.push(this.createSnapshot()),this.history.length>this.options.historyLimit&&this.history.shift()}createSnapshot(){return{lineType:this.lineType,roundedRadius:this.roundedRadius,points:this.points.map(e=>({id:e.id,position:e.position.toArray()}))}}restoreSnapshot(e){this.clearPointRecords(),this.lineType=e.lineType,this.roundedRadius=e.roundedRadius,e.points.forEach(t=>{const n=this.createPointRecord(new N(...t.position),t.id);this.points.push(n),this.pointsGroup.add(n.mesh)})}clearPointRecords(){this.clearSelection(),this.points.forEach(e=>{e.mesh.parent?.remove(e.mesh),e.mesh.geometry.dispose(),e.mesh.material.dispose()}),this.points.length=0}removePoint(e){const t=this.points.findIndex(s=>s.id===e);if(t<0)return;this.saveHistory();const[n]=this.points.splice(t,1);n.mesh.parent?.remove(n.mesh),n.mesh.geometry.dispose(),n.mesh.material.dispose(),this.selectedPointId===e&&this.clearSelection(),this.refreshAll(),this.emitChange()}updatePointCoordinate(e,t,n){const s=this.points.find(o=>o.id===e);!s||!Number.isFinite(n)||s.position[t]===n||(this.saveHistory(),s.position[t]=n,s.mesh.position[t]=n,this.refreshAll(),this.emitChange())}createPanel(){const e=document.createElement("div");e.dataset.pathDrawPanel="true",Object.assign(e.style,{position:"absolute",top:"56px",right:"16px",width:"310px",maxHeight:"calc(100% - 72px)",display:"flex",flexDirection:"column",background:"rgba(255, 255, 255, 0.98)",color:"#111827",border:"1px solid #d1d5db",borderRadius:"6px",boxShadow:"0 12px 28px rgba(15,23,42,0.18)",fontFamily:"Arial, sans-serif",fontSize:"12px",zIndex:"1200",overflow:"hidden"});const t=document.createElement("div");Object.assign(t.style,{display:"flex",alignItems:"center",minHeight:"40px",padding:"0 8px 0 12px",borderBottom:"1px solid #e5e7eb"});const n=document.createElement("strong");n.textContent="路径绘制",n.style.flex="1";const s=document.createElement("span");Object.assign(s.style,{color:"#64748b",marginRight:"8px"});const o=this.createIconButton("×","关闭路径绘制",()=>this.close());t.append(n,s,o),e.appendChild(t),this.statusElement=s;const r=document.createElement("div");Object.assign(r.style,{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:"4px",padding:"8px"}),["bezier","straight","rounded"].forEach(m=>{const I=this.createIconButton(jFt[m],GFt[m],()=>this.setLineType(m));I.dataset.lineType=m,I.style.width="100%",I.style.fontSize="18px",r.appendChild(I)}),e.appendChild(r);const A=document.createElement("label");A.dataset.radiusRow="true",Object.assign(A.style,{display:"none",alignItems:"center",gap:"8px",padding:"0 10px 8px",color:"#475569"});const a=document.createElement("span");a.textContent="圆角";const l=document.createElement("input");l.type="number",l.min="0",l.step="0.1",Object.assign(l.style,{flex:"1",minWidth:"0",height:"26px",padding:"0 7px",color:"#111827",background:"#ffffff",border:"1px solid #cbd5e1",borderRadius:"4px"}),l.addEventListener("change",()=>{const m=Number(l.value);if(!Number.isFinite(m)||m<0||m===this.roundedRadius){l.value=String(this.roundedRadius);return}this.saveHistory(),this.roundedRadius=m,this.refreshAll(),this.emitChange()}),A.append(a,l),e.appendChild(A),this.radiusInput=l;const c=document.createElement("div");Object.assign(c.style,{flex:"1",minHeight:"72px",maxHeight:"200px",overflowY:"auto",overflowX:"hidden",borderTop:"1px solid #e5e7eb"}),e.appendChild(c),this.pointsList=c;const h=document.createElement("div");Object.assign(h.style,{display:"grid",gridTemplateColumns:"1fr auto auto auto",gap:"6px",padding:"8px",borderTop:"1px solid #e5e7eb"});const d=this.createIconButton("+","添加点",()=>this.startAddPoint());d.style.width="100%";const g=this.createIconButton("↶","撤销 Ctrl+Z",()=>this.undo());g.dataset.undoButton="true";const u=this.createIconButton("⌫","清空路径",()=>this.clear());u.dataset.clearButton="true";const p=this.createIconButton("✓","完成并返回路径",()=>this.complete());p.dataset.primary="true",h.append(d,g,u,p),e.appendChild(h),this.addButton=d,this.completeButton=p,this.engine.container?.appendChild(e),this.panel=e}createIconButton(e,t,n){const s=document.createElement("button");return s.type="button",s.textContent=e,s.title=t,s.setAttribute("aria-label",t),Object.assign(s.style,{width:"32px",height:"30px",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:"0",border:"1px solid #d1d5db",borderRadius:"4px",background:"#f8fafc",color:"#334155",cursor:"pointer",fontSize:"15px"}),s.addEventListener("click",n),s}refreshPanel(){if(!this.panel||!this.pointsList)return;this.setStatus(this.mode==="picking"?"拾取中":`${this.points.length} 个点`),this.addButton&&(this.addButton.dataset.active=String(this.mode==="picking"),this.addButton.style.background=this.mode==="picking"?"#ffedd5":"#f8fafc",this.addButton.style.borderColor=this.mode==="picking"?"#f97316":"#d1d5db",this.addButton.style.color=this.mode==="picking"?"#9a3412":"#334155"),this.panel.querySelectorAll("[data-line-type]").forEach(s=>{const o=s.dataset.lineType===this.lineType;s.style.background=o?"#dcfce7":"#f8fafc",s.style.borderColor=o?"#22c55e":"#d1d5db",s.style.color=o?"#166534":"#334155"});const e=this.panel.querySelector("[data-radius-row]");e&&(e.style.display=this.lineType==="rounded"?"flex":"none"),this.radiusInput&&(this.radiusInput.value=String(this.roundedRadius));const t=this.panel.querySelector("[data-undo-button]"),n=this.panel.querySelector("[data-clear-button]");this.setButtonDisabled(t,this.history.length===0),this.setButtonDisabled(n,this.points.length===0),this.setButtonDisabled(this.completeButton,this.points.length<2),this.renderPointRows()}renderPointRows(){if(this.pointsList){if(this.pointsList.innerHTML="",this.points.length===0){const e=document.createElement("div");e.textContent="暂无点位",Object.assign(e.style,{padding:"24px 12px",textAlign:"center",color:"#94a3b8"}),this.pointsList.appendChild(e);return}this.points.forEach((e,t)=>{const n=document.createElement("div");Object.assign(n.style,{display:"grid",gridTemplateColumns:"64px repeat(3, minmax(0, 1fr)) 28px",gap:"4px",alignItems:"center",height:"40px",boxSizing:"border-box",padding:"5px 8px",cursor:"pointer",background:e.id===this.selectedPointId?"#fef3c7":"#ffffff",borderBottom:"1px solid #eef2f7"}),n.addEventListener("click",()=>this.selectPoint(e.id));const s=document.createElement("span");s.textContent=this.getRoleLabel(t),s.title=s.textContent,Object.assign(s.style,{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#334155"}),n.appendChild(s),["x","y","z"].forEach(r=>{const A=document.createElement("input");A.type="number",A.step="0.001",A.value=e.position[r].toFixed(3),A.title=r.toUpperCase(),Object.assign(A.style,{width:"100%",minWidth:"0",height:"25px",padding:"0 4px",boxSizing:"border-box",color:"#1f2937",background:"#ffffff",border:"1px solid #cbd5e1",borderRadius:"3px",fontSize:"11px"}),A.addEventListener("click",a=>a.stopPropagation()),A.addEventListener("change",()=>this.updatePointCoordinate(e.id,r,Number(A.value))),n.appendChild(A)});const o=this.createIconButton("×",`删除${this.getRoleLabel(t)}`,()=>this.removePoint(e.id));o.style.width="28px",o.style.height="25px",o.addEventListener("click",r=>r.stopPropagation()),n.appendChild(o),this.pointsList?.appendChild(n)})}}setButtonDisabled(e,t){e&&(e.disabled=t,e.style.opacity=t?"0.4":"1",e.style.cursor=t?"not-allowed":"pointer",e.dataset.primary==="true"&&(e.style.background=t?"#f1f5f9":"#16a34a",e.style.color=t?"#94a3b8":"#ffffff",e.style.borderColor=t?"#d1d5db":"#15803d"))}setStatus(e){this.statusElement&&(this.statusElement.textContent=e)}handleKeyDown(e){if(!(!this.active||this.isTextInputTarget(e))){if((e.ctrlKey||e.metaKey)&&!e.shiftKey&&!e.altKey&&e.key.toLowerCase()==="z"){if(this.history.length===0)return;e.preventDefault(),e.stopImmediatePropagation(),this.undo();return}e.key==="Escape"&&this.handelKeyEscDown()}}isTextInputTarget(e){const t=e.target;return!!(t?.isContentEditable||["INPUT","TEXTAREA","SELECT"].includes(t?.tagName??""))}emitChange(){this.options.onChange?.(this.getPathData()),this.requestRender()}requestRender(){this.engine.requestComposerRender?.()}toPlainVector(e){return{x:e.x,y:e.y,z:e.z}}};class kFt{engine;constructor(e){this.engine=e}}class WFt{engine;constructor(e){this.engine=e}}class OFt{engine;constructor(e){this.engine=e}getQuantityData(){return[{id:"1",name:"Model 1",type:"Model"}]}}class LFt{engine;constructor(e){this.engine=e}}const SC={version:"4.0.10"}.version;let KFt=class Tfe{engine;overlayMaterial;overlayMeshes=[];animState="idle";animStartTime=0;static FADE_IN_MS=200;static FADE_OUT_MS=150;tagDiv;constructor(e){this.engine=e,this.init();const t=document.createElement("div");this.tagDiv=t,t.className="tagDiv",t.style.position="absolute",t.style.top="0px",t.style.left="0px",t.style.borderRadius="10px",t.style.pointerEvents="none",this.engine.container.appendChild(this.tagDiv)}showModelNameTag(e,t){if(e==null){this.tagDiv.style.display="none";return}let n=this.engine.models.find(A=>A.url==e.url);if(n==null){this.tagDiv.style.display="none";return}let s=n.nodesMap.get(e.ids[0]);if(s.infos&&s.infos.length>0){let A=s.infos[0].name.replace(/\s*\[[a-f0-9-]+\]$/,"");this.tagDiv.innerHTML=A}const r=this.engine.worldToScreen.worldToScreen(t);this.tagDiv?(this.tagDiv.style.left=r.x+10+this.engine.reactBoundingClientRect.left+"px",this.tagDiv.style.top=r.y-10+this.engine.reactBoundingClientRect.top+"px",this.tagDiv.style.display="block"):this.tagDiv&&(this.tagDiv.style.display="none")}init(){this.overlayMaterial=new Ji({color:16777215,transparent:!0,opacity:0,blending:F0,depthWrite:!1}),this.overlayMaterial.clippingPlanes=this.engine.sectionPlane}hightMesh(e,t=16777215,n=.15){this.animState==="fadeOut"&&this.removeOverlayMeshes();const s=(Array.isArray(e)?e:e?[e]:[]).filter(o=>o?.geometry);if(s.length===0){this.clearHighlight();return}this.overlayMaterial.color.set(t),this.overlayMaterial.opacity=0,this.overlayMaterial.userData.targetOpacity=n;for(const o of s){let r=o.geometry.clone();r.computeVertexNormals();const A=new lt(r,this.overlayMaterial);o.updateWorldMatrix(!0,!1),A.matrix.copy(o.matrixWorld),A.matrixAutoUpdate=!1,this.engine.scene.add(A),this.overlayMeshes.push(A)}this.animState="fadeIn",this.animStartTime=performance.now(),this.setAnimationFrameRateExempt(!0)}clearHighlight(){this.overlayMeshes.length===0||this.animState==="fadeOut"||(this.animState="fadeOut",this.animStartTime=performance.now(),this.setAnimationFrameRateExempt(!0))}update(){if(this.animState==="idle"||this.overlayMeshes.length===0)return;const e=performance.now()-this.animStartTime,t=this.overlayMaterial.userData.targetOpacity??.35;if(this.animState==="fadeIn"){const n=Math.min(e/Tfe.FADE_IN_MS,1);this.overlayMaterial.opacity=this.easeOutQuad(n)*t,n>=1&&(this.animState="idle",this.setAnimationFrameRateExempt(!1))}else if(this.animState==="fadeOut"){const n=Math.min(e/Tfe.FADE_OUT_MS,1);this.overlayMaterial.opacity=(1-this.easeOutQuad(n))*t,n>=1&&(this.removeOverlayMeshes(),this.animState="idle",this.setAnimationFrameRateExempt(!1))}}setAnimationFrameRateExempt(e){this.engine.setIdleFrameRateExempt?.("hover-highlight-animation",e)}removeOverlayMeshes(){for(const e of this.overlayMeshes)this.engine.scene.remove(e),e.geometry?.dispose?.();this.overlayMeshes=[]}easeOutQuad(e){return 1-(1-e)*(1-e)}dispose(){this.setAnimationFrameRateExempt(!1),this.removeOverlayMeshes(),this.overlayMaterial.dispose(),this.tagDiv?.remove?.(),this.tagDiv=null,this.animState="idle"}};function Rne(){const i=globalThis.crypto?.subtle;if(!i)throw new Error("[BimEngine] Web Crypto API is required for secure sdkAuth credentials mode");return i}function _Y(i){return new TextEncoder().encode(i)}function FY(i){return i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)}function M_e(i){let e="";return i.forEach(t=>{e+=String.fromCharCode(t)}),btoa(e)}function XFt(i){const e=i.getUTCFullYear(),t=String(i.getUTCMonth()+1).padStart(2,"0"),n=String(i.getUTCDate()).padStart(2,"0");return`${e}${t}${n}`}async function VFt(i){const e=await Rne().digest("SHA-256",FY(_Y(i)));return Array.from(new Uint8Array(e)).map(t=>t.toString(16).padStart(2,"0")).join("")}async function ZFt(i,e){const t=Rne(),n=await t.importKey("raw",FY(i),{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return t.sign("HMAC",n,FY(_Y(e)))}function JFt(i){return _Y([i.appId,i.engineType,i.requestDate,String(i.timestamp),i.nonce].join("|"))}async function zFt(i){const e=Rne(),t=new Date,n=t.getTime(),s=XFt(t),o=globalThis.crypto.randomUUID(),r=globalThis.crypto.getRandomValues(new Uint8Array(12)),A=await VFt(i.appSecret),a=await ZFt(_Y(A),s),l=await e.importKey("raw",a,"AES-GCM",!1,["encrypt"]),c=JSON.stringify({appKey:i.appKey,appSecret:i.appSecret}),h=await e.encrypt({name:"AES-GCM",iv:r,additionalData:FY(JFt({appId:i.appId,engineType:i.engineType,requestDate:s,timestamp:n,nonce:o})),tagLength:128},l,FY(_Y(c)));return{appId:i.appId,engineType:i.engineType,requestDate:s,timestamp:n,nonce:o,iv:M_e(r),cipherText:M_e(new Uint8Array(h)),sdkVersion:i.sdkVersion,origin:i.origin,product:i.product}}const Nne=new Map;function NX(i){return i.replace(/\/+$/,"")}function YX(i){if(i)return i;if(typeof window<"u"&&typeof window.location?.origin=="string")return window.location.origin}function HFt(i,e){return JSON.stringify({endpoint:NX(i.endpoint),token:i.token??"",appId:i.appId??"",appKey:i.appKey??"",appSecret:i.appSecret??"",origin:YX(i.origin)??"",product:i.product??"",engineType:e,sdkVersion:SC})}async function Yne(i,e,t){const n=typeof AbortController<"u"?new AbortController:void 0,s=n?setTimeout(()=>n.abort(),t):void 0;try{const o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:n?.signal}),r=await o.json().catch(()=>({}));if(!o.ok){const A=r?.error?.message??r?.message??`SDK authentication failed with status ${o.status}`;throw new Error(A)}return r}finally{s!=null&&clearTimeout(s)}}async function qFt(i,e){const t=await Yne(`${NX(i.endpoint)}/oauth/sdk-verify`,{sdkToken:i.token,engineType:e,sdkVersion:SC,origin:YX(i.origin),product:i.product},i.timeoutMs??8e3);return t.sdkToken=i.token,t}async function $Ft(i,e){const t=await zFt({appId:i.appId,appKey:i.appKey,appSecret:i.appSecret,engineType:e,sdkVersion:SC,origin:YX(i.origin),product:i.product}),n=await Yne(`${NX(i.endpoint)}/oauth/sdk-token/secure`,t,i.timeoutMs??8e3),s=await Yne(`${NX(i.endpoint)}/oauth/sdk-verify`,{sdkToken:n.sdkToken,engineType:e,sdkVersion:SC,origin:YX(i.origin),product:i.product},i.timeoutMs??8e3);return s.sdkToken=n.sdkToken,s}async function evt(i,e){const t=i?.sdkAuth;if(!t)return null;if(!t.endpoint)throw new Error("[BimEngine] sdkAuth.endpoint is required");if(!t.token&&!(t.appId&&t.appKey&&t.appSecret))return null;const n=HFt(t,e),s=Nne.get(n);if(s){const r=await s;return i&&(i.__sdkAuthSession=r),r}const o=(t.token?qFt(t,e):$Ft(t,e)).then(r=>{if(r.authorized!==!0)throw new Error("[BimEngine] SDK authorization rejected");return i&&(i.__sdkAuthSession=r),r}).catch(r=>{throw Nne.delete(n),r});return Nne.set(n,o),o}var Gne,D_e;function ao(){return D_e||(D_e=1,Gne={options:{usePureJavaScript:!1}}),Gne}var jne={exports:{}},Une,S_e;function tvt(){if(S_e)return Une;S_e=1;var i={};Une=i;var e={};i.encode=function(n,s,o){if(typeof s!="string")throw new TypeError('"alphabet" must be a string.');if(o!==void 0&&typeof o!="number")throw new TypeError('"maxline" must be a number.');var r="";if(!(n instanceof Uint8Array))r=t(n,s);else{var A=0,a=s.length,l=s.charAt(0),c=[0];for(A=0;A<n.length;++A){for(var h=0,d=n[A];h<c.length;++h)d+=c[h]<<8,c[h]=d%a,d=d/a|0;for(;d>0;)c.push(d%a),d=d/a|0}for(A=0;n[A]===0&&A<n.length-1;++A)r+=l;for(A=c.length-1;A>=0;--A)r+=s[c[A]]}if(o){var g=new RegExp(".{1,"+o+"}","g");r=r.match(g).join(`\r
5960
5960
  `)}return r},i.decode=function(n,s){if(typeof n!="string")throw new TypeError('"input" must be a string.');if(typeof s!="string")throw new TypeError('"alphabet" must be a string.');var o=e[s];if(!o){o=e[s]=[];for(var r=0;r<s.length;++r)o[s.charCodeAt(r)]=r}n=n.replace(/\s/g,"");for(var A=s.length,a=s.charAt(0),l=[0],r=0;r<n.length;r++){var c=o[n.charCodeAt(r)];if(c===void 0)return;for(var h=0,d=c;h<l.length;++h)d+=l[h]*A,l[h]=d&255,d>>=8;for(;d>0;)l.push(d&255),d>>=8}for(var g=0;n[g]===a&&g<n.length-1;++g)l.push(0);return typeof Buffer<"u"?Buffer.from(l.reverse()):new Uint8Array(l.reverse())};function t(n,s){var o=0,r=s.length,A=s.charAt(0),a=[0];for(o=0;o<n.length();++o){for(var l=0,c=n.at(o);l<a.length;++l)c+=a[l]<<8,a[l]=c%r,c=c/r|0;for(;c>0;)a.push(c%r),c=c/r|0}var h="";for(o=0;n.at(o)===0&&o<n.length()-1;++o)h+=A;for(o=a.length-1;o>=0;--o)h+=s[a[o]];return h}return Une}var x_e;function Br(){if(x_e)return jne.exports;x_e=1;var i=ao(),e=tvt(),t=jne.exports=i.util=i.util||{};(function(){if(typeof process<"u"&&process.nextTick&&!process.browser){t.nextTick=process.nextTick,typeof setImmediate=="function"?t.setImmediate=setImmediate:t.setImmediate=t.nextTick;return}if(typeof setImmediate=="function"){t.setImmediate=function(){return setImmediate.apply(void 0,arguments)},t.nextTick=function(Q){return setImmediate(Q)};return}if(t.setImmediate=function(Q){setTimeout(Q,0)},typeof window<"u"&&typeof window.postMessage=="function"){let Q=function(b){if(b.source===window&&b.data===I){b.stopPropagation();var P=B.slice();B.length=0,P.forEach(function(F){F()})}};var I="forge.setImmediate",B=[];t.setImmediate=function(b){B.push(b),B.length===1&&window.postMessage(I,"*")},window.addEventListener("message",Q,!0)}if(typeof MutationObserver<"u"){var y=Date.now(),w=!0,M=document.createElement("div"),B=[];new MutationObserver(function(){var b=B.slice();B.length=0,b.forEach(function(P){P()})}).observe(M,{attributes:!0});var D=t.setImmediate;t.setImmediate=function(b){Date.now()-y>15?(y=Date.now(),D(b)):(B.push(b),B.length===1&&M.setAttribute("a",w=!w))}}t.nextTick=t.setImmediate})(),t.isNodejs=typeof process<"u"&&process.versions&&process.versions.node,t.globalScope=(function(){return t.isNodejs?ZD:typeof self>"u"?window:self})(),t.isArray=Array.isArray||function(I){return Object.prototype.toString.call(I)==="[object Array]"},t.isArrayBuffer=function(I){return typeof ArrayBuffer<"u"&&I instanceof ArrayBuffer},t.isArrayBufferView=function(I){return I&&t.isArrayBuffer(I.buffer)&&I.byteLength!==void 0};function n(I){if(!(I===8||I===16||I===24||I===32))throw new Error("Only 8, 16, 24, or 32 bits supported: "+I)}t.ByteBuffer=s;function s(I){if(this.data="",this.read=0,typeof I=="string")this.data=I;else if(t.isArrayBuffer(I)||t.isArrayBufferView(I))if(typeof Buffer<"u"&&I instanceof Buffer)this.data=I.toString("binary");else{var B=new Uint8Array(I);try{this.data=String.fromCharCode.apply(null,B)}catch{for(var y=0;y<B.length;++y)this.putByte(B[y])}}else(I instanceof s||typeof I=="object"&&typeof I.data=="string"&&typeof I.read=="number")&&(this.data=I.data,this.read=I.read);this._constructedStringLength=0}t.ByteStringBuffer=s;var o=4096;t.ByteStringBuffer.prototype._optimizeConstructedString=function(I){this._constructedStringLength+=I,this._constructedStringLength>o&&(this.data.substr(0,1),this._constructedStringLength=0)},t.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},t.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},t.ByteStringBuffer.prototype.putByte=function(I){return this.putBytes(String.fromCharCode(I))},t.ByteStringBuffer.prototype.fillWithByte=function(I,B){I=String.fromCharCode(I);for(var y=this.data;B>0;)B&1&&(y+=I),B>>>=1,B>0&&(I+=I);return this.data=y,this._optimizeConstructedString(B),this},t.ByteStringBuffer.prototype.putBytes=function(I){return this.data+=I,this._optimizeConstructedString(I.length),this},t.ByteStringBuffer.prototype.putString=function(I){return this.putBytes(t.encodeUtf8(I))},t.ByteStringBuffer.prototype.putInt16=function(I){return this.putBytes(String.fromCharCode(I>>8&255)+String.fromCharCode(I&255))},t.ByteStringBuffer.prototype.putInt24=function(I){return this.putBytes(String.fromCharCode(I>>16&255)+String.fromCharCode(I>>8&255)+String.fromCharCode(I&255))},t.ByteStringBuffer.prototype.putInt32=function(I){return this.putBytes(String.fromCharCode(I>>24&255)+String.fromCharCode(I>>16&255)+String.fromCharCode(I>>8&255)+String.fromCharCode(I&255))},t.ByteStringBuffer.prototype.putInt16Le=function(I){return this.putBytes(String.fromCharCode(I&255)+String.fromCharCode(I>>8&255))},t.ByteStringBuffer.prototype.putInt24Le=function(I){return this.putBytes(String.fromCharCode(I&255)+String.fromCharCode(I>>8&255)+String.fromCharCode(I>>16&255))},t.ByteStringBuffer.prototype.putInt32Le=function(I){return this.putBytes(String.fromCharCode(I&255)+String.fromCharCode(I>>8&255)+String.fromCharCode(I>>16&255)+String.fromCharCode(I>>24&255))},t.ByteStringBuffer.prototype.putInt=function(I,B){n(B);var y="";do B-=8,y+=String.fromCharCode(I>>B&255);while(B>0);return this.putBytes(y)},t.ByteStringBuffer.prototype.putSignedInt=function(I,B){return I<0&&(I+=2<<B-1),this.putInt(I,B)},t.ByteStringBuffer.prototype.putBuffer=function(I){return this.putBytes(I.getBytes())},t.ByteStringBuffer.prototype.getByte=function(){return this.data.charCodeAt(this.read++)},t.ByteStringBuffer.prototype.getInt16=function(){var I=this.data.charCodeAt(this.read)<<8^this.data.charCodeAt(this.read+1);return this.read+=2,I},t.ByteStringBuffer.prototype.getInt24=function(){var I=this.data.charCodeAt(this.read)<<16^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2);return this.read+=3,I},t.ByteStringBuffer.prototype.getInt32=function(){var I=this.data.charCodeAt(this.read)<<24^this.data.charCodeAt(this.read+1)<<16^this.data.charCodeAt(this.read+2)<<8^this.data.charCodeAt(this.read+3);return this.read+=4,I},t.ByteStringBuffer.prototype.getInt16Le=function(){var I=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8;return this.read+=2,I},t.ByteStringBuffer.prototype.getInt24Le=function(){var I=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16;return this.read+=3,I},t.ByteStringBuffer.prototype.getInt32Le=function(){var I=this.data.charCodeAt(this.read)^this.data.charCodeAt(this.read+1)<<8^this.data.charCodeAt(this.read+2)<<16^this.data.charCodeAt(this.read+3)<<24;return this.read+=4,I},t.ByteStringBuffer.prototype.getInt=function(I){n(I);var B=0;do B=(B<<8)+this.data.charCodeAt(this.read++),I-=8;while(I>0);return B},t.ByteStringBuffer.prototype.getSignedInt=function(I){var B=this.getInt(I),y=2<<I-2;return B>=y&&(B-=y<<1),B},t.ByteStringBuffer.prototype.getBytes=function(I){var B;return I?(I=Math.min(this.length(),I),B=this.data.slice(this.read,this.read+I),this.read+=I):I===0?B="":(B=this.read===0?this.data:this.data.slice(this.read),this.clear()),B},t.ByteStringBuffer.prototype.bytes=function(I){return typeof I>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+I)},t.ByteStringBuffer.prototype.at=function(I){return this.data.charCodeAt(this.read+I)},t.ByteStringBuffer.prototype.setAt=function(I,B){return this.data=this.data.substr(0,this.read+I)+String.fromCharCode(B)+this.data.substr(this.read+I+1),this},t.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},t.ByteStringBuffer.prototype.copy=function(){var I=t.createBuffer(this.data);return I.read=this.read,I},t.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},t.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},t.ByteStringBuffer.prototype.truncate=function(I){var B=Math.max(0,this.length()-I);return this.data=this.data.substr(this.read,B),this.read=0,this},t.ByteStringBuffer.prototype.toHex=function(){for(var I="",B=this.read;B<this.data.length;++B){var y=this.data.charCodeAt(B);y<16&&(I+="0"),I+=y.toString(16)}return I},t.ByteStringBuffer.prototype.toString=function(){return t.decodeUtf8(this.bytes())};function r(I,B){B=B||{},this.read=B.readOffset||0,this.growSize=B.growSize||1024;var y=t.isArrayBuffer(I),w=t.isArrayBufferView(I);if(y||w){y?this.data=new DataView(I):this.data=new DataView(I.buffer,I.byteOffset,I.byteLength),this.write="writeOffset"in B?B.writeOffset:this.data.byteLength;return}this.data=new DataView(new ArrayBuffer(0)),this.write=0,I!=null&&this.putBytes(I),"writeOffset"in B&&(this.write=B.writeOffset)}t.DataBuffer=r,t.DataBuffer.prototype.length=function(){return this.write-this.read},t.DataBuffer.prototype.isEmpty=function(){return this.length()<=0},t.DataBuffer.prototype.accommodate=function(I,B){if(this.length()>=I)return this;B=Math.max(B||this.growSize,I);var y=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),w=new Uint8Array(this.length()+B);return w.set(y),this.data=new DataView(w.buffer),this},t.DataBuffer.prototype.putByte=function(I){return this.accommodate(1),this.data.setUint8(this.write++,I),this},t.DataBuffer.prototype.fillWithByte=function(I,B){this.accommodate(B);for(var y=0;y<B;++y)this.data.setUint8(I);return this},t.DataBuffer.prototype.putBytes=function(I,B){if(t.isArrayBufferView(I)){var y=new Uint8Array(I.buffer,I.byteOffset,I.byteLength),w=y.byteLength-y.byteOffset;this.accommodate(w);var M=new Uint8Array(this.data.buffer,this.write);return M.set(y),this.write+=w,this}if(t.isArrayBuffer(I)){var y=new Uint8Array(I);this.accommodate(y.byteLength);var M=new Uint8Array(this.data.buffer);return M.set(y,this.write),this.write+=y.byteLength,this}if(I instanceof t.DataBuffer||typeof I=="object"&&typeof I.read=="number"&&typeof I.write=="number"&&t.isArrayBufferView(I.data)){var y=new Uint8Array(I.data.byteLength,I.read,I.length());this.accommodate(y.byteLength);var M=new Uint8Array(I.data.byteLength,this.write);return M.set(y),this.write+=y.byteLength,this}if(I instanceof t.ByteStringBuffer&&(I=I.data,B="binary"),B=B||"binary",typeof I=="string"){var D;if(B==="hex")return this.accommodate(Math.ceil(I.length/2)),D=new Uint8Array(this.data.buffer,this.write),this.write+=t.binary.hex.decode(I,D,this.write),this;if(B==="base64")return this.accommodate(Math.ceil(I.length/4)*3),D=new Uint8Array(this.data.buffer,this.write),this.write+=t.binary.base64.decode(I,D,this.write),this;if(B==="utf8"&&(I=t.encodeUtf8(I),B="binary"),B==="binary"||B==="raw")return this.accommodate(I.length),D=new Uint8Array(this.data.buffer,this.write),this.write+=t.binary.raw.decode(D),this;if(B==="utf16")return this.accommodate(I.length*2),D=new Uint16Array(this.data.buffer,this.write),this.write+=t.text.utf16.encode(D),this;throw new Error("Invalid encoding: "+B)}throw Error("Invalid parameter: "+I)},t.DataBuffer.prototype.putBuffer=function(I){return this.putBytes(I),I.clear(),this},t.DataBuffer.prototype.putString=function(I){return this.putBytes(I,"utf16")},t.DataBuffer.prototype.putInt16=function(I){return this.accommodate(2),this.data.setInt16(this.write,I),this.write+=2,this},t.DataBuffer.prototype.putInt24=function(I){return this.accommodate(3),this.data.setInt16(this.write,I>>8&65535),this.data.setInt8(this.write,I>>16&255),this.write+=3,this},t.DataBuffer.prototype.putInt32=function(I){return this.accommodate(4),this.data.setInt32(this.write,I),this.write+=4,this},t.DataBuffer.prototype.putInt16Le=function(I){return this.accommodate(2),this.data.setInt16(this.write,I,!0),this.write+=2,this},t.DataBuffer.prototype.putInt24Le=function(I){return this.accommodate(3),this.data.setInt8(this.write,I>>16&255),this.data.setInt16(this.write,I>>8&65535,!0),this.write+=3,this},t.DataBuffer.prototype.putInt32Le=function(I){return this.accommodate(4),this.data.setInt32(this.write,I,!0),this.write+=4,this},t.DataBuffer.prototype.putInt=function(I,B){n(B),this.accommodate(B/8);do B-=8,this.data.setInt8(this.write++,I>>B&255);while(B>0);return this},t.DataBuffer.prototype.putSignedInt=function(I,B){return n(B),this.accommodate(B/8),I<0&&(I+=2<<B-1),this.putInt(I,B)},t.DataBuffer.prototype.getByte=function(){return this.data.getInt8(this.read++)},t.DataBuffer.prototype.getInt16=function(){var I=this.data.getInt16(this.read);return this.read+=2,I},t.DataBuffer.prototype.getInt24=function(){var I=this.data.getInt16(this.read)<<8^this.data.getInt8(this.read+2);return this.read+=3,I},t.DataBuffer.prototype.getInt32=function(){var I=this.data.getInt32(this.read);return this.read+=4,I},t.DataBuffer.prototype.getInt16Le=function(){var I=this.data.getInt16(this.read,!0);return this.read+=2,I},t.DataBuffer.prototype.getInt24Le=function(){var I=this.data.getInt8(this.read)^this.data.getInt16(this.read+1,!0)<<8;return this.read+=3,I},t.DataBuffer.prototype.getInt32Le=function(){var I=this.data.getInt32(this.read,!0);return this.read+=4,I},t.DataBuffer.prototype.getInt=function(I){n(I);var B=0;do B=(B<<8)+this.data.getInt8(this.read++),I-=8;while(I>0);return B},t.DataBuffer.prototype.getSignedInt=function(I){var B=this.getInt(I),y=2<<I-2;return B>=y&&(B-=y<<1),B},t.DataBuffer.prototype.getBytes=function(I){var B;return I?(I=Math.min(this.length(),I),B=this.data.slice(this.read,this.read+I),this.read+=I):I===0?B="":(B=this.read===0?this.data:this.data.slice(this.read),this.clear()),B},t.DataBuffer.prototype.bytes=function(I){return typeof I>"u"?this.data.slice(this.read):this.data.slice(this.read,this.read+I)},t.DataBuffer.prototype.at=function(I){return this.data.getUint8(this.read+I)},t.DataBuffer.prototype.setAt=function(I,B){return this.data.setUint8(I,B),this},t.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},t.DataBuffer.prototype.copy=function(){return new t.DataBuffer(this)},t.DataBuffer.prototype.compact=function(){if(this.read>0){var I=new Uint8Array(this.data.buffer,this.read),B=new Uint8Array(I.byteLength);B.set(I),this.data=new DataView(B),this.write-=this.read,this.read=0}return this},t.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},t.DataBuffer.prototype.truncate=function(I){return this.write=Math.max(0,this.length()-I),this.read=Math.min(this.read,this.write),this},t.DataBuffer.prototype.toHex=function(){for(var I="",B=this.read;B<this.data.byteLength;++B){var y=this.data.getUint8(B);y<16&&(I+="0"),I+=y.toString(16)}return I},t.DataBuffer.prototype.toString=function(I){var B=new Uint8Array(this.data,this.read,this.length());if(I=I||"utf8",I==="binary"||I==="raw")return t.binary.raw.encode(B);if(I==="hex")return t.binary.hex.encode(B);if(I==="base64")return t.binary.base64.encode(B);if(I==="utf8")return t.text.utf8.decode(B);if(I==="utf16")return t.text.utf16.decode(B);throw new Error("Invalid encoding: "+I)},t.createBuffer=function(I,B){return B=B||"raw",I!==void 0&&B==="utf8"&&(I=t.encodeUtf8(I)),new t.ByteBuffer(I)},t.fillString=function(I,B){for(var y="";B>0;)B&1&&(y+=I),B>>>=1,B>0&&(I+=I);return y},t.xorBytes=function(I,B,y){for(var w="",M="",D="",Q=0,b=0;y>0;--y,++Q)M=I.charCodeAt(Q)^B.charCodeAt(Q),b>=10&&(w+=D,D="",b=0),D+=String.fromCharCode(M),++b;return w+=D,w},t.hexToBytes=function(I){var B="",y=0;for(I.length&!0&&(y=1,B+=String.fromCharCode(parseInt(I[0],16)));y<I.length;y+=2)B+=String.fromCharCode(parseInt(I.substr(y,2),16));return B},t.bytesToHex=function(I){return t.createBuffer(I).toHex()},t.int32ToBytes=function(I){return String.fromCharCode(I>>24&255)+String.fromCharCode(I>>16&255)+String.fromCharCode(I>>8&255)+String.fromCharCode(I&255)};var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],l="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";t.encode64=function(I,B){for(var y="",w="",M,D,Q,b=0;b<I.length;)M=I.charCodeAt(b++),D=I.charCodeAt(b++),Q=I.charCodeAt(b++),y+=A.charAt(M>>2),y+=A.charAt((M&3)<<4|D>>4),isNaN(D)?y+="==":(y+=A.charAt((D&15)<<2|Q>>6),y+=isNaN(Q)?"=":A.charAt(Q&63)),B&&y.length>B&&(w+=y.substr(0,B)+`\r
5961
5961
  `,y=y.substr(B));return w+=y,w},t.decode64=function(I){I=I.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var B="",y,w,M,D,Q=0;Q<I.length;)y=a[I.charCodeAt(Q++)-43],w=a[I.charCodeAt(Q++)-43],M=a[I.charCodeAt(Q++)-43],D=a[I.charCodeAt(Q++)-43],B+=String.fromCharCode(y<<2|w>>4),M!==64&&(B+=String.fromCharCode((w&15)<<4|M>>2),D!==64&&(B+=String.fromCharCode((M&3)<<6|D)));return B},t.encodeUtf8=function(I){return unescape(encodeURIComponent(I))},t.decodeUtf8=function(I){return decodeURIComponent(escape(I))},t.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:e.encode,decode:e.decode}},t.binary.raw.encode=function(I){return String.fromCharCode.apply(null,I)},t.binary.raw.decode=function(I,B,y){var w=B;w||(w=new Uint8Array(I.length)),y=y||0;for(var M=y,D=0;D<I.length;++D)w[M++]=I.charCodeAt(D);return B?M-y:w},t.binary.hex.encode=t.bytesToHex,t.binary.hex.decode=function(I,B,y){var w=B;w||(w=new Uint8Array(Math.ceil(I.length/2))),y=y||0;var M=0,D=y;for(I.length&1&&(M=1,w[D++]=parseInt(I[0],16));M<I.length;M+=2)w[D++]=parseInt(I.substr(M,2),16);return B?D-y:w},t.binary.base64.encode=function(I,B){for(var y="",w="",M,D,Q,b=0;b<I.byteLength;)M=I[b++],D=I[b++],Q=I[b++],y+=A.charAt(M>>2),y+=A.charAt((M&3)<<4|D>>4),isNaN(D)?y+="==":(y+=A.charAt((D&15)<<2|Q>>6),y+=isNaN(Q)?"=":A.charAt(Q&63)),B&&y.length>B&&(w+=y.substr(0,B)+`\r
5962
5962
  `,y=y.substr(B));return w+=y,w},t.binary.base64.decode=function(I,B,y){var w=B;w||(w=new Uint8Array(Math.ceil(I.length/4)*3)),I=I.replace(/[^A-Za-z0-9\+\/\=]/g,""),y=y||0;for(var M,D,Q,b,P=0,F=y;P<I.length;)M=a[I.charCodeAt(P++)-43],D=a[I.charCodeAt(P++)-43],Q=a[I.charCodeAt(P++)-43],b=a[I.charCodeAt(P++)-43],w[F++]=M<<2|D>>4,Q!==64&&(w[F++]=(D&15)<<4|Q>>2,b!==64&&(w[F++]=(Q&3)<<6|b));return B?F-y:w.subarray(0,F)},t.binary.base58.encode=function(I,B){return t.binary.baseN.encode(I,l,B)},t.binary.base58.decode=function(I,B){return t.binary.baseN.decode(I,l,B)},t.text={utf8:{},utf16:{}},t.text.utf8.encode=function(I,B,y){I=t.encodeUtf8(I);var w=B;w||(w=new Uint8Array(I.length)),y=y||0;for(var M=y,D=0;D<I.length;++D)w[M++]=I.charCodeAt(D);return B?M-y:w},t.text.utf8.decode=function(I){return t.decodeUtf8(String.fromCharCode.apply(null,I))},t.text.utf16.encode=function(I,B,y){var w=B;w||(w=new Uint8Array(I.length*2));var M=new Uint16Array(w.buffer);y=y||0;for(var D=y,Q=y,b=0;b<I.length;++b)M[Q++]=I.charCodeAt(b),D+=2;return B?D-y:w},t.text.utf16.decode=function(I){return String.fromCharCode.apply(null,new Uint16Array(I.buffer))},t.deflate=function(I,B,y){if(B=t.decode64(I.deflate(t.encode64(B)).rval),y){var w=2,M=B.charCodeAt(1);M&32&&(w=6),B=B.substring(w,B.length-4)}return B},t.inflate=function(I,B,y){var w=I.inflate(t.encode64(B)).rval;return w===null?null:t.decode64(w)};var c=function(I,B,y){if(!I)throw new Error("WebStorage not available.");var w;if(y===null?w=I.removeItem(B):(y=t.encode64(JSON.stringify(y)),w=I.setItem(B,y)),typeof w<"u"&&w.rval!==!0){var M=new Error(w.error.message);throw M.id=w.error.id,M.name=w.error.name,M}},h=function(I,B){if(!I)throw new Error("WebStorage not available.");var y=I.getItem(B);if(I.init)if(y.rval===null){if(y.error){var w=new Error(y.error.message);throw w.id=y.error.id,w.name=y.error.name,w}y=null}else y=y.rval;return y!==null&&(y=JSON.parse(t.decode64(y))),y},d=function(I,B,y,w){var M=h(I,B);M===null&&(M={}),M[y]=w,c(I,B,M)},g=function(I,B,y){var w=h(I,B);return w!==null&&(w=y in w?w[y]:null),w},u=function(I,B,y){var w=h(I,B);if(w!==null&&y in w){delete w[y];var M=!0;for(var D in w){M=!1;break}M&&(w=null),c(I,B,w)}},p=function(I,B){c(I,B,null)},m=function(I,B,y){var w=null;typeof y>"u"&&(y=["web","flash"]);var M,D=!1,Q=null;for(var b in y){M=y[b];try{if(M==="flash"||M==="both"){if(B[0]===null)throw new Error("Flash local storage not available.");w=I.apply(this,B),D=M==="flash"}(M==="web"||M==="both")&&(B[0]=localStorage,w=I.apply(this,B),D=!0)}catch(P){Q=P}if(D)break}if(!D)throw Q;return w};return t.setItem=function(I,B,y,w,M){m(d,arguments,M)},t.getItem=function(I,B,y,w){return m(g,arguments,w)},t.removeItem=function(I,B,y,w){m(u,arguments,w)},t.clearItems=function(I,B,y){m(p,arguments,y)},t.isEmpty=function(I){for(var B in I)if(I.hasOwnProperty(B))return!1;return!0},t.format=function(I){for(var B=/%./g,y,w,M=0,D=[],Q=0;y=B.exec(I);){w=I.substring(Q,B.lastIndex-2),w.length>0&&D.push(w),Q=B.lastIndex;var b=y[0][1];switch(b){case"s":case"o":M<arguments.length?D.push(arguments[M+++1]):D.push("<?>");break;case"%":D.push("%");break;default:D.push("<%"+b+"?>")}}return D.push(I.substring(Q)),D.join("")},t.formatNumber=function(I,B,y,w){var M=I,D=isNaN(B=Math.abs(B))?2:B,Q=y===void 0?",":y,b=w===void 0?".":w,P=M<0?"-":"",F=parseInt(M=Math.abs(+M||0).toFixed(D),10)+"",T=F.length>3?F.length%3:0;return P+(T?F.substr(0,T)+b:"")+F.substr(T).replace(/(\d{3})(?=\d)/g,"$1"+b)+(D?Q+Math.abs(M-F).toFixed(D).slice(2):"")},t.formatSize=function(I){return I>=1073741824?I=t.formatNumber(I/1073741824,2,".","")+" GiB":I>=1048576?I=t.formatNumber(I/1048576,2,".","")+" MiB":I>=1024?I=t.formatNumber(I/1024,0)+" KiB":I=t.formatNumber(I,0)+" bytes",I},t.bytesFromIP=function(I){return I.indexOf(".")!==-1?t.bytesFromIPv4(I):I.indexOf(":")!==-1?t.bytesFromIPv6(I):null},t.bytesFromIPv4=function(I){if(I=I.split("."),I.length!==4)return null;for(var B=t.createBuffer(),y=0;y<I.length;++y){var w=parseInt(I[y],10);if(isNaN(w))return null;B.putByte(w)}return B.getBytes()},t.bytesFromIPv6=function(I){var B=0;I=I.split(":").filter(function(Q){return Q.length===0&&++B,!0});for(var y=(8-I.length+B)*2,w=t.createBuffer(),M=0;M<8;++M){if(!I[M]||I[M].length===0){w.fillWithByte(0,y),y=0;continue}var D=t.hexToBytes(I[M]);D.length<2&&w.putByte(0),w.putBytes(D)}return w.getBytes()},t.bytesToIP=function(I){return I.length===4?t.bytesToIPv4(I):I.length===16?t.bytesToIPv6(I):null},t.bytesToIPv4=function(I){if(I.length!==4)return null;for(var B=[],y=0;y<I.length;++y)B.push(I.charCodeAt(y));return B.join(".")},t.bytesToIPv6=function(I){if(I.length!==16)return null;for(var B=[],y=[],w=0,M=0;M<I.length;M+=2){for(var D=t.bytesToHex(I[M]+I[M+1]);D[0]==="0"&&D!=="0";)D=D.substr(1);if(D==="0"){var Q=y[y.length-1],b=B.length;!Q||b!==Q.end+1?y.push({start:b,end:b}):(Q.end=b,Q.end-Q.start>y[w].end-y[w].start&&(w=y.length-1))}B.push(D)}if(y.length>0){var P=y[w];P.end-P.start>0&&(B.splice(P.start,P.end-P.start+1,""),P.start===0&&B.unshift(""),P.end===7&&B.push(""))}return B.join(":")},t.estimateCores=function(I,B){if(typeof I=="function"&&(B=I,I={}),I=I||{},"cores"in t&&!I.update)return B(null,t.cores);if(typeof navigator<"u"&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return t.cores=navigator.hardwareConcurrency,B(null,t.cores);if(typeof Worker>"u")return t.cores=1,B(null,t.cores);if(typeof Blob>"u")return t.cores=2,B(null,t.cores);var y=URL.createObjectURL(new Blob(["(",(function(){self.addEventListener("message",function(Q){var b=Date.now(),P=b+4;self.postMessage({st:b,et:P})})}).toString(),")()"],{type:"application/javascript"}));w([],5,16);function w(Q,b,P){if(b===0){var F=Math.floor(Q.reduce(function(T,x){return T+x},0)/Q.length);return t.cores=Math.max(1,F),URL.revokeObjectURL(y),B(null,t.cores)}M(P,function(T,x){Q.push(D(P,x)),w(Q,b-1,P)})}function M(Q,b){for(var P=[],F=[],T=0;T<Q;++T){var x=new Worker(y);x.addEventListener("message",function(C){if(F.push(C.data),F.length===Q){for(var S=0;S<Q;++S)P[S].terminate();b(null,F)}}),P.push(x)}for(var T=0;T<Q;++T)P[T].postMessage(T)}function D(Q,b){for(var P=[],F=0;F<Q;++F)for(var T=b[F],x=P[F]=[],C=0;C<Q;++C)if(F!==C){var S=b[C];(T.st>S.st&&T.st<S.et||S.st>T.st&&S.st<T.et)&&x.push(C)}return P.reduce(function(v,Y){return Math.max(v,Y.length)},0)}},jne.exports}var kne,T_e;function Wne(){if(T_e)return kne;T_e=1;var i=ao();Br(),kne=i.cipher=i.cipher||{},i.cipher.algorithms=i.cipher.algorithms||{},i.cipher.createCipher=function(t,n){var s=t;if(typeof s=="string"&&(s=i.cipher.getAlgorithm(s),s&&(s=s())),!s)throw new Error("Unsupported algorithm: "+t);return new i.cipher.BlockCipher({algorithm:s,key:n,decrypt:!1})},i.cipher.createDecipher=function(t,n){var s=t;if(typeof s=="string"&&(s=i.cipher.getAlgorithm(s),s&&(s=s())),!s)throw new Error("Unsupported algorithm: "+t);return new i.cipher.BlockCipher({algorithm:s,key:n,decrypt:!0})},i.cipher.registerAlgorithm=function(t,n){t=t.toUpperCase(),i.cipher.algorithms[t]=n},i.cipher.getAlgorithm=function(t){return t=t.toUpperCase(),t in i.cipher.algorithms?i.cipher.algorithms[t]:null};var e=i.cipher.BlockCipher=function(t){this.algorithm=t.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=t.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=t.decrypt,this.algorithm.initialize(t)};return e.prototype.start=function(t){t=t||{};var n={};for(var s in t)n[s]=t[s];n.decrypt=this._decrypt,this._finish=!1,this._input=i.util.createBuffer(),this.output=t.output||i.util.createBuffer(),this.mode.start(n)},e.prototype.update=function(t){for(t&&this._input.putBuffer(t);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},e.prototype.finish=function(t){t&&(this.mode.name==="ECB"||this.mode.name==="CBC")&&(this.mode.pad=function(s){return t(this.blockSize,s,!1)},this.mode.unpad=function(s){return t(this.blockSize,s,!0)});var n={};return n.decrypt=this._decrypt,n.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,n)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,n))||this.mode.afterFinish&&!this.mode.afterFinish(this.output,n))},kne}var One={exports:{}},P_e;function __e(){if(P_e)return One.exports;P_e=1;var i=ao();Br(),i.cipher=i.cipher||{};var e=One.exports=i.cipher.modes=i.cipher.modes||{};e.ecb=function(o){o=o||{},this.name="ECB",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},e.ecb.prototype.start=function(o){},e.ecb.prototype.encrypt=function(o,r,A){if(o.length()<this.blockSize&&!(A&&o.length()>0))return!0;for(var a=0;a<this._ints;++a)this._inBlock[a]=o.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var a=0;a<this._ints;++a)r.putInt32(this._outBlock[a])},e.ecb.prototype.decrypt=function(o,r,A){if(o.length()<this.blockSize&&!(A&&o.length()>0))return!0;for(var a=0;a<this._ints;++a)this._inBlock[a]=o.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var a=0;a<this._ints;++a)r.putInt32(this._outBlock[a])},e.ecb.prototype.pad=function(o,r){var A=o.length()===this.blockSize?this.blockSize:this.blockSize-o.length();return o.fillWithByte(A,A),!0},e.ecb.prototype.unpad=function(o,r){if(r.overflow>0)return!1;var A=o.length(),a=o.at(A-1);return a>this.blockSize<<2?!1:(o.truncate(a),!0)},e.cbc=function(o){o=o||{},this.name="CBC",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},e.cbc.prototype.start=function(o){if(o.iv===null){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else if("iv"in o)this._iv=t(o.iv,this.blockSize),this._prev=this._iv.slice(0);else throw new Error("Invalid IV parameter.")},e.cbc.prototype.encrypt=function(o,r,A){if(o.length()<this.blockSize&&!(A&&o.length()>0))return!0;for(var a=0;a<this._ints;++a)this._inBlock[a]=this._prev[a]^o.getInt32();this.cipher.encrypt(this._inBlock,this._outBlock);for(var a=0;a<this._ints;++a)r.putInt32(this._outBlock[a]);this._prev=this._outBlock},e.cbc.prototype.decrypt=function(o,r,A){if(o.length()<this.blockSize&&!(A&&o.length()>0))return!0;for(var a=0;a<this._ints;++a)this._inBlock[a]=o.getInt32();this.cipher.decrypt(this._inBlock,this._outBlock);for(var a=0;a<this._ints;++a)r.putInt32(this._prev[a]^this._outBlock[a]);this._prev=this._inBlock.slice(0)},e.cbc.prototype.pad=function(o,r){var A=o.length()===this.blockSize?this.blockSize:this.blockSize-o.length();return o.fillWithByte(A,A),!0},e.cbc.prototype.unpad=function(o,r){if(r.overflow>0)return!1;var A=o.length(),a=o.at(A-1);return a>this.blockSize<<2?!1:(o.truncate(a),!0)},e.cfb=function(o){o=o||{},this.name="CFB",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=i.util.createBuffer(),this._partialBytes=0},e.cfb.prototype.start=function(o){if(!("iv"in o))throw new Error("Invalid IV parameter.");this._iv=t(o.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},e.cfb.prototype.encrypt=function(o,r,A){var a=o.length();if(a===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize){for(var l=0;l<this._ints;++l)this._inBlock[l]=o.getInt32()^this._outBlock[l],r.putInt32(this._inBlock[l]);return}var c=(this.blockSize-a)%this.blockSize;c>0&&(c=this.blockSize-c),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialBlock[l]=o.getInt32()^this._outBlock[l],this._partialOutput.putInt32(this._partialBlock[l]);if(c>0)o.read-=this.blockSize;else for(var l=0;l<this._ints;++l)this._inBlock[l]=this._partialBlock[l];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),c>0&&!A)return r.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=c,!0;r.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0},e.cfb.prototype.decrypt=function(o,r,A){var a=o.length();if(a===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize){for(var l=0;l<this._ints;++l)this._inBlock[l]=o.getInt32(),r.putInt32(this._inBlock[l]^this._outBlock[l]);return}var c=(this.blockSize-a)%this.blockSize;c>0&&(c=this.blockSize-c),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialBlock[l]=o.getInt32(),this._partialOutput.putInt32(this._partialBlock[l]^this._outBlock[l]);if(c>0)o.read-=this.blockSize;else for(var l=0;l<this._ints;++l)this._inBlock[l]=this._partialBlock[l];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),c>0&&!A)return r.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=c,!0;r.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0},e.ofb=function(o){o=o||{},this.name="OFB",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=i.util.createBuffer(),this._partialBytes=0},e.ofb.prototype.start=function(o){if(!("iv"in o))throw new Error("Invalid IV parameter.");this._iv=t(o.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},e.ofb.prototype.encrypt=function(o,r,A){var a=o.length();if(o.length()===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize){for(var l=0;l<this._ints;++l)r.putInt32(o.getInt32()^this._outBlock[l]),this._inBlock[l]=this._outBlock[l];return}var c=(this.blockSize-a)%this.blockSize;c>0&&(c=this.blockSize-c),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialOutput.putInt32(o.getInt32()^this._outBlock[l]);if(c>0)o.read-=this.blockSize;else for(var l=0;l<this._ints;++l)this._inBlock[l]=this._outBlock[l];if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),c>0&&!A)return r.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=c,!0;r.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0},e.ofb.prototype.decrypt=e.ofb.prototype.encrypt,e.ctr=function(o){o=o||{},this.name="CTR",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=i.util.createBuffer(),this._partialBytes=0},e.ctr.prototype.start=function(o){if(!("iv"in o))throw new Error("Invalid IV parameter.");this._iv=t(o.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},e.ctr.prototype.encrypt=function(o,r,A){var a=o.length();if(a===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize)for(var l=0;l<this._ints;++l)r.putInt32(o.getInt32()^this._outBlock[l]);else{var c=(this.blockSize-a)%this.blockSize;c>0&&(c=this.blockSize-c),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialOutput.putInt32(o.getInt32()^this._outBlock[l]);if(c>0&&(o.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),c>0&&!A)return r.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=c,!0;r.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}n(this._inBlock)},e.ctr.prototype.decrypt=e.ctr.prototype.encrypt,e.gcm=function(o){o=o||{},this.name="GCM",this.cipher=o.cipher,this.blockSize=o.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=i.util.createBuffer(),this._partialBytes=0,this._R=3774873600},e.gcm.prototype.start=function(o){if(!("iv"in o))throw new Error("Invalid IV parameter.");var r=i.util.createBuffer(o.iv);this._cipherLength=0;var A;if("additionalData"in o?A=i.util.createBuffer(o.additionalData):A=i.util.createBuffer(),"tagLength"in o?this._tagLength=o.tagLength:this._tagLength=128,this._tag=null,o.decrypt&&(this._tag=i.util.createBuffer(o.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var a=r.length();if(a===12)this._j0=[r.getInt32(),r.getInt32(),r.getInt32(),1];else{for(this._j0=[0,0,0,0];r.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(s(a*8)))}this._inBlock=this._j0.slice(0),n(this._inBlock),this._partialBytes=0,A=i.util.createBuffer(A),this._aDataLength=s(A.length()*8);var l=A.length()%this.blockSize;for(l&&A.fillWithByte(0,this.blockSize-l),this._s=[0,0,0,0];A.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[A.getInt32(),A.getInt32(),A.getInt32(),A.getInt32()])},e.gcm.prototype.encrypt=function(o,r,A){var a=o.length();if(a===0)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),this._partialBytes===0&&a>=this.blockSize){for(var l=0;l<this._ints;++l)r.putInt32(this._outBlock[l]^=o.getInt32());this._cipherLength+=this.blockSize}else{var c=(this.blockSize-a)%this.blockSize;c>0&&(c=this.blockSize-c),this._partialOutput.clear();for(var l=0;l<this._ints;++l)this._partialOutput.putInt32(o.getInt32()^this._outBlock[l]);if(c<=0||A){if(A){var h=a%this.blockSize;this._cipherLength+=h,this._partialOutput.truncate(this.blockSize-h)}else this._cipherLength+=this.blockSize;for(var l=0;l<this._ints;++l)this._outBlock[l]=this._partialOutput.getInt32();this._partialOutput.read-=this.blockSize}if(this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),c>0&&!A)return o.read-=this.blockSize,r.putBytes(this._partialOutput.getBytes(c-this._partialBytes)),this._partialBytes=c,!0;r.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),n(this._inBlock)},e.gcm.prototype.decrypt=function(o,r,A){var a=o.length();if(a<this.blockSize&&!(A&&a>0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),n(this._inBlock),this._hashBlock[0]=o.getInt32(),this._hashBlock[1]=o.getInt32(),this._hashBlock[2]=o.getInt32(),this._hashBlock[3]=o.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var l=0;l<this._ints;++l)r.putInt32(this._outBlock[l]^this._hashBlock[l]);a<this.blockSize?this._cipherLength+=a%this.blockSize:this._cipherLength+=this.blockSize},e.gcm.prototype.afterFinish=function(o,r){var A=!0;r.decrypt&&r.overflow&&o.truncate(this.blockSize-r.overflow),this.tag=i.util.createBuffer();var a=this._aDataLength.concat(s(this._cipherLength*8));this._s=this.ghash(this._hashSubkey,this._s,a);var l=[];this.cipher.encrypt(this._j0,l);for(var c=0;c<this._ints;++c)this.tag.putInt32(this._s[c]^l[c]);return this.tag.truncate(this.tag.length()%(this._tagLength/8)),r.decrypt&&this.tag.bytes()!==this._tag&&(A=!1),A},e.gcm.prototype.multiply=function(o,r){for(var A=[0,0,0,0],a=r.slice(0),l=0;l<128;++l){var c=o[l/32|0]&1<<31-l%32;c&&(A[0]^=a[0],A[1]^=a[1],A[2]^=a[2],A[3]^=a[3]),this.pow(a,a)}return A},e.gcm.prototype.pow=function(o,r){for(var A=o[3]&1,a=3;a>0;--a)r[a]=o[a]>>>1|(o[a-1]&1)<<31;r[0]=o[0]>>>1,A&&(r[0]^=this._R)},e.gcm.prototype.tableMultiply=function(o){for(var r=[0,0,0,0],A=0;A<32;++A){var a=A/8|0,l=o[a]>>>(7-A%8)*4&15,c=this._m[A][l];r[0]^=c[0],r[1]^=c[1],r[2]^=c[2],r[3]^=c[3]}return r},e.gcm.prototype.ghash=function(o,r,A){return r[0]^=A[0],r[1]^=A[1],r[2]^=A[2],r[3]^=A[3],this.tableMultiply(r)},e.gcm.prototype.generateHashTable=function(o,r){for(var A=8/r,a=4*A,l=16*A,c=new Array(l),h=0;h<l;++h){var d=[0,0,0,0],g=h/a|0,u=(a-1-h%a)*r;d[g]=1<<r-1<<u,c[h]=this.generateSubHashTable(this.multiply(d,o),r)}return c},e.gcm.prototype.generateSubHashTable=function(o,r){var A=1<<r,a=A>>>1,l=new Array(A);l[a]=o.slice(0);for(var c=a>>>1;c>0;)this.pow(l[2*c],l[c]=[]),c>>=1;for(c=2;c<a;){for(var h=1;h<c;++h){var d=l[c],g=l[h];l[c+h]=[d[0]^g[0],d[1]^g[1],d[2]^g[2],d[3]^g[3]]}c*=2}for(l[0]=[0,0,0,0],c=a+1;c<A;++c){var u=l[c^a];l[c]=[o[0]^u[0],o[1]^u[1],o[2]^u[2],o[3]^u[3]]}return l};function t(o,r){if(typeof o=="string"&&(o=i.util.createBuffer(o)),i.util.isArray(o)&&o.length>4){var A=o;o=i.util.createBuffer();for(var a=0;a<A.length;++a)o.putByte(A[a])}if(o.length()<r)throw new Error("Invalid IV length; got "+o.length()+" bytes and expected "+r+" bytes.");if(!i.util.isArray(o)){for(var l=[],c=r/4,a=0;a<c;++a)l.push(o.getInt32());o=l}return o}function n(o){o[o.length-1]=o[o.length-1]+1&4294967295}function s(o){return[o/4294967296|0,o&4294967295]}return One.exports}var Lne,F_e;function DS(){if(F_e)return Lne;F_e=1;var i=ao();Wne(),__e(),Br(),Lne=i.aes=i.aes||{},i.aes.startEncrypting=function(g,u,p,m){var I=d({key:g,output:p,decrypt:!1,mode:m});return I.start(u),I},i.aes.createEncryptionCipher=function(g,u){return d({key:g,output:null,decrypt:!1,mode:u})},i.aes.startDecrypting=function(g,u,p,m){var I=d({key:g,output:p,decrypt:!0,mode:m});return I.start(u),I},i.aes.createDecryptionCipher=function(g,u){return d({key:g,output:null,decrypt:!0,mode:u})},i.aes.Algorithm=function(g,u){t||l();var p=this;p.name=g,p.mode=new u({blockSize:16,cipher:{encrypt:function(m,I){return h(p._w,m,I,!1)},decrypt:function(m,I){return h(p._w,m,I,!0)}}}),p._init=!1},i.aes.Algorithm.prototype.initialize=function(g){if(!this._init){var u=g.key,p;if(typeof u=="string"&&(u.length===16||u.length===24||u.length===32))u=i.util.createBuffer(u);else if(i.util.isArray(u)&&(u.length===16||u.length===24||u.length===32)){p=u,u=i.util.createBuffer();for(var m=0;m<p.length;++m)u.putByte(p[m])}if(!i.util.isArray(u)){p=u,u=[];var I=p.length();if(I===16||I===24||I===32){I=I>>>2;for(var m=0;m<I;++m)u.push(p.getInt32())}}if(!i.util.isArray(u)||!(u.length===4||u.length===6||u.length===8))throw new Error("Invalid key parameter.");var B=this.mode.name,y=["CFB","OFB","CTR","GCM"].indexOf(B)!==-1;this._w=c(u,g.decrypt&&!y),this._init=!0}},i.aes._expandKey=function(g,u){return t||l(),c(g,u)},i.aes._updateBlock=h,e("AES-ECB",i.cipher.modes.ecb),e("AES-CBC",i.cipher.modes.cbc),e("AES-CFB",i.cipher.modes.cfb),e("AES-OFB",i.cipher.modes.ofb),e("AES-CTR",i.cipher.modes.ctr),e("AES-GCM",i.cipher.modes.gcm);function e(g,u){var p=function(){return new i.aes.Algorithm(g,u)};i.cipher.registerAlgorithm(g,p)}var t=!1,n=4,s,o,r,A,a;function l(){t=!0,r=[0,1,2,4,8,16,32,64,128,27,54];for(var g=new Array(256),u=0;u<128;++u)g[u]=u<<1,g[u+128]=u+128<<1^283;s=new Array(256),o=new Array(256),A=new Array(4),a=new Array(4);for(var u=0;u<4;++u)A[u]=new Array(256),a[u]=new Array(256);for(var p=0,m=0,I,B,y,w,M,D,Q,u=0;u<256;++u){w=m^m<<1^m<<2^m<<3^m<<4,w=w>>8^w&255^99,s[p]=w,o[w]=p,M=g[w],I=g[p],B=g[I],y=g[B],D=M<<24^w<<16^w<<8^(w^M),Q=(I^B^y)<<24^(p^y)<<16^(p^B^y)<<8^(p^I^y);for(var b=0;b<4;++b)A[b][p]=D,a[b][w]=Q,D=D<<24|D>>>8,Q=Q<<24|Q>>>8;p===0?p=m=1:(p=I^g[g[g[I^y]]],m^=g[g[m]])}}function c(g,u){for(var p=g.slice(0),m,I=1,B=p.length,y=B+6+1,w=n*y,M=B;M<w;++M)m=p[M-1],M%B===0?(m=s[m>>>16&255]<<24^s[m>>>8&255]<<16^s[m&255]<<8^s[m>>>24]^r[I]<<24,I++):B>6&&M%B===4&&(m=s[m>>>24]<<24^s[m>>>16&255]<<16^s[m>>>8&255]<<8^s[m&255]),p[M]=p[M-B]^m;if(u){var D,Q=a[0],b=a[1],P=a[2],F=a[3],T=p.slice(0);w=p.length;for(var M=0,x=w-n;M<w;M+=n,x-=n)if(M===0||M===w-n)T[M]=p[x],T[M+1]=p[x+3],T[M+2]=p[x+2],T[M+3]=p[x+1];else for(var C=0;C<n;++C)D=p[x+C],T[M+(3&-C)]=Q[s[D>>>24]]^b[s[D>>>16&255]]^P[s[D>>>8&255]]^F[s[D&255]];p=T}return p}function h(g,u,p,m){var I=g.length/4-1,B,y,w,M,D;m?(B=a[0],y=a[1],w=a[2],M=a[3],D=o):(B=A[0],y=A[1],w=A[2],M=A[3],D=s);var Q,b,P,F,T,x,C;Q=u[0]^g[0],b=u[m?3:1]^g[1],P=u[2]^g[2],F=u[m?1:3]^g[3];for(var S=3,v=1;v<I;++v)T=B[Q>>>24]^y[b>>>16&255]^w[P>>>8&255]^M[F&255]^g[++S],x=B[b>>>24]^y[P>>>16&255]^w[F>>>8&255]^M[Q&255]^g[++S],C=B[P>>>24]^y[F>>>16&255]^w[Q>>>8&255]^M[b&255]^g[++S],F=B[F>>>24]^y[Q>>>16&255]^w[b>>>8&255]^M[P&255]^g[++S],Q=T,b=x,P=C;p[0]=D[Q>>>24]<<24^D[b>>>16&255]<<16^D[P>>>8&255]<<8^D[F&255]^g[++S],p[m?3:1]=D[b>>>24]<<24^D[P>>>16&255]<<16^D[F>>>8&255]<<8^D[Q&255]^g[++S],p[2]=D[P>>>24]<<24^D[F>>>16&255]<<16^D[Q>>>8&255]<<8^D[b&255]^g[++S],p[m?1:3]=D[F>>>24]<<24^D[Q>>>16&255]<<16^D[b>>>8&255]<<8^D[P&255]^g[++S]}function d(g){g=g||{};var u=(g.mode||"CBC").toUpperCase(),p="AES-"+u,m;g.decrypt?m=i.cipher.createDecipher(p,g.key):m=i.cipher.createCipher(p,g.key);var I=m.start;return m.start=function(B,y){var w=null;y instanceof i.util.ByteBuffer&&(w=y,y={}),y=y||{},y.output=w,y.iv=B,I.call(m,y)},m}return Lne}var Kne={exports:{}},Xne={exports:{}},Vne={exports:{}},v_e;function SS(){if(v_e)return Vne.exports;v_e=1;var i=ao();i.pki=i.pki||{};var e=Vne.exports=i.pki.oids=i.oids=i.oids||{};function t(s,o){e[s]=o,e[o]=s}function n(s,o){e[s]=o}return t("1.2.840.113549.1.1.1","rsaEncryption"),t("1.2.840.113549.1.1.4","md5WithRSAEncryption"),t("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),t("1.2.840.113549.1.1.7","RSAES-OAEP"),t("1.2.840.113549.1.1.8","mgf1"),t("1.2.840.113549.1.1.9","pSpecified"),t("1.2.840.113549.1.1.10","RSASSA-PSS"),t("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),t("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),t("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),t("1.3.101.112","EdDSA25519"),t("1.2.840.10040.4.3","dsa-with-sha1"),t("1.3.14.3.2.7","desCBC"),t("1.3.14.3.2.26","sha1"),t("1.3.14.3.2.29","sha1WithRSASignature"),t("2.16.840.1.101.3.4.2.1","sha256"),t("2.16.840.1.101.3.4.2.2","sha384"),t("2.16.840.1.101.3.4.2.3","sha512"),t("2.16.840.1.101.3.4.2.4","sha224"),t("2.16.840.1.101.3.4.2.5","sha512-224"),t("2.16.840.1.101.3.4.2.6","sha512-256"),t("1.2.840.113549.2.2","md2"),t("1.2.840.113549.2.5","md5"),t("1.2.840.113549.1.7.1","data"),t("1.2.840.113549.1.7.2","signedData"),t("1.2.840.113549.1.7.3","envelopedData"),t("1.2.840.113549.1.7.4","signedAndEnvelopedData"),t("1.2.840.113549.1.7.5","digestedData"),t("1.2.840.113549.1.7.6","encryptedData"),t("1.2.840.113549.1.9.1","emailAddress"),t("1.2.840.113549.1.9.2","unstructuredName"),t("1.2.840.113549.1.9.3","contentType"),t("1.2.840.113549.1.9.4","messageDigest"),t("1.2.840.113549.1.9.5","signingTime"),t("1.2.840.113549.1.9.6","counterSignature"),t("1.2.840.113549.1.9.7","challengePassword"),t("1.2.840.113549.1.9.8","unstructuredAddress"),t("1.2.840.113549.1.9.14","extensionRequest"),t("1.2.840.113549.1.9.20","friendlyName"),t("1.2.840.113549.1.9.21","localKeyId"),t("1.2.840.113549.1.9.22.1","x509Certificate"),t("1.2.840.113549.1.12.10.1.1","keyBag"),t("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),t("1.2.840.113549.1.12.10.1.3","certBag"),t("1.2.840.113549.1.12.10.1.4","crlBag"),t("1.2.840.113549.1.12.10.1.5","secretBag"),t("1.2.840.113549.1.12.10.1.6","safeContentsBag"),t("1.2.840.113549.1.5.13","pkcs5PBES2"),t("1.2.840.113549.1.5.12","pkcs5PBKDF2"),t("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),t("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),t("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),t("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),t("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),t("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),t("1.2.840.113549.2.7","hmacWithSHA1"),t("1.2.840.113549.2.8","hmacWithSHA224"),t("1.2.840.113549.2.9","hmacWithSHA256"),t("1.2.840.113549.2.10","hmacWithSHA384"),t("1.2.840.113549.2.11","hmacWithSHA512"),t("1.2.840.113549.3.7","des-EDE3-CBC"),t("2.16.840.1.101.3.4.1.2","aes128-CBC"),t("2.16.840.1.101.3.4.1.22","aes192-CBC"),t("2.16.840.1.101.3.4.1.42","aes256-CBC"),t("2.5.4.3","commonName"),t("2.5.4.4","surname"),t("2.5.4.5","serialNumber"),t("2.5.4.6","countryName"),t("2.5.4.7","localityName"),t("2.5.4.8","stateOrProvinceName"),t("2.5.4.9","streetAddress"),t("2.5.4.10","organizationName"),t("2.5.4.11","organizationalUnitName"),t("2.5.4.12","title"),t("2.5.4.13","description"),t("2.5.4.15","businessCategory"),t("2.5.4.17","postalCode"),t("2.5.4.42","givenName"),t("2.5.4.65","pseudonym"),t("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),t("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),t("2.16.840.1.113730.1.1","nsCertType"),t("2.16.840.1.113730.1.13","nsComment"),n("2.5.29.1","authorityKeyIdentifier"),n("2.5.29.2","keyAttributes"),n("2.5.29.3","certificatePolicies"),n("2.5.29.4","keyUsageRestriction"),n("2.5.29.5","policyMapping"),n("2.5.29.6","subtreesConstraint"),n("2.5.29.7","subjectAltName"),n("2.5.29.8","issuerAltName"),n("2.5.29.9","subjectDirectoryAttributes"),n("2.5.29.10","basicConstraints"),n("2.5.29.11","nameConstraints"),n("2.5.29.12","policyConstraints"),n("2.5.29.13","basicConstraints"),t("2.5.29.14","subjectKeyIdentifier"),t("2.5.29.15","keyUsage"),n("2.5.29.16","privateKeyUsagePeriod"),t("2.5.29.17","subjectAltName"),t("2.5.29.18","issuerAltName"),t("2.5.29.19","basicConstraints"),n("2.5.29.20","cRLNumber"),n("2.5.29.21","cRLReason"),n("2.5.29.22","expirationDate"),n("2.5.29.23","instructionCode"),n("2.5.29.24","invalidityDate"),n("2.5.29.25","cRLDistributionPoints"),n("2.5.29.26","issuingDistributionPoint"),n("2.5.29.27","deltaCRLIndicator"),n("2.5.29.28","issuingDistributionPoint"),n("2.5.29.29","certificateIssuer"),n("2.5.29.30","nameConstraints"),t("2.5.29.31","cRLDistributionPoints"),t("2.5.29.32","certificatePolicies"),n("2.5.29.33","policyMappings"),n("2.5.29.34","policyConstraints"),t("2.5.29.35","authorityKeyIdentifier"),n("2.5.29.36","policyConstraints"),t("2.5.29.37","extKeyUsage"),n("2.5.29.46","freshestCRL"),n("2.5.29.54","inhibitAnyPolicy"),t("1.3.6.1.4.1.11129.2.4.2","timestampList"),t("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),t("1.3.6.1.5.5.7.3.1","serverAuth"),t("1.3.6.1.5.5.7.3.2","clientAuth"),t("1.3.6.1.5.5.7.3.3","codeSigning"),t("1.3.6.1.5.5.7.3.4","emailProtection"),t("1.3.6.1.5.5.7.3.8","timeStamping"),Vne.exports}var R_e;function xC(){if(R_e)return Xne.exports;R_e=1;var i=ao();Br(),SS();var e=Xne.exports=i.asn1=i.asn1||{};e.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},e.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},e.maxDepth=256,e.create=function(r,A,a,l,c){if(i.util.isArray(l)){for(var h=[],d=0;d<l.length;++d)l[d]!==void 0&&h.push(l[d]);l=h}var g={tagClass:r,type:A,constructed:a,composed:a||i.util.isArray(l),value:l};return c&&"bitStringContents"in c&&(g.bitStringContents=c.bitStringContents,g.original=e.copy(g)),g},e.copy=function(r,A){var a;if(i.util.isArray(r)){a=[];for(var l=0;l<r.length;++l)a.push(e.copy(r[l],A));return a}return typeof r=="string"?r:(a={tagClass:r.tagClass,type:r.type,constructed:r.constructed,composed:r.composed,value:e.copy(r.value,A)},A&&!A.excludeBitStringContents&&(a.bitStringContents=r.bitStringContents),a)},e.equals=function(r,A,a){if(i.util.isArray(r)){if(!i.util.isArray(A)||r.length!==A.length)return!1;for(var l=0;l<r.length;++l)if(!e.equals(r[l],A[l]))return!1;return!0}if(typeof r!=typeof A)return!1;if(typeof r=="string")return r===A;var c=r.tagClass===A.tagClass&&r.type===A.type&&r.constructed===A.constructed&&r.composed===A.composed&&e.equals(r.value,A.value);return a&&a.includeBitStringContents&&(c=c&&r.bitStringContents===A.bitStringContents),c},e.getBerValueLength=function(r){var A=r.getByte();if(A!==128){var a,l=A&128;return l?a=r.getInt((A&127)<<3):a=A,a}};function t(r,A,a){if(a>A){var l=new Error("Too few bytes to parse DER.");throw l.available=r.length(),l.remaining=A,l.requested=a,l}}var n=function(r,A){var a=r.getByte();if(A--,a!==128){var l,c=a&128;if(!c)l=a;else{var h=a&127;t(r,A,h),l=r.getInt(h<<3)}if(l<0)throw new Error("Negative length: "+l);return l}};e.fromDer=function(r,A){A===void 0&&(A={strict:!0,parseAllBytes:!0,decodeBitStrings:!0}),typeof A=="boolean"&&(A={strict:A,parseAllBytes:!0,decodeBitStrings:!0}),"strict"in A||(A.strict=!0),"parseAllBytes"in A||(A.parseAllBytes=!0),"decodeBitStrings"in A||(A.decodeBitStrings=!0),"maxDepth"in A||(A.maxDepth=e.maxDepth),typeof r=="string"&&(r=i.util.createBuffer(r));var a=r.length(),l=s(r,r.length(),0,A);if(A.parseAllBytes&&r.length()!==0){var c=new Error("Unparsed DER bytes remain after ASN.1 parsing.");throw c.byteCount=a,c.remaining=r.length(),c}return l};function s(r,A,a,l){if(a>=l.maxDepth)throw new Error("ASN.1 parsing error: Max depth exceeded.");var c;t(r,A,2);var h=r.getByte();A--;var d=h&192,g=h&31;c=r.length();var u=n(r,A);if(A-=c-r.length(),u!==void 0&&u>A){if(l.strict){var p=new Error("Too few bytes to read ASN.1 value.");throw p.available=r.length(),p.remaining=A,p.requested=u,p}u=A}var m,I,B=(h&32)===32;if(B)if(m=[],u===void 0)for(;;){if(t(r,A,2),r.bytes(2)==="\0\0"){r.getBytes(2),A-=2;break}c=r.length(),m.push(s(r,A,a+1,l)),A-=c-r.length()}else for(;u>0;)c=r.length(),m.push(s(r,u,a+1,l)),A-=c-r.length(),u-=c-r.length();if(m===void 0&&d===e.Class.UNIVERSAL&&g===e.Type.BITSTRING&&(I=r.bytes(u)),m===void 0&&l.decodeBitStrings&&d===e.Class.UNIVERSAL&&g===e.Type.BITSTRING&&u>1){var y=r.read,w=A,M=0;if(g===e.Type.BITSTRING&&(t(r,A,1),M=r.getByte(),A--),M===0)try{c=r.length();var D={strict:!0,decodeBitStrings:!0},Q=s(r,A,a+1,D),b=c-r.length();A-=b,g==e.Type.BITSTRING&&b++;var P=Q.tagClass;b===u&&(P===e.Class.UNIVERSAL||P===e.Class.CONTEXT_SPECIFIC)&&(m=[Q])}catch{}m===void 0&&(r.read=y,A=w)}if(m===void 0){if(u===void 0){if(l.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");u=A}if(g===e.Type.BMPSTRING)for(m="";u>0;u-=2)t(r,A,2),m+=String.fromCharCode(r.getInt16()),A-=2;else m=r.getBytes(u),A-=u}var F=I===void 0?null:{bitStringContents:I};return e.create(d,g,B,m,F)}e.toDer=function(r){var A=i.util.createBuffer(),a=r.tagClass|r.type,l=i.util.createBuffer(),c=!1;if("bitStringContents"in r&&(c=!0,r.original&&(c=e.equals(r,r.original))),c)l.putBytes(r.bitStringContents);else if(r.composed){r.constructed?a|=32:l.putByte(0);for(var h=0;h<r.value.length;++h)r.value[h]!==void 0&&l.putBuffer(e.toDer(r.value[h]))}else if(r.type===e.Type.BMPSTRING)for(var h=0;h<r.value.length;++h)l.putInt16(r.value.charCodeAt(h));else r.type===e.Type.INTEGER&&r.value.length>1&&(r.value.charCodeAt(0)===0&&(r.value.charCodeAt(1)&128)===0||r.value.charCodeAt(0)===255&&(r.value.charCodeAt(1)&128)===128)?l.putBytes(r.value.substr(1)):l.putBytes(r.value);if(A.putByte(a),l.length()<=127)A.putByte(l.length()&127);else{var d=l.length(),g="";do g+=String.fromCharCode(d&255),d=d>>>8;while(d>0);A.putByte(g.length|128);for(var h=g.length-1;h>=0;--h)A.putByte(g.charCodeAt(h))}return A.putBuffer(l),A},e.oidToDer=function(r){var A=r.split("."),a=i.util.createBuffer();a.putByte(40*parseInt(A[0],10)+parseInt(A[1],10));for(var l,c,h,d,g=2;g<A.length;++g){if(l=!0,c=[],h=parseInt(A[g],10),h>4294967295)throw new Error("OID value too large; max is 32-bits.");do d=h&127,h=h>>>7,l||(d|=128),c.push(d),l=!1;while(h>0);for(var u=c.length-1;u>=0;--u)a.putByte(c[u])}return a},e.derToOid=function(r){var A;typeof r=="string"&&(r=i.util.createBuffer(r));var a=r.getByte();A=Math.floor(a/40)+"."+a%40;for(var l=0;r.length()>0;){if(l>70368744177663)throw new Error("OID value too large; max is 53-bits.");a=r.getByte(),l=l*128,a&128?l+=a&127:(A+="."+(l+a),l=0)}return A},e.utcTimeToDate=function(r){var A=new Date,a=parseInt(r.substr(0,2),10);a=a>=50?1900+a:2e3+a;var l=parseInt(r.substr(2,2),10)-1,c=parseInt(r.substr(4,2),10),h=parseInt(r.substr(6,2),10),d=parseInt(r.substr(8,2),10),g=0;if(r.length>11){var u=r.charAt(10),p=10;u!=="+"&&u!=="-"&&(g=parseInt(r.substr(10,2),10),p+=2)}if(A.setUTCFullYear(a,l,c),A.setUTCHours(h,d,g,0),p&&(u=r.charAt(p),u==="+"||u==="-")){var m=parseInt(r.substr(p+1,2),10),I=parseInt(r.substr(p+4,2),10),B=m*60+I;B*=6e4,u==="+"?A.setTime(+A-B):A.setTime(+A+B)}return A},e.generalizedTimeToDate=function(r){var A=new Date,a=parseInt(r.substr(0,4),10),l=parseInt(r.substr(4,2),10)-1,c=parseInt(r.substr(6,2),10),h=parseInt(r.substr(8,2),10),d=parseInt(r.substr(10,2),10),g=parseInt(r.substr(12,2),10),u=0,p=0,m=!1;r.charAt(r.length-1)==="Z"&&(m=!0);var I=r.length-5,B=r.charAt(I);if(B==="+"||B==="-"){var y=parseInt(r.substr(I+1,2),10),w=parseInt(r.substr(I+4,2),10);p=y*60+w,p*=6e4,B==="+"&&(p*=-1),m=!0}return r.charAt(14)==="."&&(u=parseFloat(r.substr(14),10)*1e3),m?(A.setUTCFullYear(a,l,c),A.setUTCHours(h,d,g,u),A.setTime(+A+p)):(A.setFullYear(a,l,c),A.setHours(h,d,g,u)),A},e.dateToUtcTime=function(r){if(typeof r=="string")return r;var A="",a=[];a.push((""+r.getUTCFullYear()).substr(2)),a.push(""+(r.getUTCMonth()+1)),a.push(""+r.getUTCDate()),a.push(""+r.getUTCHours()),a.push(""+r.getUTCMinutes()),a.push(""+r.getUTCSeconds());for(var l=0;l<a.length;++l)a[l].length<2&&(A+="0"),A+=a[l];return A+="Z",A},e.dateToGeneralizedTime=function(r){if(typeof r=="string")return r;var A="",a=[];a.push(""+r.getUTCFullYear()),a.push(""+(r.getUTCMonth()+1)),a.push(""+r.getUTCDate()),a.push(""+r.getUTCHours()),a.push(""+r.getUTCMinutes()),a.push(""+r.getUTCSeconds());for(var l=0;l<a.length;++l)a[l].length<2&&(A+="0"),A+=a[l];return A+="Z",A},e.integerToDer=function(r){var A=i.util.createBuffer();if(r>=-128&&r<128)return A.putSignedInt(r,8);if(r>=-32768&&r<32768)return A.putSignedInt(r,16);if(r>=-8388608&&r<8388608)return A.putSignedInt(r,24);if(r>=-2147483648&&r<2147483648)return A.putSignedInt(r,32);var a=new Error("Integer too large; max is 32-bits.");throw a.integer=r,a},e.derToInteger=function(r){typeof r=="string"&&(r=i.util.createBuffer(r));var A=r.length()*8;if(A>32)throw new Error("Integer too large; max is 32-bits.");return r.getSignedInt(A)},e.validate=function(r,A,a,l){var c=!1;if((r.tagClass===A.tagClass||typeof A.tagClass>"u")&&(r.type===A.type||typeof A.type>"u"))if(r.constructed===A.constructed||typeof A.constructed>"u"){if(c=!0,A.value&&i.util.isArray(A.value))for(var h=0,d=0;c&&d<A.value.length;++d){var g=A.value[d];c=!!g.optional;var u=r.value[h];if(!u){g.optional||(c=!1,l&&l.push("["+A.name+'] Missing required element. Expected tag class "'+g.tagClass+'", type "'+g.type+'"'));continue}var p=typeof g.tagClass<"u"&&typeof g.type<"u";if(p&&(u.tagClass!==g.tagClass||u.type!==g.type))if(g.optional){c=!0;continue}else{c=!1,l&&l.push("["+A.name+"] Tag mismatch. Expected ("+g.tagClass+","+g.type+"), got ("+u.tagClass+","+u.type+")");break}var m=e.validate(u,g,a,l);if(m)++h,c=!0;else if(g.optional)c=!0;else{c=!1;break}}if(c&&a&&(A.capture&&(a[A.capture]=r.value),A.captureAsn1&&(a[A.captureAsn1]=r),A.captureBitStringContents&&"bitStringContents"in r&&(a[A.captureBitStringContents]=r.bitStringContents),A.captureBitStringValue&&"bitStringContents"in r))if(r.bitStringContents.length<2)a[A.captureBitStringValue]="";else{var I=r.bitStringContents.charCodeAt(0);if(I!==0)throw new Error("captureBitStringValue only supported for zero unused bits");a[A.captureBitStringValue]=r.bitStringContents.slice(1)}}else l&&l.push("["+A.name+'] Expected constructed "'+A.constructed+'", got "'+r.constructed+'"');else l&&(r.tagClass!==A.tagClass&&l.push("["+A.name+'] Expected tag class "'+A.tagClass+'", got "'+r.tagClass+'"'),r.type!==A.type&&l.push("["+A.name+'] Expected type "'+A.type+'", got "'+r.type+'"'));return c};var o=/[^\\u0000-\\u00ff]/;return e.prettyPrint=function(r,A,a){var l="";A=A||0,a=a||2,A>0&&(l+=`
@@ -5977,7 +5977,7 @@ void main() {
5977
5977
  Private-Lines: `+g+`\r
5978
5978
  `,c+=p;var M=s("putty-private-key-file-mac-key",r),D=i.util.createBuffer();n(D,a),n(D,l),n(D,A),D.putInt32(h.length()),D.putBuffer(h),D.putInt32(u.length()),D.putBuffer(u);var Q=i.hmac.create();return Q.start("sha1",M),Q.update(D.bytes()),c+=`\r
5979
5979
  Private-MAC: `+Q.digest().toHex()+`\r
5980
- `,c},e.publicKeyToOpenSSH=function(o,r){var A="ssh-rsa";r=r||"";var a=i.util.createBuffer();return n(a,A),t(a,o.e),t(a,o.n),A+" "+i.util.encode64(a.bytes())+" "+r},e.privateKeyToOpenSSH=function(o,r){return r?i.pki.encryptRsaPrivateKey(o,r,{legacy:!0,algorithm:"aes128"}):i.pki.privateKeyToPem(o)},e.getPublicKeyFingerprint=function(o,r){r=r||{};var A=r.md||i.md.md5.create(),a="ssh-rsa",l=i.util.createBuffer();n(l,a),t(l,o.e),t(l,o.n),A.start(),A.update(l.getBytes());var c=A.digest();if(r.encoding==="hex"){var h=c.toHex();return r.delimiter?h.match(/.{2}/g).join(r.delimiter):h}else{if(r.encoding==="binary")return c.getBytes();if(r.encoding)throw new Error('Unknown encoding "'+r.encoding+'".')}return c};function t(o,r){var A=r.toString(16);A[0]>="8"&&(A="00"+A);var a=i.util.hexToBytes(A);o.putInt32(a.length),o.putBytes(a)}function n(o,r){o.putInt32(r.length),o.putString(r)}function s(){for(var o=i.md.sha1.create(),r=arguments.length,A=0;A<r;++A)o.update(arguments[A]);return o.digest()}return Dse.exports}var Sse,D2e;function hvt(){return D2e||(D2e=1,Sse=ao(),DS(),nvt(),xC(),Wne(),GX(),ovt(),vY(),rvt(),Avt(),avt(),A2e(),nse(),p_(),q_e(),d2e(),lvt(),u2e(),e2e(),K_e(),mse(),bI(),Z_e(),cvt(),p2e(),Br()),Sse}var xse=hvt();const dvt="evtrsa1",Tse=new Map;function S2e(i){return i.replace(/\/+$/,"")}function gvt(i){return new TextEncoder().encode(i)}function LX(i){let e="";return i.forEach(t=>{e+=String.fromCharCode(t)}),btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function uvt(i,e){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),e):void 0;try{const s=await fetch(i,{method:"GET",headers:{Accept:"application/json"},signal:t?.signal}),o=await s.json().catch(()=>({}));if(!s.ok){const r=o?.error?.message??o?.message??`ViewToken public key request failed with status ${s.status}`;throw new Error(r)}return o}finally{n!=null&&clearTimeout(n)}}function Pse(i){const e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("[BimEngine] crypto.getRandomValues is required to encrypt viewToken");return e.getRandomValues(new Uint8Array(i))}function fvt(i){let e="";return i.forEach(t=>{e+=String.fromCharCode(t)}),e}function pvt(i){const e=new Uint8Array(i.length);for(let t=0;t<i.length;t+=1)e[t]=i.charCodeAt(t)&255;return e}async function Ivt(i,e){const t=`${S2e(i)}/models/view-token/public-key`,n=await uvt(t,e);if(n.algorithm!=="RSA-OAEP-256"||!n.publicKey)throw new Error("[BimEngine] OpenAPI returned an invalid viewToken public key");return xse.pki.publicKeyFromPem(n.publicKey)}function mvt(i,e){const t=S2e(i),n=Tse.get(t);if(n)return n;const s=Ivt(i,e).catch(o=>{throw Tse.delete(t),o});return Tse.set(t,s),s}async function Cvt(i,e,t){const n=await mvt(i,t),s=Pse(32),o=Pse(12),r=Pse(16),A=JSON.stringify({viewToken:e,timestamp:Date.now(),nonce:LX(r)}),a=n.encrypt(fvt(s),"RSA-OAEP",{md:xse.md.sha256.create(),mgf1:{md:xse.md.sha256.create()}}),l=U4(s,o).encrypt(gvt(A));return[dvt,LX(pvt(a)),LX(o),LX(l)].join(".")}function Evt(i){return i.replace(/\/+$/,"")}async function Bvt(i,e,t){const n=typeof AbortController<"u"?new AbortController:void 0,s=n?setTimeout(()=>n.abort(),t):void 0;try{const o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:n?.signal}),r=await o.json().catch(()=>({}));if(!o.ok){const A=r?.error?.message??r?.message??`ViewToken resolve failed with status ${o.status}`;throw new Error(A)}return r}finally{s!=null&&clearTimeout(s)}}function yvt(i){switch(i){case"2d":return"cad_model";case"720":return"panorama";case"gis":return"gis_scene";case"gaussian":return"gaussian_model";case"3d":default:return"model"}}function wvt(i){return{models:[{modelType:i.toLowerCase().endsWith(".json")?"3dtiles":"glb",url:i}]}}function bvt(i,e){return{applicationId:0,engineType:e,assetCategory:yvt(e),url:i,urls:[i],info:e==="gis"?wvt(i):void 0}}async function I_(i,e,t){const n=i?.sdkAuth;if(!n?.endpoint)return bvt(e,t);let s;(n.token||n.appId&&n.appKey&&n.appSecret)&&(s=(await evt(i,t))?.sdkToken);const r={viewToken:await Cvt(n.endpoint,e,n.timeoutMs??8e3),engineType:t};return s&&(r.sdkToken=s),Bvt(`${Evt(n.endpoint)}/models/view-token/resolve`,r,n.timeoutMs??8e3)}function Qvt(i){const e=i.postProcessing??{},t=n=>n===!0||n!=null&&typeof n=="object"&&n.enabled===!0?n:!1;i.postProcessing={...e,vxgi:t(e.vxgi),ssgi:t(e.ssgi),traa:t(e.traa),ssr:t(e.ssr),bloom:t(e.bloom),gtao:t(e.gtao),colorGrading:{colorTemperature:6500,saturation:1,contrast:1,sharpen:0,...e.colorGrading??{}}}}class Mvt{version=SC;options;container;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;handelBehaved;viewCube;octreeBox;controls;worldToScreen;modelProperties;hoverHighLight;autoExposureModule;rxQuotaListMapper;filterLoaderModel;engineModelModule;viewTree;merge2d;rangeScale;setting;measure;modelTree;engineInfo;search;modelMapperBatch;modelEdge;nodeBox;pathRoaming;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;fabricDraw;drawingPin;modelLink3d;label;annotation3d;calibration;modelPlace;modelComparison;materialTool;pathDraw;clipping;collector;modelEditor;modelQuantityList;roomSpace;materialReplacement;stats;models=[];reactBoundingClientRect={left:0,top:0};catchSvg;sectionPlane=[];ready;modelExplode;isDisposed=!1;isRenderingPaused=!1;pendingComposerRender=!0;frameLockEnabled=!0;idleFrameInterval=1e3;lastIdleFrameTime=0;idleFrameRateExemptionReasons=new Set;temporalRenderingRequired=!1;controlsEnabledBeforePause=!0;boundControl=null;controlEventHandlers=null;resizeObserver;renderStatsEl=null;renderTrianglesValueEl=null;renderDrawCallsValueEl=null;versionEl=null;constructor(e){window.THREE=uD,ebt(),this.options=e,this.container=this.resolveContainer(e),this.rxQuotaListMapper=new vQt(this),this.filterLoaderModel=new mQt(this),this.deviceModule=new DEt(this),this.deviceModule.isMobile()&&Qvt(this.options),this.cameraModule=new YCt(this),this.sceneModule=new IQt(this),this.scene=this.sceneModule.scene,this.renderModule=new pQt(this),this.renderer=this.renderModule.createRenderer(),this.autoExposureModule=new yCt(this),this.camera=this.cameraModule.perspectiveCamera,this.scene.camera=this.camera;const t=this.renderer;t.interactionCullingEnabled=!0,t.interactionActive=!1,t.interactionRenderScene=this.scene,t.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,t.interactionSkipShadows=this.options.interactionSkipShadows??!0,this.controlModule=new MEt(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.composerModule=new ECt(this),this.composerModule.init(),this.engineModelModule=new jQt(this),this.clipping=new MMt(this),this.clipping.init(),this.events=new SEt;const n=this.events.trigger.bind(this.events);this.events.trigger=((s,o)=>{n(s,o),String(s)!==String(Qs.EngineBusy)&&this.requestComposerRender(),this.updateTemporalFrameRateExemption()}),this.engineStatus=new CQt(this),this.engineStatus.init(),this.updateTemporalFrameRateExemption(),this.materialReplacement=new jbe(this,this.options.materialReplacementOptions),this.materialReplacement.init(),this.loaderModule=new zbt(this),this.lightModule=new PEt(this),this.lightModule.init(),this.engineModelModule.init(),this.initializeVersionDisplay(),this.viewCube=new PQt(this),this.viewCube.init(),this.options.showViewCube===!1&&this.viewCube.hide(),this.octreeBox=_Qt(this),this.handelBehaved=Tee(this),this.modelToolModule=new AQt(this),this.modelProperties=new FQt(this),this.rangeScale=new UQt(this),this.rangeScale.init(),this.setting=new cMt(this),this.modelMapperBatch=new _Mt(this),this.measure=new EMt(this),this.modelLink3d=new G2t(this,this.options.linkOptions??{}),this.modelLink3d.init(),this.search=new PMt(this),this.modelEdge=new rMt(this),this.events.on(Qs.LoadingCompleted,()=>{this.modelEdge.active(),this.composerModule.markSceneDirty()}),this.nodeBox=new RMt(this),this.modelTree=new DMt(this),this.viewTree=new nDt(this),this.merge2d=new WPt(this),this.engineInfo=new SMt(this),this.pathRoaming=new jMt(this),this.pathRoaming.init(),this.oneClickEncoding=new KMt(this),this.minMap=new UMt(this),this.linkElement2d3d=new OMt(this),this.linkView2d3d=new LMt(this),this.grid=new OQt(this),this.level=new zQt(this),this.issueReport=new kMt(this),this.fabricDraw=new R2t(this),this.drawingPin=new N2t(this),this.label=new j2t(this),this.annotation3d=new BFt(this),this.calibration=new yFt(this),this.modelPlace=new MFt(this),this.modelComparison=new DFt(this),this.modelExplode=new SFt(this),this.materialTool=new vFt(this,this.options.materialEditorOptions??{}),this.materialTool.init(),this.pathDraw=new UFt(this),this.collector=new kFt(this),this.modelEditor=new WFt(this),this.modelQuantityList=new OFt(this),this.roomSpace=new LFt(this),this.text=new WMt(this),this.hdr=new VQt(this),this.ground=new LQt(this),this.ground.init(),this.skyManager=new lMt(this),this.setting.init(),this.interactionModule=new _Et(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new KFt(this),this.worldToScreen=new po(this.camera,this.renderer,this.scene),this.catchSvg=this.createCatchSvg(),this.initializeStats(),this.bindControlEvents(this.controls),this.resizeObserver=typeof ResizeObserver>"u"?null:new ResizeObserver(s=>{const o=s[0];o&&this.handleWindowResize(o.contentRect.width,o.contentRect.height)}),this.resizeObserver?.observe(this.container),this.ready=this.initialize().catch(s=>{throw this.dispose(),s})}updateVersionDisplay(){if(this.versionEl==null)return;const e=this.engineModelModule?.getQualityLevel?.()??"";this.versionEl.textContent=`v${this.version} | ${e}`}initializeVersionDisplay(){if(this.versionEl!=null)return;const e=document.createElement("div");e.className="versionText",this.versionEl=e,this.updateVersionDisplay(),this.container.appendChild(e)}bindControlEvents(e){if(this.boundControl===e||(this.boundControl?.removeEventListener&&this.controlEventHandlers&&(this.boundControl.removeEventListener("start",this.controlEventHandlers.start),this.boundControl.removeEventListener("end",this.controlEventHandlers.end),this.boundControl.removeEventListener("change",this.controlEventHandlers.change)),this.boundControl=e,this.controlEventHandlers=null,!e?.addEventListener))return;const t=()=>{this.renderer.interactionActive=!0,this.events.trigger(Qs.EngineBusy),this.container.style.cursor="none"},n=()=>{this.renderer.interactionActive=!1,this.events.trigger(Qs.EngineFree),this.container.style.cursor="default"},s=()=>{this.requestComposerRender(),this.modelEdge?.update?.();const o=new N;this.camera.getWorldDirection(o),window.dispatchEvent(new CustomEvent("D3ViewUpdate",{detail:{position:this.camera.position,rotation:Math.atan2(o.x,-o.z),type:this.camera.type}}))};e.addEventListener("start",t),e.addEventListener("end",n),e.addEventListener("change",s),this.controlEventHandlers={start:t,end:n,change:s}}requestComposerRender(){this.pendingComposerRender=!0}requestRender(){this.requestComposerRender()}async loadModelByViewToken(e,t){const n=await I_(this.options,e,"3d"),s=Array.isArray(n.urls)&&n.urls.length>0?n.urls:[n.url];await this.loaderModule.loadModels(s,t)}requestShadowUpdate(){this.lightModule?.requestShadowUpdate?.(),this.requestComposerRender()}setFrameLock(e){this.frameLockEnabled=e,this.lastIdleFrameTime=0,this.requestComposerRender()}isFrameLockEnabled(){return this.frameLockEnabled}setTemporalRenderingRequired(e){this.temporalRenderingRequired=e,this.updateTemporalFrameRateExemption()}setIdleFrameRateExempt(e,t){if(e){if(t){this.idleFrameRateExemptionReasons.add(e),this.requestComposerRender();return}this.idleFrameRateExemptionReasons.delete(e)}}updateTemporalFrameRateExemption(){this.setIdleFrameRateExempt("webgpu-temporal-post-processing",this.temporalRenderingRequired&&this.engineStatus?.isFree===!1)}pauseRendering(){this.isRenderingPaused||(this.isRenderingPaused=!0,this.controlsEnabledBeforePause=this.controls?.enabled!==!1,this.controls&&(this.controls.enabled=!1))}resumeRendering(){this.isRenderingPaused&&(this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.requestComposerRender())}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(this.isDisposed)return;const n=this.container.getBoundingClientRect(),s=Math.max(1,Math.round(n.width||e||this.container.clientWidth)),o=Math.max(1,Math.round(n.height||t||this.container.clientHeight)),r=this.camera.position.clone(),A=this.camera.quaternion.clone(),a=this.camera.up.clone(),l=this.controls?.target?.clone?.(),c=this.controlModule.orbitControls?.origin?.clone?.();this.renderer.setPixelRatio(bSe(this)),this.renderer.setSize(s,o,!1);const h=s/o;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=h,this.cameraModule.perspectiveCamera.updateProjectionMatrix();else{const d=this.cameraModule.getOrthographicVisibleHeight(this.cameraModule.orthographicCamera);this.cameraModule.setOrthographicVisibleHeight(d,this.cameraModule.orthographicCamera,h)}this.camera.position.copy(r),this.camera.quaternion.copy(A),this.camera.up.copy(a),this.camera.updateMatrixWorld(!0),l&&this.controls?.target&&this.controls.target.copy(l),c&&this.controlModule.orbitControls?.origin&&this.controlModule.orbitControls.origin.copy(c),this.catchSvg.setAttribute("viewBox",`0 0 ${s} ${o}`),this.catchSvg.style.width=`${s}px`,this.catchSvg.style.height=`${o}px`,this.viewCube?.cubeTool?.Resize?.(),this.fabricDraw?.resize?.(s,o),this.events.trigger(Qs.ViewportResize,{width:s,height:o}),this.requestComposerRender()}dispose(){if(this.isDisposed)return;this.isDisposed=!0,this.resizeObserver?.disconnect(),this.renderer.setAnimationLoop(null),this.rangeScale?.dispose?.(),this.measure?.dispose?.(),this.clipping?.dispose?.(),this.pathRoaming?.dispose?.(),this.linkElement2d3d?.dispose?.(),this.linkView2d3d?.dispose?.(),this.skyManager?.close?.(!0),this.hdr?.dispose?.(),this.minMap?.dispose?.(),this.grid?.dispose?.(),this.level?.dispose?.(),this.ground?.dispose?.(),this.issueReport?.dispose?.(),this.fabricDraw?.dispose?.(),this.modelLink3d?.dispose?.(),this.label?.dispose?.(),this.annotation3d?.dispose?.(),this.calibration?.dispose?.(),this.search?.dispose?.(),this.modelPlace?.dispose?.(),this.modelComparison?.dispose?.(),this.modelExplode?.dispose?.(),this.materialTool?.dispose?.(),this.materialReplacement?.dispose?.(),this.pathDraw?.dispose?.(),this.nodeBox?.dispose?.(),this.interactionModule?.dispose?.(),this.hoverHighLight?.dispose?.(),gbt(this),this.handelBehaved?.disActive?.(),this.viewCube?.cubeTool?.dispose?.(),this.controlModule?.dispose?.(),this.engineStatus?.dispose?.(),this.events?.dispose?.(),this.cameraModule?.dispose?.(),this.composerModule?.dispose?.(),this.engineModelModule?.dispose?.(),this.autoExposureModule?.dispose?.(),this.catchSvg?.remove(),this.stats?.dom?.remove(),this.stats=void 0,this.renderStatsEl?.remove(),this.renderStatsEl=null,this.renderTrianglesValueEl=null,this.renderDrawCallsValueEl=null,this.versionEl?.remove(),this.versionEl=null;const e=new Set,t=new Set,n=new Set,s=new Set,o=r=>{if(!(r==null||typeof r!="object"||s.has(r))){if(s.add(r),r.isTexture===!0&&typeof r.dispose=="function"){n.add(r);return}if(Array.isArray(r)){r.forEach(o);return}Object.values(r).forEach(o)}};this.scene.traverse(r=>{const A=r;A.geometry&&e.add(A.geometry),(Array.isArray(A.material)?A.material:A.material?[A.material]:[]).forEach(l=>{t.add(l),o(l)})}),e.forEach(r=>r.dispose()),t.forEach(r=>r.dispose()),n.forEach(r=>r.dispose()),this.scene.clear(),this.renderModule.disposeRenderer()}async initialize(){if(await this.renderModule.initRenderer(),this.options.backgroundColor===void 0&&this.skyManager?.activate(),this.isDisposed)throw new Error("EngineKernelV3 在初始化完成前已被销毁。");return await this.renderer.setAnimationLoop(this.animate),this.requestComposerRender(),this}animate=e=>{if(this.isDisposed||this.isRenderingPaused)return;const t=this.engineStatus?.isFree===!0;this.frameLockEnabled&&t&&this.idleFrameRateExemptionReasons.size===0&&!this.pendingComposerRender&&e-this.lastIdleFrameTime<this.idleFrameInterval||(this.lastIdleFrameTime=e,this.stats?.begin(),this.modelEdge?.update?.(),this.controlModule.update(),this.autoExposureModule?.update(e),dbt(this,this.camera,this.container.clientHeight)&&this.requestShadowUpdate(),this.skyManager?.update?.(e),this.composerModule.render(),this.renderModule.drawWatermark(),this.viewCube?.cubeTool?.RenderScene?.(),this.hoverHighLight.update(),this.measure?.update?.(),this.ground?.update?.(),this.modelPlace?.update?.(),this.pathDraw?.update?.(),this.minMap?.update?.(),this.grid?.update?.(),this.level?.update?.(),this.text?.update?.(),this.label?.update?.(),this.annotation3d?.updateFrame?.(1/60),this.modelExplode?.update?.(),this.updateRenderStats(),this.stats?.end(),this.pendingComposerRender=this.options.continuousRendering===!0)};initializeStats(){if(this.options.showStats!==!0)return;this.stats=new Cee,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0",this.stats.dom.style.left="0",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom);const e=document.createElement("div");e.className="bim-render-stats";const t=document.createElement("span");t.textContent="三角面";const n=document.createElement("span");n.textContent="0";const s=document.createElement("span");s.textContent="Draw Calls";const o=document.createElement("span");o.textContent="0",e.append(t,n,s,o),this.container.appendChild(e),this.renderStatsEl=e,this.renderTrianglesValueEl=n,this.renderDrawCallsValueEl=o}updateRenderStats(){if(this.renderStatsEl==null)return;const e=this.renderer?.info?.render,t=Number.isFinite(e?.triangles)?e.triangles:0,n=Number.isFinite(e?.drawCalls)?e.drawCalls:0;this.renderTrianglesValueEl!=null&&(this.renderTrianglesValueEl.textContent=Math.round(t).toLocaleString()),this.renderDrawCallsValueEl!=null&&(this.renderDrawCallsValueEl.textContent=Math.round(n).toLocaleString())}createCatchSvg(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");return e.classList.add("catchSvg"),e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.pointerEvents="none",window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.container.appendChild(e),e}resolveContainer(e){if(e.container instanceof HTMLElement)return e.container;const t=e.containerId?document.getElementById(e.containerId):null;if(!t)throw new Error(`Container ${e.containerId??""} not found`);return t}}const Dvt=Object.freeze(Object.defineProperty({__proto__:null,EngineKernelV3:Mvt},Symbol.toStringTag,{value:"Module"}));class Svt{engine;scene;constructor(e){this.engine=e,this.scene=new ld;let t=new qn;t.name="groupEdge",this.scene.add(t)}}var Rb=(i=>(i.PERSPECTIVE="perspective",i.ORTHOGRAPHIC="orthographic",i))(Rb||{});class aa{static MIN_VISIBLE_HEIGHT=1e-4;static MIN_CAMERA_DISTANCE=1e-4;static CAMERA_ANIMATION_IDLE_EXEMPT_REASON="camera-module-animation";engine;perspectiveCamera;orthographicCamera;cameraAnimationFrame=null;constructor(e){this.engine=e,this.perspectiveCamera=new Yo(45,this.engine.container.clientWidth/this.engine.container.clientHeight,.1,1e3),this.perspectiveCamera.position.set(2,2,2),this.perspectiveCamera.lookAt(0,0,0);const t=50,n=this.engine.container.clientWidth/this.engine.container.clientHeight;this.orthographicCamera=new Zo(t*n/-2,t*n/2,t/2,t/-2,.1,1e3)}exitDrawingPinView(){this.engine.drawingPin?.exitViewMode?.()}getCameraAspect(e){const t=e?.width??this.engine.container?.clientWidth??1,n=e?.height??this.engine.container?.clientHeight??1;return n>0?t/n:1}getPerspectiveVisibleHeight(e,t){const n=Math.max(e.position.distanceTo(t),aa.MIN_CAMERA_DISTANCE),s=Ai.degToRad(e.getEffectiveFOV()*.5);return Math.max(2*n*Math.tan(s),aa.MIN_VISIBLE_HEIGHT)}getOrthographicVisibleHeight(e=this.orthographicCamera){return Math.max((e.top-e.bottom)/e.zoom,aa.MIN_VISIBLE_HEIGHT)}setOrthographicVisibleHeight(e,t=this.orthographicCamera,n){const s=Math.max(e,aa.MIN_VISIBLE_HEIGHT),o=Number.isFinite(n)&&n>0?n:this.getCameraAspect(),r=Math.max(t.zoom||1,aa.MIN_CAMERA_DISTANCE),A=s*r*.5,a=A*o;t.left=-a,t.right=a,t.top=A,t.bottom=-A}getViewDirection(e,t,n){const s=new N().subVectors(e,t);return s.lengthSq()>aa.MIN_CAMERA_DISTANCE?s.normalize():new N(0,0,1).applyQuaternion(n).normalize()}getStableCameraUp(e){const t=e.clone().normalize();if(t.lengthSq()<=aa.MIN_CAMERA_DISTANCE)return new N(0,1,0);const n=[new N(0,1,0),new N(0,0,1),new N(1,0,0)];for(const s of n){const o=s.clone().sub(t.clone().multiplyScalar(s.dot(t)));if(o.lengthSq()>aa.MIN_CAMERA_DISTANCE)return o.normalize()}return new N(0,1,0)}updateComposerCamera(){if(!this.engine.composerModule?.composer)return;const e=this.engine.camera,t=this.engine.composerModule.composer;if(t.passes)for(const n of t.passes)n.camera!==void 0&&(n.camera=e)}applySwitchedCamera(e,t){this.engine.camera=e,this.engine.scene.camera=e,this.engine.controls?.target&&this.engine.controls.target.copy(t),this.engine.controls&&(this.engine.controls.object=e),this.engine.controlModule.orbitControls.object=e,this.engine.controlModule.firstPersonControls.camera=e,this.engine.controlModule.firstPersonControls.object=e,this.engine.controlModule.firstPersonControls.syncRotationStateFromCamera?.(),this.engine.controlModule.firstPersonControls.syncSharedTargetFromCamera?.(),this.engine.controlModule.thirdPersonControls&&(this.engine.controlModule.thirdPersonControls.camera=e,this.engine.controlModule.thirdPersonControls.object=e,this.engine.controlModule.thirdPersonControls.syncRotationStateFromCamera?.(),this.engine.controlModule.thirdPersonControls.syncSharedTargetFromAvatar?.()),e.updateProjectionMatrix?.(),e.updateMatrixWorld(),this.updateComposerCamera(),this.engine.controls?.update&&this.engine.controls.update(),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene)}resolvePoseReferenceUp(e,t){if(e.referenceUp){const a=new N(e.referenceUp.x,e.referenceUp.y,e.referenceUp.z);if(a.lengthSq()>aa.MIN_CAMERA_DISTANCE)return a.normalize()}if(!e.up||!t)return;const n=new N(e.up.x,e.up.y,e.up.z);if(n.lengthSq()<=aa.MIN_CAMERA_DISTANCE)return;const s=t.clone().sub(this.engine.camera.position);if(s.lengthSq()<=aa.MIN_CAMERA_DISTANCE)return;s.normalize(),n.normalize();const o=[new N(0,1,0),new N(0,-1,0),new N(0,0,1),new N(0,0,-1),new N(1,0,0),new N(-1,0,0)];let r,A=-1/0;for(const a of o){const l=a.clone().sub(s.clone().multiplyScalar(a.dot(s)));if(l.lengthSq()<=aa.MIN_CAMERA_DISTANCE)continue;const c=l.normalize().dot(n);c>A&&(A=c,r=a.clone())}return r}syncControlsAfterPoseRestore(e,t,n,s){const o=this.engine.camera;if(!o)return;e&&this.engine.controls?.target&&this.engine.controls.target.copy(e);const r=this.engine.controlModule?.orbitControls;r&&(e&&typeof r.syncStateFromCamera=="function"?r.syncStateFromCamera(o,e,{origin:t??"target",referenceUp:n,viewRight:s}):(r.object=o,e&&r.target&&r.target.copy(e),t&&r.origin?r.origin.copy(t):e&&r.origin&&r.origin.copy(e),n&&r._referenceUp?.copy&&r._referenceUp.copy(n).normalize(),s&&r._viewRight?.copy&&r._viewRight.copy(s).normalize(),r._rotateVelocity?.set?.(0,0),r._panVelocity?.set?.(0,0),typeof r._zoomVelocity=="number"&&(r._zoomVelocity=0),r._lastPosition?.copy?.(o.position),r._lastTarget?.copy?.(r.target),r._lastUp?.copy?.(o.up),r._lastQuaternion?.copy?.(o.quaternion),r._lastZoom=o.zoom,r.saveState?.()));const A=this.engine.controlModule?.firstPersonControls;A&&(A.camera=o,A.object=o,A.syncRotationStateFromCamera?.(),A.syncSharedTargetFromCamera?.());const a=this.engine.controlModule?.thirdPersonControls;a&&(a.camera=o,a.object=o,a.syncRotationStateFromCamera?.(),a.syncSharedTargetFromAvatar?.()),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene)}inferTargetFromRestoredCamera(e){const t=new N;e.getWorldDirection(t),t.lengthSq()<=aa.MIN_CAMERA_DISTANCE&&t.set(0,0,-1);const s=this.engine.controls?.target?.distanceTo?.(e.position),o=this.engine.octreeBox?.getBoundingBox?.(),r=o?.min&&o?.max?o.max.distanceTo(o.min)*.8:0;let A=10;return typeof s=="number"&&Number.isFinite(s)&&s>aa.MIN_CAMERA_DISTANCE?A=s:r>aa.MIN_CAMERA_DISTANCE&&(A=r),e.position.clone().add(t.normalize().multiplyScalar(A))}switchCurrentCamera(){this.engine.camera===this.perspectiveCamera?this.switchToOrthographicCamera():this.switchToPerspectiveCamera()}setPerspectiveFov(e,t){const n=this.perspectiveCamera,s=n.fov,o=Math.max(1,Math.min(120,e));if(t?.adjustDistance!==!1&&this.engine.camera===n&&this.engine.controls?.target){const A=this.engine.controls.target.clone(),a=n.position.clone(),l=a.distanceTo(A);if(l>1e-6){const c=Ai.degToRad(s*.5),h=Ai.degToRad(o*.5),d=Math.tan(c)/Math.tan(h),g=l*d,u=new N().subVectors(a,A).normalize();n.position.copy(A).add(u.multiplyScalar(g))}}n.fov=o,n.updateProjectionMatrix()}switchToPerspectiveCamera(){if(this.exitDrawingPinView(),!this.engine.controls)return;const e=this.engine.camera;if(!e)return;const t=e.position.clone(),n=this.engine.controls.target.clone(),s=e.quaternion.clone(),o=e.up.clone(),r=this.perspectiveCamera,A=this.getViewDirection(t,n,s),a=e instanceof Zo?this.getOrthographicVisibleHeight(e):this.getPerspectiveVisibleHeight(e,n),l=Ai.degToRad(r.getEffectiveFOV()*.5),c=Math.max(a/(2*Math.tan(l)),aa.MIN_CAMERA_DISTANCE);r.near=e.near,r.far=e.far,r.aspect=this.getCameraAspect(),r.up.copy(o),r.position.copy(n).add(A.multiplyScalar(c)),r.lookAt(n),this.engine.camera=r,this.applySwitchedCamera(r,n)}switchToOrthographicCamera(){if(this.exitDrawingPinView(),!this.engine.controls)return;const e=this.engine.camera;if(!e)return;const t=e.position.clone(),n=this.engine.controls.target.clone(),s=e.quaternion.clone(),o=e.up.clone(),r=this.orthographicCamera,A=this.getViewDirection(t,n,s),a=e instanceof Yo?this.getPerspectiveVisibleHeight(e,n):this.getOrthographicVisibleHeight(e),l=Ai.degToRad(e.getEffectiveFOV()*.5),c=Math.max(a/(2*Math.tan(l)),aa.MIN_CAMERA_DISTANCE);r.near=e.near,r.far=e.far,r.zoom=1,this.setOrthographicVisibleHeight(a,r),r.up.copy(o);const h=this.engine.octreeBox?.getBoundingBox?.(),d=h?h.max.distanceTo(h.min)*.8:c,g=Math.max(d,aa.MIN_CAMERA_DISTANCE);r.position.copy(n).add(A.clone().multiplyScalar(g)),r.quaternion.copy(s),this.engine.camera=r,this.applySwitchedCamera(r,n)}getCameraType(){return this.engine.camera===this.perspectiveCamera?"perspective":this.engine.camera===this.orthographicCamera?"orthographic":"perspective"}getCameraPose(){const e=this.engine.camera,t=this.getCameraType(),n={type:t,position:{x:e.position.x,y:e.position.y,z:e.position.z},rotation:{x:e.rotation.x,y:e.rotation.y,z:e.rotation.z},quaternion:{x:e.quaternion.x,y:e.quaternion.y,z:e.quaternion.z,w:e.quaternion.w},up:{x:e.up.x,y:e.up.y,z:e.up.z}};this.engine.controls?.target&&(n.target={x:this.engine.controls.target.x,y:this.engine.controls.target.y,z:this.engine.controls.target.z});const s=this.engine.controlModule?.orbitControls;return s?.origin&&(n.origin={x:s.origin.x,y:s.origin.y,z:s.origin.z}),s?._referenceUp&&(n.referenceUp={x:s._referenceUp.x,y:s._referenceUp.y,z:s._referenceUp.z}),s?._viewRight&&(n.viewRight={x:s._viewRight.x,y:s._viewRight.y,z:s._viewRight.z}),t==="orthographic"&&(n.zoom=e.zoom,n.orthographicHeight=this.getOrthographicVisibleHeight(e)),n}restoreCameraPose(e){this.exitDrawingPinView(),this.getCameraType()!==e.type&&(e.type==="perspective"?this.switchToPerspectiveCamera():this.switchToOrthographicCamera());const n=this.engine.camera;n.position.set(e.position.x,e.position.y,e.position.z),e.up&&n.up.set(e.up.x,e.up.y,e.up.z),e.quaternion?n.quaternion.set(e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w):e.rotation&&n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z);let s;e.target&&(s=new N(e.target.x,e.target.y,e.target.z));const o=e.origin?new N(e.origin.x,e.origin.y,e.origin.z):s?.clone();if(e.type==="orthographic"){const a=n;e.zoom!==void 0&&(a.zoom=e.zoom),e.orthographicHeight!==void 0&&this.setOrthographicVisibleHeight(e.orthographicHeight,a),a.updateProjectionMatrix()}n.updateMatrix(),n.updateMatrixWorld(!0),s||(s=this.inferTargetFromRestoredCamera(n));const r=this.resolvePoseReferenceUp(e,s),A=e.viewRight?new N(e.viewRight.x,e.viewRight.y,e.viewRight.z):void 0;this.syncControlsAfterPoseRestore(s,o,r,A)}setViewFromOriginAndDirection(e,t,n=null,s,o=0,r){this.exitDrawingPinView();const A=new N(t.x,t.y,t.z).normalize(),a=new N(e.x,e.y,e.z);let l=s??null;if(l==null||l<=0){const d=this.engine.octreeBox?.getBoundingBox?.();if(d&&d.min&&d.max){const g=new N().subVectors(d.max,d.min);l=Math.max(g.x,g.y,g.z)*1.2}else l=50}const c=a.clone().add(A.clone().negate().multiplyScalar(l));if(this.engine.camera){if(n||(n=this.getStableCameraUp(A)),o>0){this.animateCameraToTarget(c,a,n,o,r);return}this.applyCameraPose(c,a,n),r?.()}}rotateToTarget(e,t=0,n){const s=this.engine.camera;if(!s)return;const o=new N(e.x,e.y,e.z);if(s.position.distanceToSquared(o)<=aa.MIN_CAMERA_DISTANCE){n?.();return}const r=s.position.clone(),A=s.up.lengthSq()>aa.MIN_CAMERA_DISTANCE?s.up.clone().normalize():this.getStableCameraUp(o.clone().sub(r));if(t>0){this.animateCameraToTarget(r,o,A,t,n);return}this.applyCameraPose(r,o,A),n?.()}applyCameraPose(e,t,n){const s=this.engine.camera;s&&(s.position.copy(e),s.up.copy(n),this.engine.controls?.target&&this.engine.controls.target.copy(t),typeof this.engine.controls?.setScreenUp=="function"?this.engine.controls.setScreenUp(n):s.lookAt(t),this.engine.controls?.update&&this.engine.controls.update(),s.updateMatrix(),s.updateMatrixWorld(!0))}animateCameraToTarget(e,t,n,s,o){const r=this.engine.camera,A=this.engine.controls;if(!r||!A?.target){this.applyCameraPose(e,t,n),o?.();return}const a=()=>{this.engine.renderer&&(this.engine.renderer.interactionActive=!0),this.engine.setIdleFrameRateExempt?.(aa.CAMERA_ANIMATION_IDLE_EXEMPT_REASON,!0),this.engine.events?.trigger?.("engine-busy"),this.engine.requestComposerRender?.()},l=()=>{this.engine.renderer&&(this.engine.renderer.interactionActive=!1),this.engine.setIdleFrameRateExempt?.(aa.CAMERA_ANIMATION_IDLE_EXEMPT_REASON,!1),this.engine.events?.trigger?.("engine-free")};this.cameraAnimationFrame!=null&&(cancelAnimationFrame(this.cameraAnimationFrame),this.cameraAnimationFrame=null,l());const c=new qg.Tween({px:r.position.x,py:r.position.y,pz:r.position.z,tx:A.target.x,ty:A.target.y,tz:A.target.z,ux:r.up.x,uy:r.up.y,uz:r.up.z}).to({px:e.x,py:e.y,pz:e.z,tx:t.x,ty:t.y,tz:t.z,ux:n.x,uy:n.y,uz:n.z},s);c.easing(qg.Easing.Cubic.InOut),c.onUpdate(d=>{r.position.set(d.px,d.py,d.pz),A.target.set(d.tx,d.ty,d.tz),r.up.set(d.ux,d.uy,d.uz).normalize(),typeof A.setScreenUp=="function"?A.setScreenUp(r.up.clone()):r.lookAt(A.target),A.auto=!0,A.update?.(),r.updateMatrix(),r.updateMatrixWorld(!0),this.engine.requestComposerRender?.()}),c.onComplete(()=>{A.auto=!1,this.cameraAnimationFrame=null,this.applyCameraPose(e,t,n),this.engine.requestComposerRender?.(),l(),o?.()});const h=()=>{c.update()&&(this.cameraAnimationFrame=requestAnimationFrame(h))};a(),c.start(),h()}}class xvt{engine;deviceType;constructor(e){this.engine=e,this.deviceType=this.detectDeviceType()}detectDeviceType(){const e=[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i,/Mobile/i],t=navigator.userAgent||globalThis.opera,n=e.some(c=>c.test(t)),s="ontouchstart"in globalThis||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0,o=globalThis.screen.width,r=globalThis.screen.height,A=o<=768||r<=768,l=(globalThis.devicePixelRatio||1)>=2;return n||s&&A||s&&l?"mobile":"PC"}getDeviceType(){return this.deviceType}isMobile(){return this.deviceType==="mobile"}isPC(){return this.deviceType==="PC"}redetectDeviceType(){return this.deviceType=this.detectDeviceType(),this.deviceType}getContainerSize(){return{width:this.engine.container.clientWidth,height:this.engine.container.clientHeight}}}const _se=1.1;function x2e(i){if(i?.deviceModule?.isMobile?.()!==!0)return window.devicePixelRatio||1;const e=Number(i?.options?.limit_memory);return!Number.isFinite(e)||e<=4?.8:e>=8||e>=6?2:1}function T2e(i){if(i?.deviceModule?.isMobile?.()!==!0)return!0;const e=Number(i?.options?.limit_memory);return!(!Number.isFinite(e)||e<=4)}class Tvt{engine;renderer;watermark;constructor(e){this.engine=e,this.renderer=null,this.watermark=new NN(uD)}createRenderer(){const{width:e,height:t}=this.engine.deviceModule.getContainerSize();return this.engine.deviceModule.isMobile(),In.enabled=!0,this.renderer=new Rm({antialias:this.engine.options.antialias??!0,alpha:!0,premultipliedAlpha:!1,stencil:!0,preserveDrawingBuffer:T2e(this.engine)}),this.renderer.setClearColor(0,0),this.renderer.setSize(e,t,!1),this.renderer.setPixelRatio(x2e(this.engine)),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.renderer.domElement.style.display="block",this.renderer.shadowMap.enabled=T2e(this.engine),this.renderer.shadowMap.type=P0,this.renderer.localClippingEnabled=!0,this.renderer.outputColorSpace=Cs,this.renderer.toneMapping=v0,this.renderer.toneMappingExposure=_se,this.engine.container.appendChild(this.renderer.domElement),this.renderer}disposeRenderer(){this.watermark.dispose(),this.renderer?.dispose()}drawWatermark(){this.renderer&&this.watermark.render(this.renderer)}}const Pvt={type:"change"},P2e={type:"start"},_2e={type:"end"},yr=1e-6,Fse=Math.PI*2,Qc={NONE:-1,ROTATE:0,PAN:1,DOLLY:2,TOUCH_ROTATE:3,TOUCH_DOLLY_PAN:4},vse=new N(1,0,0),_vt=new N(0,1,0),Fvt=new N(0,0,1),m_=new N,KX=new N,fg=new N,Ar=new N,Sp=new N,rh=new N,xp=new N,vvt=new N,XX=new nn,Rse=new nn,F2e=new Set(["KeyW","KeyA","KeyS","KeyD","KeyQ","KeyE","ArrowUp","ArrowLeft","ArrowDown","ArrowRight","ShiftLeft","ShiftRight"]);function VX(i,e,t){return Math.max(e,Math.min(t,i))}function v2e(i){return{width:Math.max(i?.clientWidth||1,1),height:Math.max(i?.clientHeight||1,1)}}function Nb(i){return i&&typeof i.x=="number"&&typeof i.y=="number"&&typeof i.z=="number"}function R2e(i){const e=i?.tagName?.toLowerCase?.();return i?.isContentEditable===!0||e==="input"||e==="textarea"||e==="select"}class N2e extends GO{constructor(e,t,n=null){super(t,n),this.engine=e,this.target=new N,this.origin=new N,this.cursor=new N,this.showOriginIcon=!0,this.auto=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.enableRotate=!0,this.enablePan=!0,this.enableZoom=!0,this.enableDamping=!1,this.rotateSpeed=.51,this.panSpeed=1,this.zoomSpeed=1,this.touchZoomSpeed=1.35,this.dampingFactor=.08,this.keyRotateSpeed=1,this.keyPanSpeed=7,this.keyMoveSpeed=.5,this.keyMoveBoost=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:uc.ROTATE,MIDDLE:uc.DOLLY,RIGHT:uc.PAN},this.state=Qc.NONE,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.up0=this.object.up.clone(),this.origin0=this.origin.clone(),this._lastZoom=this.object.zoom,this._lastPosition=this.object.position.clone(),this._lastTarget=this.target.clone(),this._lastUp=this.object.up.clone(),this._lastQuaternion=this.object.quaternion.clone(),this._referenceUp=this.object.up.clone().normalize(),this._viewRight=new N(1,0,0).applyQuaternion(this.object.quaternion).normalize(),this._rotateVelocity=new Ne,this._panVelocity=new Ne,this._zoomVelocity=0,this._mouseStart=new Ne,this._touchCenter=new Ne,this._touchDistance=0,this._pointers=new Map,this._pressedKeys=new Set,this._keyboardAnimationId=null,this._lastKeyboardMoveTime=0,this._isInteracting=!1,this._keyDomElement=null,this._touchAction="",this._onContextMenu=this._handleContextMenu.bind(this),this._onPointerDown=this._handlePointerDown.bind(this),this._onPointerMove=this._handlePointerMove.bind(this),this._onPointerUp=this._handlePointerUp.bind(this),this._onPointerCancel=this._handlePointerUp.bind(this),this._onWheel=this._handleWheel.bind(this),this._onKeyDown=this._handleKeyDown.bind(this),this._onKeyUp=this._handleKeyUp.bind(this),this.domElement&&this.connect(this.domElement),this.update(),this.saveState()}connect(e){e&&(this.disconnect(),this.domElement=e,this._touchAction=e.style.touchAction,e.style.touchAction="none",e.addEventListener("contextmenu",this._onContextMenu),e.addEventListener("pointerdown",this._onPointerDown),e.addEventListener("pointermove",this._onPointerMove),e.addEventListener("pointerup",this._onPointerUp),e.addEventListener("pointercancel",this._onPointerCancel),e.addEventListener("wheel",this._onWheel,{passive:!1}),this.listenToKeyEvents(window))}disconnect(){this.domElement&&(this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onWheel),this.domElement.style.touchAction=this._touchAction,this.stopListenToKeyEvents())}dispose(){this.disconnect(),this._pointers.clear(),this._pressedKeys.clear(),this._stopKeyboardMoveLoop(),this.state=Qc.NONE}listenToKeyEvents(e){this.stopListenToKeyEvents(),this._keyDomElement=e,this._keyDomElement?.addEventListener("keydown",this._onKeyDown),this._keyDomElement?.addEventListener("keyup",this._onKeyUp)}stopListenToKeyEvents(){this._keyDomElement&&(this._keyDomElement.removeEventListener("keydown",this._onKeyDown),this._keyDomElement.removeEventListener("keyup",this._onKeyUp),this._keyDomElement=null,this._pressedKeys.clear(),this._stopKeyboardMoveLoop())}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom,this.up0.copy(this.object.up),Nb(this.origin)&&this.origin0.copy(this.origin)}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.up.copy(this.up0),Nb(this.origin)&&this.origin.copy(this.origin0),this._rotateVelocity.set(0,0),this._panVelocity.set(0,0),this._zoomVelocity=0,this.object.updateProjectionMatrix?.(),this.update(!0),this.state=Qc.NONE}setScreenUp(e){return!Nb(e)||(rh.copy(this.target).sub(this.object.position),rh.lengthSq()<yr)||(rh.normalize(),Sp.copy(e).normalize(),Ar.crossVectors(rh,Sp),Ar.lengthSq()<yr)?!1:(this._viewRight.copy(Ar.normalize()),this.update(!0),!0)}syncStateFromCamera(e=this.object,t=this.target,n={}){if(!e)return!1;this.object=e,Nb(t)&&this.target.copy(t),n.origin==="target"?this.origin.copy(this.target):Nb(n.origin)&&this.origin.copy(n.origin);const s=this.target.clone().sub(e.position),o=Nb(n.referenceUp)?new N(n.referenceUp.x,n.referenceUp.y,n.referenceUp.z).normalize():e.up.clone().normalize();return o.lengthSq()>yr&&this._referenceUp.copy(o),Nb(n.viewRight)?this._viewRight.copy(n.viewRight).normalize():s.lengthSq()>yr&&(s.normalize(),Ar.crossVectors(s,this._referenceUp),Ar.lengthSq()>yr?this._viewRight.copy(Ar.normalize()):this._viewRight.set(1,0,0).applyQuaternion(e.quaternion).normalize()),this._rotateVelocity.set(0,0),this._panVelocity.set(0,0),this._zoomVelocity=0,this._mouseStart.set(0,0),this._touchCenter.set(0,0),this._touchDistance=0,this._pointers.clear(),this._pressedKeys.clear(),this._isInteracting=!1,this.state=Qc.NONE,this._lastPosition.copy(e.position),this._lastTarget.copy(this.target),this._lastUp.copy(e.up),this._lastQuaternion.copy(e.quaternion),this._lastZoom=e.zoom,this.saveState(),!0}update(e=null,t=!1){const n=typeof e=="number"?e:null,s=typeof e=="boolean"?e:!!t,o=this._applyPendingMotion(n);this._alignCamera();const r=s||o||this._hasCameraStateChanged();return r&&(this.dispatchEvent(Pvt),this._rememberState()),r}_applyPendingMotion(e){let t=!1;this.autoRotate&&this.state===Qc.NONE&&this.auto===!1&&(this._rotateVelocity.x+=this._getAutoRotateAngle(e)),this._applyKeyboardMove(e)&&(t=!0);const n=this._consumeVector2(this._rotateVelocity);n.lengthSq()>yr&&this.enableRotate&&(this._applyRotation(n.x,n.y),t=!0);const s=this._consumeVector2(this._panVelocity);s.lengthSq()>yr&&this.enablePan&&(this._applyPan(s.x,s.y),t=!0);const o=this._consumeNumber("_zoomVelocity");return Math.abs(o)>yr&&this.enableZoom&&(this._applyZoom(o),t=!0),t}_applyKeyboardMove(e){if(!this.enabled||!this.object?.isPerspectiveCamera||this._pressedKeys.size===0||(xp.set(0,0,0),(this._pressedKeys.has("KeyW")||this._pressedKeys.has("ArrowUp"))&&(xp.z+=1),(this._pressedKeys.has("KeyS")||this._pressedKeys.has("ArrowDown"))&&(xp.z-=1),(this._pressedKeys.has("KeyA")||this._pressedKeys.has("ArrowLeft"))&&(xp.x-=1),(this._pressedKeys.has("KeyD")||this._pressedKeys.has("ArrowRight"))&&(xp.x+=1),this._pressedKeys.has("KeyQ")&&(xp.y+=1),this._pressedKeys.has("KeyE")&&(xp.y-=1),xp.lengthSq()<=yr)||(xp.normalize(),Ar.copy(vse).applyQuaternion(this.object.quaternion).normalize(),rh.set(0,0,-1).applyQuaternion(this.object.quaternion).normalize(),Sp.copy(this._referenceUp).normalize(),Sp.lengthSq()<=yr&&Sp.copy(this.object.up).normalize(),fg.set(0,0,0),fg.addScaledVector(Ar,xp.x),fg.addScaledVector(rh,xp.z),fg.addScaledVector(Sp,xp.y),fg.lengthSq()<=yr))return!1;fg.normalize();const t=Number.isFinite(e)&&e>0?e:1/60,n=Math.max(this.object.position.distanceTo(this.target),1),s=this._pressedKeys.has("ShiftLeft")||this._pressedKeys.has("ShiftRight")?this.keyMoveBoost:1,o=Math.max(n*.8,1)*this.keyMoveSpeed*t*s;return fg.multiplyScalar(o),this.object.position.add(fg),this.target.add(fg),this.origin.add(fg),!0}_startKeyboardMoveLoop(){if(this._keyboardAnimationId!=null)return;this._lastKeyboardMoveTime=performance.now();const e=t=>{if(this._keyboardAnimationId=null,!this.enabled||this._pressedKeys.size===0){this._lastKeyboardMoveTime=0;return}const n=Math.min(Math.max((t-this._lastKeyboardMoveTime)/1e3,0),.05);this._lastKeyboardMoveTime=t,this.update(n),this._keyboardAnimationId=requestAnimationFrame(e)};this._keyboardAnimationId=requestAnimationFrame(e)}_stopKeyboardMoveLoop(){this._keyboardAnimationId!=null&&(cancelAnimationFrame(this._keyboardAnimationId),this._keyboardAnimationId=null),this._lastKeyboardMoveTime=0}_consumeVector2(e){if(!this.enableDamping){const s=e.clone();return e.set(0,0),s}const t=VX(this.dampingFactor,0,1),n=e.clone().multiplyScalar(t);return e.sub(n),e.lengthSq()<yr&&e.set(0,0),n}_consumeNumber(e){if(!this.enableDamping){const s=this[e];return this[e]=0,s}const t=VX(this.dampingFactor,0,1),n=this[e]*t;return this[e]-=n,Math.abs(this[e])<yr&&(this[e]=0),n}_applyRotation(e,t){const n=this._getRotatePivot(),s=this.object.position;m_.copy(s).sub(n),m_.lengthSq()<yr&&m_.set(0,0,Math.max(this.minDistance,1)),KX.copy(this.target).sub(n),rh.copy(this.target).sub(s).normalize(),Math.abs(e)>yr&&(XX.setFromAxisAngle(this._referenceUp,-e),m_.applyQuaternion(XX),KX.applyQuaternion(XX),rh.applyQuaternion(XX).normalize()),Ar.copy(this._getStableRightAxis(rh)),Math.abs(t)>yr&&Ar.lengthSq()>yr&&(Rse.setFromAxisAngle(Ar,-t),m_.applyQuaternion(Rse),KX.applyQuaternion(Rse)),s.copy(n).add(m_),this.target.copy(n).add(KX)}_applyPan(e,t){const{width:n,height:s}=v2e(this.domElement);Ar.copy(vse).applyQuaternion(this.object.quaternion).normalize(),Sp.copy(_vt).applyQuaternion(this.object.quaternion).normalize();let o=0,r=0;if(this.object.isPerspectiveCamera){const a=2*Math.max(this.object.position.distanceTo(this.target),yr)*Math.tan(Ai.degToRad(this.object.getEffectiveFOV()*.5)),l=a*this.object.aspect;o=e/n*l*this.panSpeed,r=t/s*a*this.panSpeed}else if(this.object.isOrthographicCamera){const A=(this.object.right-this.object.left)/this.object.zoom,a=(this.object.top-this.object.bottom)/this.object.zoom;o=e/n*A*this.panSpeed,r=t/s*a*this.panSpeed}else return;fg.set(0,0,0),fg.addScaledVector(Ar,-o),fg.addScaledVector(Sp,r),this.object.position.add(fg),this.target.add(fg)}_applyZoom(e){const t=Math.pow(.95,this.zoomSpeed*e);if(this.object.isPerspectiveCamera){rh.copy(this.object.position).sub(this.target);const n=Math.max(rh.length(),yr),s=VX(n/t,this.minDistance,this.maxDistance);rh.setLength(s),this.object.position.copy(this.target).add(rh);return}this.object.isOrthographicCamera&&(this.object.zoom=VX(this.object.zoom*t,this.minZoom,this.maxZoom),this.object.updateProjectionMatrix())}_alignCamera(){rh.copy(this.target).sub(this.object.position),!(rh.lengthSq()<yr)&&(rh.normalize(),Ar.copy(this._getStableRightAxis(rh)),Sp.crossVectors(Ar,rh).normalize(),Sp.lengthSq()<yr&&Sp.copy(this._referenceUp),this._viewRight.copy(Ar),this.object.up.copy(Sp),this.object.lookAt(this.target),this.object.updateMatrixWorld())}_getStableRightAxis(e){return Ar.crossVectors(e,this._referenceUp),Ar.lengthSq()<yr&&(Ar.copy(this._viewRight),Ar.addScaledVector(e,-Ar.dot(e))),Ar.lengthSq()<yr&&(Ar.copy(vse),Ar.addScaledVector(e,-Ar.dot(e))),Ar.lengthSq()<yr&&(Ar.copy(Fvt),Ar.addScaledVector(e,-Ar.dot(e))),Ar.normalize(),this._viewRight.lengthSq()>yr&&Ar.dot(this._viewRight)<0&&Ar.negate(),Ar}_getRotatePivot(){return Nb(this.origin)?this.origin.distanceToSquared(this.target)<yr?this.target:vvt.copy(this.origin):this.target}_hasCameraStateChanged(){const e=this.object.isOrthographicCamera&&Math.abs(this.object.zoom-this._lastZoom)>yr;return this._lastPosition.distanceToSquared(this.object.position)>yr||this._lastTarget.distanceToSquared(this.target)>yr||this._lastUp.distanceToSquared(this.object.up)>yr||8*(1-Math.abs(this._lastQuaternion.dot(this.object.quaternion)))>yr||e}_rememberState(){this._lastPosition.copy(this.object.position),this._lastTarget.copy(this.target),this._lastUp.copy(this.object.up),this._lastQuaternion.copy(this.object.quaternion),this._lastZoom=this.object.zoom}_getAutoRotateAngle(e){return e!=null?Fse/60*this.autoRotateSpeed*e:Fse/3600*this.autoRotateSpeed}_beginInteraction(e){this._isInteracting||(this.dispatchEvent(P2e),this._isInteracting=!0),this.state=e}_endInteraction(){this._isInteracting&&(this._isInteracting=!1,this.state=Qc.NONE,this.dispatchEvent(_2e))}_handleContextMenu(e){e.preventDefault()}_handlePointerDown(e){if(!this.enabled||!this.domElement)return;if(this.domElement.setPointerCapture?.(e.pointerId),this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,pointerType:e.pointerType,button:e.button}),e.pointerType==="touch"){this._handleTouchStart();return}const t=this._resolveMouseAction(e);t!=null&&(this._mouseStart.set(e.clientX,e.clientY),this._beginInteraction(t))}_handlePointerMove(e){const t=this._pointers.get(e.pointerId);if(!t)return;if(e.pointerType==="touch"){t.x=e.clientX,t.y=e.clientY,this._handleTouchMove();return}if(!this.enabled||this.state===Qc.NONE)return;const n=e.clientX-this._mouseStart.x,s=e.clientY-this._mouseStart.y;this._mouseStart.set(e.clientX,e.clientY),this.state===Qc.ROTATE?this._queueRotate(n,s):this.state===Qc.PAN?this._queuePan(n,s):this.state===Qc.DOLLY&&this._queueZoom(s*.01),this.update()}_handlePointerUp(e){if(this._pointers.has(e.pointerId)){if(this.domElement?.releasePointerCapture?.(e.pointerId),this._pointers.delete(e.pointerId),e.pointerType==="touch"){this._pointers.size>0?this._restartTouchGesture():this._endInteraction();return}this._endInteraction()}}_handleWheel(e){!this.enabled||!this.enableZoom||(e.preventDefault(),this.dispatchEvent(P2e),this._queueZoom(Math.sign(e.deltaY)),this.update(),this.dispatchEvent(_2e))}_handleKeyDown(e){if(!this.enabled)return;const t=e.code||e.key;if(this.object?.isPerspectiveCamera&&F2e.has(t)){R2e(e.target)||(this._pressedKeys.add(t),this._startKeyboardMoveLoop(),e.preventDefault());return}let n=!1;switch(t){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this._queuePan(0,this.keyPanSpeed):this._queueRotate(0,this.keyRotateSpeed),n=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this._queuePan(0,-this.keyPanSpeed):this._queueRotate(0,-this.keyRotateSpeed),n=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this._queuePan(this.keyPanSpeed,0):this._queueRotate(this.keyRotateSpeed,0),n=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this._queuePan(-this.keyPanSpeed,0):this._queueRotate(-this.keyRotateSpeed,0),n=!0;break}n&&(e.preventDefault(),this.update())}_handleKeyUp(e){const t=e.code||e.key;F2e.has(t)&&(this._pressedKeys.delete(t),this._pressedKeys.size===0&&this._stopKeyboardMoveLoop(),this.object?.isPerspectiveCamera&&!R2e(e.target)&&e.preventDefault())}_handleTouchStart(){const e=Array.from(this._pointers.values());if(e.length===1){this._touchCenter.set(e[0].x,e[0].y),this._touchDistance=0,this._beginInteraction(Qc.TOUCH_ROTATE);return}if(e.length>=2){const t=(e[0].x+e[1].x)*.5,n=(e[0].y+e[1].y)*.5,s=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y);this._touchCenter.set(t,n),this._touchDistance=s,this._beginInteraction(Qc.TOUCH_DOLLY_PAN)}}_restartTouchGesture(){const e=Array.from(this._pointers.values());if(e.length===1){this.state=Qc.TOUCH_ROTATE,this._touchCenter.set(e[0].x,e[0].y),this._touchDistance=0;return}e.length>=2&&(this.state=Qc.TOUCH_DOLLY_PAN,this._touchCenter.set((e[0].x+e[1].x)*.5,(e[0].y+e[1].y)*.5),this._touchDistance=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y))}_handleTouchMove(){if(!this.enabled)return;const e=Array.from(this._pointers.values());if(e.length===1&&this.state===Qc.TOUCH_ROTATE){const o=e[0].x-this._touchCenter.x,r=e[0].y-this._touchCenter.y;this._touchCenter.set(e[0].x,e[0].y),this._queueRotate(o,r),this.update();return}if(e.length<2||this.state!==Qc.TOUCH_DOLLY_PAN)return;const t=(e[0].x+e[1].x)*.5,n=(e[0].y+e[1].y)*.5,s=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y);if(this._queuePan(t-this._touchCenter.x,n-this._touchCenter.y),this._touchCenter.set(t,n),this._touchDistance>0&&s>0){const o=s/this._touchDistance,r=Math.pow(o,Math.max(this.touchZoomSpeed||1,yr));this._queueZoom(Math.log(r)/Math.log(.95))}this._touchDistance=s,this.update()}_resolveMouseAction(e){let t=null;return e.button===0?t=e.ctrlKey||e.metaKey||e.shiftKey?this.mouseButtons.RIGHT:this.mouseButtons.LEFT:e.button===1?t=this.mouseButtons.MIDDLE:e.button===2&&(t=this.mouseButtons.RIGHT),t===uc.ROTATE&&this.enableRotate?Qc.ROTATE:t===uc.PAN&&this.enablePan?Qc.PAN:t===uc.DOLLY&&this.enableZoom?Qc.DOLLY:null}_queueRotate(e,t){if(!this.enableRotate||!this.domElement)return;const{height:n}=v2e(this.domElement),s=Fse/n;this._rotateVelocity.x+=e*s*this.rotateSpeed,this._rotateVelocity.y+=t*s*this.rotateSpeed}_queuePan(e,t){this.enablePan&&(this._panVelocity.x+=e,this._panVelocity.y+=t)}_queueZoom(e){this.enableZoom&&(this._zoomVelocity+=e)}}class Y2e extends wl{constructor(e,t,n,s){super(),this._Engine=e,this.camera=t,this.object=t,this.domElement=n,this._isEnabled=!1,this._rayOriginOffset=new N(0,-1,0),this._camerLocalDirection=new N,this._tmpVector=new N,this._lookDirection=new N,this._rayCaster=new Ao,this._fallingTime=0,this._isMouseInElement=!1,this._euler=new Gr(0,0,0,"YZX"),this._prevMouseX=0,this._prevMouseY=0,this._pointerLookActive=!1,this._externalLookActive=!1,this._interactionActive=!1,this._sharedTargetDistance=10,this.target=this.camera.position.clone().add(new N(0,0,-1).applyQuaternion(this.camera.quaternion).normalize().multiplyScalar(this._sharedTargetDistance)),this.applyGravity=!1,this.gravityMinHeight=!0,this.applyCollision=!0,this.positionEasing=!0,this.lookflag=1,this.lookHorizontalFlag=1,this.lookSpeed=.003,this.moveSpeed=.02,this.playerHeight=1.6,this.jumpSpeed=.24,this.jumpGravity=.012,this.maxRotateX=Math.PI*.5-.01,this.g=9.8,this.bindmousedown=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchStart.bind(this):this.onMouseDown.bind(this),this.bindmouseup=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchEnd.bind(this):this.onMouseUp.bind(this),this.bindmousemove=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchMove.bind(this):this.onMouseMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindWindowBlur=this.onWindowBlur.bind(this),this.bindVisibilityChange=this.onVisibilityChange.bind(this),this.bindMousewheel=this.onMousewheel.bind(this),this.bindMouseEnter=this.onMouseEnter.bind(this),this.bindMouseLeave=this.onMouseLeave.bind(this),this.needMousewheel=!1,this.moveWheelRun=!0,this.moveWheelStop=!1,this.wheelClock,this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this._jumpStartHeight=this.camera.position.y,this.gravityTestCount=5,this.catchTestCount=10,this.GetEngine=()=>e,this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera()}set colliders(e){this._rayCastObjects=e}set enabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?(this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera(),this.addEvents()):(this.removeEvents(),this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState?.(),this.syncRotationStateFromCamera(),this.syncSharedTargetFromCamera()))}get enabled(){return this._isEnabled}hasMoveInput(){return this._camerLocalDirection.lengthSq()>1e-8}setPointerLookActive(e){this._pointerLookActive=e===!0,this.syncInteractionState()}setExternalLookActive(e){this._externalLookActive=e===!0,this.syncInteractionState()}syncInteractionState(){const e=this._pointerLookActive||this._externalLookActive||this.hasMoveInput()||this._isJumping;this._interactionActive!==e&&(this._interactionActive=e,this.dispatchEvent({type:e?"start":"end"}))}dispatchCameraChange(){window.dispatchEvent(new CustomEvent("bimengine:camerachange",{detail:""})),this.dispatchEvent({type:"change"})}isPcDevice(){const e=this._Engine?.deviceModule?.getDeviceType?.()??this._Engine?.deviceType??this._Engine?.DeviceType;return e==="PC"||!e}addEvents(){this.isPcDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),window.addEventListener("blur",this.bindWindowBlur,!1),document.addEventListener("visibilitychange",this.bindVisibilityChange,!1),this.needMousewheel&&(document.addEventListener&&document.addEventListener("DOMMouseScroll",this.bindMousewheel,!1),window.addEventListener("mousewheel",this.bindMousewheel,!1))}removeEvents(){this.isPcDevice()?(this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove)):(this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove)),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),window.removeEventListener("blur",this.bindWindowBlur),document.removeEventListener("visibilitychange",this.bindVisibilityChange),this.needMousewheel&&(document.addEventListener&&document.removeEventListener("DOMMouseScroll",this.bindMousewheel),window.removeEventListener("mousewheel",this.bindMousewheel))}onMouseEnter(e){this._isMouseInElement=!0}onMouseLeave(e){this._isMouseInElement=!1,this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onWindowBlur(){this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onVisibilityChange(){document.hidden&&(this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState())}onMousewheel(e){let t;switch(e.wheelDelta?(e.wheelDelta>0&&(t="up"),e.wheelDelta<0&&(t="down")):e.detail&&(e.detail<0&&(t="up"),e.detail>0&&(t="down")),t){case"up":this._camerLocalDirection.z=1;break;case"down":this._camerLocalDirection.z=-1;break}this.moveWheelRun==!0?(this.moveWheelRun=!1,this.moveWheelStop=!0,this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0,this.syncInteractionState())},200)):(clearTimeout(this.wheelClock),this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0,this.syncInteractionState())},150)),this.syncInteractionState()}onMouseDown(e){console.log("[FirstPersonCameraControl] onMouseDown",e),this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this.syncRotationStateFromCamera(),this.setPointerLookActive(!0),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY}onMouseMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?e.screenX-this._prevMouseX:0,n=this._prevMouseY?e.screenY-this._prevMouseY:0,s=this._euler.x-n*this.lookflag*this.lookSpeed;s>=0?s<this.maxRotateX?this._euler.x=s:this._euler.x=this.maxRotateX:s>-this.maxRotateX?this._euler.x=s:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY;let o=this.GetEngine();o.movefirst=!0,this.dispatchCameraChange()}onMouseUp(e){let t=this.GetEngine();t.movefirst=!1,this.setPointerLookActive(!1),this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(e){this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this.syncRotationStateFromCamera(),this.setPointerLookActive(!0),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY}onTouchMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?this._prevMouseX-e.targetTouches[0].clientX:0,n=this._prevMouseY?this._prevMouseY-e.targetTouches[0].clientY:0,s=this._euler.x-n*this.lookflag*this.lookSpeed;s>=0?s<this.maxRotateX?this._euler.x=s:this._euler.x=this.maxRotateX:s>-this.maxRotateX?this._euler.x=s:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY;let o=this.GetEngine();o.movefirst=!0,this.dispatchCameraChange()}onTouchEnd(e){let t=this.GetEngine();t.movefirst=!1,this.setPointerLookActive(!1),this.domElement.removeEventListener("touchmove",this.bindmousemove)}onKeyDown(e){if(!this._isMouseInElement)return;let t=this.GetEngine();switch(t.movefirst=!0,this.dispatchCameraChange(),e.keyCode){case 38:this._camerLocalDirection.z=1;break;case 81:if(this.applyGravity){this.keydown=!1,this._camerLocalDirection.y=0;break}this.keydown=!0,this._camerLocalDirection.y=1;break;case 69:if(this.applyGravity){this.keydown=!1,this._camerLocalDirection.y=0;break}this._camerLocalDirection.y=-1;break;case 87:this._camerLocalDirection.z=1;break;case 37:this._camerLocalDirection.x=-1;break;case 65:this._camerLocalDirection.x=-1;break;case 40:this._camerLocalDirection.z=-1;break;case 83:this._camerLocalDirection.z=-1;break;case 39:this._camerLocalDirection.x=1;break;case 68:this._camerLocalDirection.x=1;break;case 32:e.preventDefault?.(),e.stopPropagation?.(),this._isJumpKeyDown||(this._isJumpKeyDown=!0,this.jump());break;case 16:this.shiftDown=!0;break}this.syncInteractionState()}onKeyUp(e){let t=this.GetEngine();switch(e.keyCode){case 38:case 87:this._camerLocalDirection.z=0;break;case 37:case 65:this._camerLocalDirection.x=0;break;case 40:case 83:this._camerLocalDirection.z=0;break;case 39:case 68:this._camerLocalDirection.x=0;break;case 81:case 69:this.keydown=!1,this._camerLocalDirection.y=0;break;case 32:e.preventDefault?.(),e.stopPropagation?.(),this._isJumpKeyDown=!1;break;case 16:this.shiftDown=!1;break}t.movefirst=this._camerLocalDirection.x!==0||this._camerLocalDirection.y!==0||this._camerLocalDirection.z!==0,this.syncInteractionState()}rotateX(e){this.syncRotationStateFromCamera(),this._euler.y-=e*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this.dispatchCameraChange()}rotateY(e){this.syncRotationStateFromCamera();let t=this._euler.x-e*this.lookflag*.5*this.lookSpeed;t>=0?t<this.maxRotateX?this._euler.x=t:this._euler.x=this.maxRotateX:t>-this.maxRotateX?this._euler.x=t:this._euler.x=-this.maxRotateX,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this.dispatchCameraChange()}setLookDirection({horizontal:e,vertical:t}={}){(e===1||e===-1)&&(this.lookHorizontalFlag=e),(t===1||t===-1)&&(this.lookflag=t)}update(){const e=this.camera.position.clone(),t=this.camera.quaternion.clone();this.applyGravity&&(this.keydown=!1,this._camerLocalDirection.y=0),this.updateJump(),!this.keydown&&!this._isJumping&&this.gravityTest(),this.collisionTest(),this.syncSharedTargetFromCamera(),this.syncInteractionState(),(e.distanceToSquared(this.camera.position)>1e-12||1-Math.abs(t.dot(this.camera.quaternion))>1e-12)&&this.dispatchCameraChange()}syncRotationStateFromCamera(){this.camera&&(this.object=this.camera,this.camera.updateMatrixWorld?.(),this._euler.setFromQuaternion(this.camera.quaternion,"YZX"))}sanitizeCameraOrientation(){this.camera&&(this.syncRotationStateFromCamera(),this._euler.x=Ai.clamp(this._euler.x,-this.maxRotateX,this.maxRotateX),this._euler.z=0,this.camera.up.set(0,1,0),this.camera.quaternion.setFromEuler(this._euler),this.camera.updateMatrixWorld?.(!0))}syncSharedTargetFromCamera(){if(!this.camera)return;this.object=this.camera;let e=this.GetEngine();const t=[],n=s=>{!s?.target||t.includes(s)||t.push(s)};if(n(this),n(e?.controls),n(e?.controlModule?.orbitControls),t.length!==0){this.camera.getWorldDirection(this._lookDirection);for(const s of t){const o=this.camera.position.distanceTo(s.target);Number.isFinite(o)&&o>.001&&(this._sharedTargetDistance=o),s.target.copy(this.camera.position).addScaledVector(this._lookDirection,this._sharedTargetDistance)}}}setScreenUp(e){return!e||typeof e.x!="number"||typeof e.y!="number"||typeof e.z!="number"||!this.camera?!1:(this.camera.up.copy(e).normalize(),this.target&&this.camera.lookAt(this.target),this.camera.updateMatrixWorld?.(!0),this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera(),!0)}resetMovementState(){this._camerLocalDirection.set(0,0,0),this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1;let e=this.GetEngine();e&&(e.movefirst=!1),this.syncInteractionState()}resetMovementState(){this._camerLocalDirection.set(0,0,0),this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1;let e=this.GetEngine();e&&(e.movefirst=!1),this.syncInteractionState()}jump(){this._isJumping||(this._jumpStartHeight=this.camera.position.y,this._verticalVelocity=this.jumpSpeed,this._isJumping=!0,this.syncInteractionState())}updateJump(){if(!this._isJumping)return;this.setCameraHeight(this.camera.position.y+this._verticalVelocity),this._verticalVelocity-=this.jumpGravity;const e=this.getJumpFloorCameraHeight();this._verticalVelocity<=0&&this.camera.position.y<=e&&(this.setCameraHeight(e),this._verticalVelocity=0,this._isJumping=!1,this._fallingTime=0,this.syncInteractionState())}getJumpFloorCameraHeight(){const e=this.hitTest(new N(0,-1,0),this.playerHeight+3);if(e?.point)return e.point.y+this.playerHeight;const t=this.getMinHeight();return Math.max(this._jumpStartHeight,t??-1/0)}gravityTest(){if(!(this._camerLocalDirection.y==0&&this._camerLocalDirection.z==0&&this._camerLocalDirection.x==0))if(this.applyGravity){let e=!0;this._fallingTime+=.01,this._tmpVector.set(0,-1,0);const t=this.hitTest(this._tmpVector,this.playerHeight+3);if(t==null)return;if(t){const n=t.point.add(new N(0,this.playerHeight,0));if(this.positionEasing){if(n.y>=this.camera.position.y||n.y-this.camera.position.y<.2){this.setCameraHeight(this.camera.position.y+(n.y-this.camera.position.y)*.08),this._fallingTime=0,e=!1;return}}else t.distance<this.playerHeight&&(this.setCameraHeight(n.y),this._fallingTime=0,e=!1)}e&&this.setCameraHeight(this.camera.position.y-this.g*Math.pow(this._fallingTime,2))}else this.setCameraHeight(this.camera.position.y)}collisionTest(){this._camerLocalDirection.x!==0&&this.collisionTestX(),this._camerLocalDirection.z!==0&&this.collisionTestZ(),!this.applyGravity&&this._camerLocalDirection.y!==0&&this.collisionTestY()}collisionTestX(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.x),this._tmpVector.set(this._tmpVector.x,0,this._tmpVector.z),this._tmpVector=this._tmpVector.normalize(),this.applyCollision){const t=this.hitTest(this._tmpVector);if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1))}collisionTestZ(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.crossVectors(this.camera.up,this._tmpVector),this._tmpVector.multiplyScalar(this._camerLocalDirection.z),this._tmpVector.set(this._tmpVector.x,0,this._tmpVector.z),this._tmpVector=this._tmpVector.normalize(),this.applyCollision){const t=this.hitTest(this._tmpVector);if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1))}collisionTestY(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector=new N(0,1,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.y),this.applyCollision){const n=this.hitTest(this._tmpVector);if(n&&n.distance<.3)return}let t=this.camera.position.clone().addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1));this.setCameraHeight(t.y)}setCameraHeight(e){let t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&e<t?this.camera.position.y=t:this.camera.position.y=e}getMinHeight(){let e,t=this.GetEngine(),n=t.ToolUntils?t.ToolUntils.GetBoundingBox(t):null;return t&&n&&(e=n.min.y),e}hitTest(e=this._tmpVector,t=1/0){const n=this.camera.position.clone().add(this._rayOriginOffset);this._rayCaster.ray.origin=n,this._rayCaster.ray.direction=e,this._rayCaster.far=t;let s=this.GetEngine();var o=s.scene.ground;o&&o.material.type;let r={},A=s.handelBehaved.handle_catch(this._rayCaster,r,!1);if(this._rayCaster.far=1/0,A==null)return null;let a=A.object.name,l=A.object.url,c=s.models.find(h=>h.url==l);if(c!=null){let h=c.nodesMap.get(a);if(h.infos!=null&&h.infos.length!=0&&h.infos[0].name&&(h.infos[0].name.includes("门")||h.infos[0].name.includes("門")||h.infos[0].name.includes("door")))return null}return A}}const Rvt=bn("/assets/worker_walk.glb",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href),Nvt=Math.PI,Yvt={16:"ShiftLeft",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",65:"KeyA",68:"KeyD",69:"KeyE",81:"KeyQ",32:"Space",83:"KeyS",87:"KeyW"},Uh={forward:["KeyW","ArrowUp"],backward:["KeyS","ArrowDown"],left:["KeyA","ArrowLeft"],right:["KeyD","ArrowRight"],up:["KeyQ"],down:["KeyE"],jump:["Space"],boost:["ShiftLeft","ShiftRight"]};class G2e extends wl{constructor(e,t,n,s={}){super(),this._Engine=e,this.camera=t,this.object=t,this.domElement=n,this._isEnabled=!1,this.target=new N,this.auto=!1,this.applyGravity=s.applyGravity??!0,this.gravityMinHeight=!0,this.applyCollision=s.applyCollision??!0,this.positionEasing=!0,this.lookflag=1,this.lookHorizontalFlag=1,this.lookSpeed=s.lookSpeed??.003,this.moveSpeed=s.moveSpeed??.02,this.playerHeight=s.playerHeight??1.6,this.playerRadius=s.playerRadius??.3,this.cameraDistance=s.cameraDistance??2,this.cameraHeight=s.cameraHeight??0,this.targetHeight=s.targetHeight??this.playerHeight,this.cameraCollisionTargetHeight=s.cameraCollisionTargetHeight??this.playerHeight+.1,this.cameraCollisionInterval=Math.max(1,Math.floor(s.cameraCollisionInterval??20)),this.cameraCollisionPadding=s.cameraCollisionPadding??.15,this.minCameraCollisionDistance=s.minCameraCollisionDistance??.35,this.jumpSpeed=s.jumpSpeed??.24,this.jumpGravity=s.jumpGravity??.012,this.maxRotateX=s.maxPitch??Math.PI*.45,this.minPitch=s.minPitch??-Math.PI*.38,this.g=9.8,this._moveInput=new N,this._moveDirection=new N,this._rayCaster=new Ao,this._cameraRayCaster=new Ao,this._cameraCollisionFrame=0,this._lastCameraSafeDistance=null,this._fallingTime=0,this._isMouseInElement=!1,this._prevMouseX=0,this._prevMouseY=0,this._dragRotateThreshold=s.dragRotateThreshold??2,this._pointerLookActive=!1,this._externalLookActive=!1,this._scriptedMotionActive=!1,this._interactionActive=!1,this._yaw=0,this._pitch=s.initialPitch??0,this._pressedKeys=new Set,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this._jumpStartHeight=0,this.avatarRoot=new qn,this.avatarRoot.name="ThirdPersonAvatarRoot",this.avatarRoot.visible=s.visible??!0,this.avatarMixer=null,this.avatarWalkAction=null,this._isWalkActionPlaying=!1,this._avatarAnimationTimer=new AD,this._avatarAnimationTimer.connect(document),this._avatarLoadRequestId=0,this.defaultAvatarUrl=s.avatarUrl??Rvt,this._ownsAvatarResources=!s.avatar,this.avatar=s.avatar||this.createDefaultAvatar(),this.avatar.name=this.avatar.name||"ThirdPersonAvatar",this.avatarRoot.add(this.avatar),!s.avatar&&this.defaultAvatarUrl&&this.loadAvatarModel(this.defaultAvatarUrl,s.avatarOptions);const o=this.isPcDevice();this.bindmousedown=o?this.onMouseDown.bind(this):this.onTouchStart.bind(this),this.bindmouseup=o?this.onMouseUp.bind(this):this.onTouchEnd.bind(this),this.bindmousemove=o?this.onMouseMove.bind(this):this.onTouchMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindWindowBlur=this.onWindowBlur.bind(this),this.bindVisibilityChange=this.onVisibilityChange.bind(this),this.bindMouseEnter=this.onMouseEnter.bind(this),this.bindMouseLeave=this.onMouseLeave.bind(this),this.initAvatarPoseFromCamera()}set enabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?(this.ensureAvatarInScene(),this.syncRotationStateFromCamera(),this._avatarAnimationTimer.reset(),this.addEvents(),this.updateCameraFromAvatar()):(this.removeEvents(),this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.setScriptedMotionActive(!1),this.resetMovementState(),this.avatarRoot.visible=!1))}get enabled(){return this._isEnabled}setPointerLookActive(e){this._pointerLookActive=e===!0,this.syncInteractionState()}setExternalLookActive(e){this._externalLookActive=e===!0,this.syncInteractionState()}setScriptedMotionActive(e){this._scriptedMotionActive=e===!0,this.syncInteractionState()}syncInteractionState(){const e=this._pointerLookActive||this._externalLookActive||this._scriptedMotionActive||this.hasMoveInput()||this._isJumping;this._interactionActive!==e&&(this._interactionActive=e,this.dispatchEvent({type:e?"start":"end"}))}isPcDevice(){const e=this._Engine?.DeviceType??this._Engine?.deviceType;return e==="PC"||!e}createDefaultAvatar(){const e=new qn;return e.name="ThirdPersonEmptyAvatar",e.visible=!1,e}setAvatarModel(e,t={}){if(e){if(this.clearAvatarAnimation(),this.avatar&&(this.avatarRoot.remove(this.avatar),this._ownsAvatarResources&&this.disposeObjectResources(this.avatar)),this.avatar=e,this._ownsAvatarResources=t.ownsResources===!0,e.rotation.y+=t.yawOffset??0,t.alignToFeet!==!1){const n=new Wt().setFromObject(e),s=n.max.y-n.min.y;if(t.fitToPlayerHeight!==!1&&Number.isFinite(s)&&s>1e-6){const r=(t.targetHeight??this.playerHeight)/s;e.scale.multiplyScalar(r),n.setFromObject(e)}Number.isFinite(n.min.y)&&(e.position.y-=n.min.y)}e.traverse(n=>{(n.isMesh||n.isSkinnedMesh)&&(n.castShadow=!0,n.receiveShadow=!0,n.frustumCulled=!1)}),this.avatarRoot.add(e)}}loadAvatarModel(e,t={}){const n=++this._avatarLoadRequestId;new S1().load(e,o=>{if(n!==this._avatarLoadRequestId||!o?.scene)return;const r=o.scene;r.name="ThirdPersonWorkerAvatar",this.setAvatarModel(r,{alignToFeet:!0,fitToPlayerHeight:!0,ownsResources:!0,yawOffset:Nvt,...t}),this.setupAvatarAnimation(r,o.animations||[])},void 0,o=>{console.warn("[ThirdPersonCameraControl] failed to load avatar model",e,o)})}setupAvatarAnimation(e,t){if(!t.length)return;this.avatarMixer=new Xv(e);const n=t.find(s=>/walk|run|move/i.test(s.name))||t[0];this.avatarWalkAction=this.avatarMixer.clipAction(n),this.avatarWalkAction.enabled=!0,this.avatarWalkAction.clampWhenFinished=!1,this.avatarWalkAction.setEffectiveWeight(1),this.avatarWalkAction.paused=!0,this.avatarWalkAction.play(),this._avatarAnimationTimer.reset()}clearAvatarAnimation(){this.avatarMixer&&(this.avatarMixer.stopAllAction(),this.avatarMixer.uncacheRoot(this.avatar)),this.avatarMixer=null,this.avatarWalkAction=null,this._isWalkActionPlaying=!1}ensureAvatarInScene(){this._Engine?.scene&&(this.avatarRoot.parent||this._Engine.scene.add(this.avatarRoot),this.avatarRoot.visible=!0)}initAvatarPoseFromCamera(){if(!this.camera)return;const e=new N;this.camera.getWorldDirection(e),e.y=0,e.lengthSq()<1e-6&&e.set(0,0,-1),e.normalize(),this.setViewYaw(Math.atan2(e.x,-e.z));const t=this.targetHeight+this.cameraHeight+Math.sin(this._pitch)*this.cameraDistance,n=this.camera.position.clone().addScaledVector(e,this.cameraDistance).add(new N(0,-t,0)),s=this.getMinHeight();s!==void 0&&n.y<s&&(n.y=s),this.avatarRoot.position.copy(n),this.setViewYaw(this._yaw)}addEvents(){this.isPcDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),window.addEventListener("blur",this.bindWindowBlur,!1),document.addEventListener("visibilitychange",this.bindVisibilityChange,!1)}removeEvents(){this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove),this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),window.removeEventListener("blur",this.bindWindowBlur),document.removeEventListener("visibilitychange",this.bindVisibilityChange)}onMouseEnter(){this._isMouseInElement=!0}onMouseLeave(){this._isMouseInElement=!1,this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onWindowBlur(){this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onVisibilityChange(){document.hidden&&(this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState())}onMouseDown(e){this._isMouseInElement=!0,this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this.setPointerLookActive(!0),e.preventDefault?.(),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY}onMouseMove(e){if(!this._isEnabled)return;const t=e.screenX-this._prevMouseX,n=e.screenY-this._prevMouseY;Math.abs(t)+Math.abs(n)<this._dragRotateThreshold||(this.rotateByPointerDelta(t,n),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY)}onMouseUp(){this.updateEngineMovingFlag(),this.setPointerLookActive(!1),this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(e){const t=e.targetTouches?.[0];t&&(this._isMouseInElement=!0,this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this.setPointerLookActive(!0),e.preventDefault?.(),this._prevMouseX=t.clientX,this._prevMouseY=t.clientY)}onTouchMove(e){if(!this._isEnabled)return;const t=e.targetTouches?.[0];if(!t)return;const n=t.clientX-this._prevMouseX,s=t.clientY-this._prevMouseY;Math.abs(n)+Math.abs(s)<this._dragRotateThreshold||(this.rotateByPointerDelta(n,s),this._prevMouseX=t.clientX,this._prevMouseY=t.clientY)}onTouchEnd(){this.updateEngineMovingFlag(),this.setPointerLookActive(!1),this.domElement.removeEventListener("touchmove",this.bindmousemove)}setViewYaw(e){this._yaw=e,this.updateAvatarFacing()}getAvatarFacingYaw(){const e=-this._yaw,t=Math.sign(this._moveInput.x);return t!==0?e-t*Math.PI*.5:this._moveInput.z<0?e+Math.PI:e}updateAvatarFacing(){this.avatarRoot.rotation.y=this.getAvatarFacingYaw()}setViewPitch(e){this._pitch=Ai.clamp(e,this.minPitch,this.maxRotateX)}rotateByPointerDelta(e,t){this.setViewYaw(this._yaw+e*this.lookHorizontalFlag*this.lookSpeed),this.setViewPitch(this._pitch+t*this.lookflag*this.lookSpeed),this.updateCameraFromAvatar(),this.dispatchCameraChange()}onKeyDown(e){if(!this._isEnabled||!this._isMouseInElement)return;const t=this.getEventCode(e);if(this.isManagedKey(t)){if(e.preventDefault?.(),this.hasCodeInGroup(t,Uh.jump)){e.stopPropagation?.(),this._isJumpKeyDown||(this._isJumpKeyDown=!0,this.jump());return}this._pressedKeys.add(t),this.updateEngineMovingFlag(),this.dispatchCameraChange()}}onKeyUp(e){const t=this.getEventCode(e);if(this.isManagedKey(t)){if(e.preventDefault?.(),this.hasCodeInGroup(t,Uh.jump)){e.stopPropagation?.(),this._isJumpKeyDown=!1;return}this._pressedKeys.delete(t),this.updateEngineMovingFlag()}}getEventCode(e){return e.code||Yvt[e.keyCode]||e.key||""}hasPressed(e){return e.some(t=>this._pressedKeys.has(t))}isManagedKey(e){return this.hasCodeInGroup(e,Uh.forward)||this.hasCodeInGroup(e,Uh.backward)||this.hasCodeInGroup(e,Uh.left)||this.hasCodeInGroup(e,Uh.right)||this.hasCodeInGroup(e,Uh.up)||this.hasCodeInGroup(e,Uh.down)||this.hasCodeInGroup(e,Uh.jump)||this.hasCodeInGroup(e,Uh.boost)}hasCodeInGroup(e,t){return t.includes(e)}updateMoveInputFromKeys(){const e=(this.hasPressed(Uh.right)?1:0)-(this.hasPressed(Uh.left)?1:0),t=(this.hasPressed(Uh.forward)?1:0)-(this.hasPressed(Uh.backward)?1:0),n=this.applyGravity?0:(this.hasPressed(Uh.up)?1:0)-(this.hasPressed(Uh.down)?1:0);return this._moveInput.set(e,n,t),this._moveInput}hasMoveInput(){return this.updateMoveInputFromKeys().lengthSq()>0}updateEngineMovingFlag(){const e=this.hasMoveInput();this.updateAvatarFacing(),this._Engine&&(this._Engine.movefirst=e),this.syncInteractionState()}rotateX(e){this.setViewYaw(this._yaw-e*this.lookHorizontalFlag*this.lookSpeed),this.updateCameraFromAvatar()}rotateY(e){this.setViewPitch(this._pitch+e*this.lookflag*.5*this.lookSpeed),this.updateCameraFromAvatar()}setLookDirection({horizontal:e,vertical:t}={}){(e===1||e===-1)&&(this.lookHorizontalFlag=e),(t===1||t===-1)&&(this.lookflag=t)}update(){this._isEnabled&&(this.auto||(this.updateAvatarAnimation(),this.updateMoveInputFromKeys(),this.updateJump(),this.applyGravity&&!this._isJumping&&this.gravityTest(),this.moveAvatar(),this.updateCameraFromAvatar()))}moveAvatar(){this._moveDirection.set(0,0,0);const e=this.getFlatForward(),t=new N(-e.z,0,e.x).normalize();if(this._moveInput.z!==0&&this._moveDirection.addScaledVector(e,this._moveInput.z),this._moveInput.x!==0&&this._moveDirection.addScaledVector(t,this._moveInput.x),!this.applyGravity&&this._moveInput.y!==0&&(this._moveDirection.y+=this._moveInput.y),this._moveDirection.lengthSq()<=0){this.setAvatarWalking(!1),this.updateAvatarFacing(),this.updateEngineMovingFlag();return}this._moveDirection.normalize();const n=this.moveSpeed*(this.hasPressed(Uh.boost)?2:1);if(this.applyCollision&&this.isBlocked(this._moveDirection,n)){this.setAvatarWalking(!1),this.updateAvatarFacing(),this.updateEngineMovingFlag();return}this.avatarRoot.position.addScaledVector(this._moveDirection,n),this.updateAvatarFacing(),this.setAvatarWalking(this._moveInput.x!==0||this._moveInput.z!==0),this._Engine&&(this._Engine.movefirst=!0)}jump(){this._isJumping||(this._jumpStartHeight=this.avatarRoot.position.y,this._verticalVelocity=this.jumpSpeed,this._isJumping=!0,this.syncInteractionState())}updateJump(){if(!this._isJumping)return;this.avatarRoot.position.y+=this._verticalVelocity,this._verticalVelocity-=this.jumpGravity;const e=this.getJumpFloorHeight();this._verticalVelocity<=0&&this.avatarRoot.position.y<=e&&(this.setAvatarHeight(e),this._verticalVelocity=0,this._isJumping=!1,this._fallingTime=0,this.syncInteractionState())}getJumpFloorHeight(){const e=this.hitTest(new N(0,-1,0),this.playerHeight+3);if(e?.point)return e.point.y;const t=this.getMinHeight();return Math.max(this._jumpStartHeight,t??-1/0)}setAvatarWalking(e){!this.avatarWalkAction||this._isWalkActionPlaying===e||(this._isWalkActionPlaying=e,this.avatarWalkAction.paused=!1,e?this.avatarWalkAction.reset().fadeIn(.12).play():this.avatarWalkAction.fadeOut(.16))}updateAvatarAnimation(){this.avatarMixer&&(this._avatarAnimationTimer.update(),this.avatarMixer.update(this._avatarAnimationTimer.getDelta()))}getFlatForward(){return new N(Math.sin(this._yaw),0,-Math.cos(this._yaw)).normalize()}updateCameraFromAvatar(){if(!this.camera)return;const e=this.avatarRoot.position.clone().add(new N(0,this.targetHeight,0)),t=Math.cos(this._pitch)*this.cameraDistance,n=new N(-Math.sin(this._yaw)*t,this.cameraHeight+Math.sin(this._pitch)*this.cameraDistance,Math.cos(this._yaw)*t),s=e.clone().add(n);this.camera.position.copy(this.resolveCameraPosition(s)),this.camera.up.set(0,1,0),this.camera.lookAt(e),this.camera.updateMatrixWorld(!0),this.target.copy(e),this.syncSharedTargetFromAvatar(),this.dispatchEvent({type:"change"})}resolveCameraPosition(e){const t=this.getCameraCollisionTarget(),n=e.clone().sub(t),s=n.length();if(s<=1e-6)return e;const o=n.normalize();if(!this.shouldDetectCameraCollision()&&Number.isFinite(this._lastCameraSafeDistance))return t.clone().addScaledVector(o,Math.min(this._lastCameraSafeDistance,s));const r=this.hitCameraObstacle(t,o,s);if(!r)return this._lastCameraSafeDistance=s,e;const A=Math.max(r.distance-this.cameraCollisionPadding,this.minCameraCollisionDistance);return this._lastCameraSafeDistance=Math.min(A,s),t.clone().addScaledVector(o,this._lastCameraSafeDistance)}getCameraCollisionTarget(){return this.avatarRoot.position.clone().add(new N(0,this.cameraCollisionTargetHeight,0))}shouldDetectCameraCollision(){return this._cameraCollisionFrame+=1,Number.isFinite(this._lastCameraSafeDistance)?this._cameraCollisionFrame%this.cameraCollisionInterval===0:!0}getControlPosition(){return this.avatarRoot.position.clone()}setAvatarXZ(e,t,n={}){return!Number.isFinite(e)||!Number.isFinite(t)?!1:(this.avatarRoot.position.x=e,this.avatarRoot.position.z=t,n.updateCamera!==!1&&this.updateCameraFromAvatar(),this.dispatchCameraChange(),!0)}placeAvatarAtPoint(e,t={}){return e instanceof N?(this.avatarRoot.position.copy(e),this.setAvatarHeight(this.avatarRoot.position.y),this.syncRotationStateFromCamera(),this.setViewYaw(this._yaw),t.updateCamera!==!1&&(this.updateCameraFromAvatar(),this.dispatchCameraChange()),!0):!1}rotateYaw(e){return Number.isFinite(e)?(this.setViewYaw(this._yaw+e),this.updateCameraFromAvatar(),this.dispatchCameraChange(),!0):!1}syncAvatarFromCameraTarget(e=this.target,t={}){if(!this.camera||!(e instanceof N))return!1;this.target.copy(e),this.avatarRoot.position.set(e.x,e.y-this.targetHeight,e.z);const n=this.camera.position.clone().sub(e),s=Math.hypot(n.x,n.z);if(s>1e-6&&this.setViewYaw(Math.atan2(-n.x,n.z)),t.preserveCameraDistance!==!1){const o=n.y-this.cameraHeight,r=Math.hypot(s,o);Number.isFinite(r)&&r>1e-6&&(this.cameraDistance=r,this._pitch=Ai.clamp(Math.atan2(o,s),this.minPitch,this.maxRotateX))}else this.syncRotationStateFromCamera();return this.syncSharedTargetFromAvatar(),this.dispatchEvent({type:"change"}),!0}flyToPoint(e,t={}){if(!(e instanceof N))return!1;const n=t.duration??500,s=this.avatarRoot.position.clone(),o=this.resolveAvatarFlightTarget(e),r=performance.now();this.resetMovementState(),this.setScriptedMotionActive(!0);const A=()=>{const a=performance.now()-r,l=Math.min(a/n,1),c=l<.5?2*l*l:1-Math.pow(-2*l+2,2)/2;this.avatarRoot.position.lerpVectors(s,o,c),this.updateCameraFromAvatar(),l<1?requestAnimationFrame(A):(this.setAvatarHeight(o.y),this.updateCameraFromAvatar(),this.setScriptedMotionActive(!1))};return requestAnimationFrame(A),!0}resolveAvatarFlightTarget(e){const t=e.clone(),n=e.clone().sub(this.avatarRoot.position);n.y=0,n.lengthSq()>1e-6&&(n.normalize(),t.addScaledVector(n,-(this.playerRadius+.2)));const s=this.getMinHeight();return this.gravityMinHeight&&s!==void 0&&t.y<s&&(t.y=s),t}syncRotationStateFromCamera(){if(!this.camera)return;const e=new N;this.camera.getWorldDirection(e);const t=e.clone();t.y=0,t.lengthSq()>1e-6&&(t.normalize(),this.setViewYaw(Math.atan2(t.x,-t.z))),this.setViewPitch(-Math.asin(e.y)),this.setViewYaw(this._yaw)}syncSharedTargetFromAvatar(){const e=[],t=n=>{!n?.target||e.includes(n)||e.push(n)};t(this),t(this._Engine?.controls),t(this._Engine?.controlModule?.orbitControls);for(const n of e)n.target.copy(this.target)}setScreenUp(e){return!e||!this.camera?!1:(this.camera.up.copy(e).normalize(),this.updateCameraFromAvatar(),!0)}gravityTest(){if(!this.applyGravity){this.setAvatarHeight(this.avatarRoot.position.y);return}let e=!0;this._fallingTime+=.01;const t=this.hitTest(new N(0,-1,0),this.playerHeight+2);if(!t)return;const n=t.point.y;if(this.positionEasing){if(n>=this.avatarRoot.position.y||n-this.avatarRoot.position.y<.2){this.setAvatarHeight(this.avatarRoot.position.y+(n-this.avatarRoot.position.y)*.08),this._fallingTime=0,e=!1;return}}else t.distance<this.playerHeight&&(this.setAvatarHeight(n),this._fallingTime=0,e=!1);e&&this.setAvatarHeight(this.avatarRoot.position.y-this.g*Math.pow(this._fallingTime,2))}setAvatarHeight(e){const t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&e<t?this.avatarRoot.position.y=t:this.avatarRoot.position.y=e}getMinHeight(){const e=this._Engine?.ToolUntils?this._Engine.ToolUntils.GetBoundingBox(this._Engine):null;return e?e.min.y:void 0}isBlocked(e,t){const n=this.hitTest(e,this.playerRadius+t+.05);return!!(n&&n.distance<this.playerRadius+t+.05)}hitCameraObstacle(e,t,n){if(!this._Engine?.handelBehaved?.handle_catch)return null;this._cameraRayCaster.ray.origin.copy(e),this._cameraRayCaster.ray.direction.copy(t).normalize(),this._cameraRayCaster.far=n;const s={},o=this._Engine.handelBehaved.handle_catch(this._cameraRayCaster,s,!1);return this._cameraRayCaster.far=1/0,!o||o.distance>=n?null:o}hitTest(e,t=1/0){const n=this.avatarRoot.position.clone().add(new N(0,this.playerHeight*.5,0));this._rayCaster.ray.origin.copy(n),this._rayCaster.ray.direction.copy(e).normalize(),this._rayCaster.far=t;const s={},o=this._Engine?.handelBehaved?.handle_catch?.(this._rayCaster,s,!1);if(this._rayCaster.far=1/0,o==null)return null;const r=o.object?.name,A=o.object?.url,a=this._Engine?.models?.find?.(l=>l.url===A);if(a&&r){const c=a.nodesMap?.get?.(r)?.infos?.[0]?.name;if(c&&(c.includes("门")||c.includes("門")||c.toLowerCase().includes("door")))return null}return o}dispatchCameraChange(){const e=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(e),this.dispatchEvent({type:"change"})}resetMovementState(){this._pressedKeys.clear(),this._moveInput.set(0,0,0),this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this.updateAvatarFacing(),this.setAvatarWalking(!1),this._Engine&&(this._Engine.movefirst=!1),this.syncInteractionState()}dispose(){this.enabled=!1,this._avatarAnimationTimer.dispose(),this.avatarRoot?.parent&&this.avatarRoot.parent.remove(this.avatarRoot),this._avatarLoadRequestId++,this.clearAvatarAnimation(),this._ownsAvatarResources&&this.avatar&&this.disposeObjectResources(this.avatar)}disposeObjectResources(e){e.traverse(t=>{t.geometry&&t.geometry.dispose?.(),t.material&&(Array.isArray(t.material)?t.material.forEach(n=>n.dispose?.()):t.material.dispose?.())})}}class Gvt{constructor(e){this.engine=e}snapModelCache=new Map;applySnapPreview(e,t,n){const s=this.engine,o=e.object.url,r=e.object.name;let A=s.modelEdge.getModelEdge(o,r);A||(A=[0,0,[]]);const a=Nu(s,o),l=this.getModelSnapCache(o,r,A);s.camera.updateMatrixWorld(!0);const c=new nt().multiplyMatrices(s.camera.projectionMatrix,s.camera.matrixWorldInverse),h=s.renderer.domElement.clientWidth,d=s.renderer.domElement.clientHeight,g=new Ne(t.offsetX,t.offsetY),u=new ji,p=new N,m=new N,I=new Ne,B=new Ne,y=new N;let w="face",M=null,D=null,Q=100;if(n!=null){const b=e.point.clone(),P=e.normal||(e.face?e.face.normal:null);if(P&&e.object?.matrixWorld?.elements){const F=P.clone().transformDirection(e.object.matrixWorld).normalize(),x=new N().subVectors(n,b).dot(F),C=n.clone().sub(F.clone().multiplyScalar(x)),S=this.projectWorldPointToScreen(C,c,h,d,I,u);if(S!=null){const v=this.getDistanceSq(S.x,S.y,g.x,g.y);v<Q*4&&(Q=v,M={point:C,distanceSq:v,pointxy:S.clone(),style:"vertical"},w="point")}}}for(let b=0;b<l.localPoints.length;b+=3){if(p.set(l.localPoints[b],l.localPoints[b+1],l.localPoints[b+2]).applyMatrix4(a),s.clipping&&!s.clipping.isPointInClippingRange(p))continue;const P=this.projectWorldPointToScreen(p,c,h,d,I,u);if(P==null)continue;const F=this.getDistanceSq(P.x,P.y,g.x,g.y);F<Q&&(Q=F,M={point:p.clone(),distanceSq:F,pointxy:P.clone(),style:"rect"})}for(let b=0;b<l.localCenters.length;b+=3){if(p.set(l.localCenters[b],l.localCenters[b+1],l.localCenters[b+2]).applyMatrix4(a),s.clipping&&!s.clipping.isPointInClippingRange(p))continue;const P=this.projectWorldPointToScreen(p,c,h,d,I,u);if(P==null)continue;const F=this.getDistanceSq(P.x,P.y,g.x,g.y);F<Q&&(Q=F,M={point:p.clone(),distanceSq:F,pointxy:P.clone(),style:"default"})}if(M!=null)w="point";else{for(let b=0;b<l.localLines.length;b+=6){p.set(l.localLines[b],l.localLines[b+1],l.localLines[b+2]).applyMatrix4(a),m.set(l.localLines[b+3],l.localLines[b+4],l.localLines[b+5]).applyMatrix4(a);const P=this.projectWorldPointToScreen(p,c,h,d,I,u),F=this.projectWorldPointToScreen(m,c,h,d,B,u);if(P==null||F==null)continue;const T=this.pointToLineProjection(g,P,F),x=this.pointToLineDistanceSq(g,P,F);if(x<Q){const C=this.pointToLineProjection3D(T,p,m,c,y);if(s.clipping&&!s.clipping.isPointInClippingRange(C))continue;D={distanceSq:x,point:C.clone(),pointxy:this.projectWorldPointToScreen(C,c,h,d,I,u)?.clone()??P.clone(),start:P.clone(),end:F.clone(),style:"funnel"},Q=x}}D!=null&&(w="line")}return w==="point"&&M!=null?(this.renderPointCandidate(M),e.point=M.point,e):w==="line"&&D!=null?(this.renderLineCandidate(D),e.point=D.point,e):(this.renderFaceCandidate(e),e)}getModelSnapCache(e,t,n){const s=`${e}::${t}`,o=Array.isArray(n?.[2])?n[2]:[],r=this.snapModelCache.get(s);if(r&&r.source===o)return r;const A=new Float32Array(o.length*3),a=new Float32Array(o.length*3),l=new Float32Array(o.length*6);let c=0,h=0,d=0;o.forEach(u=>{if(u?.[0]==null||u?.[1]==null)return;const p=u[0],m=u[1];A[c++]=p.X,A[c++]=p.Z,A[c++]=-p.Y,a[h++]=(p.X+m.X)*.5,a[h++]=(p.Z+m.Z)*.5,a[h++]=(-p.Y-m.Y)*.5,l[d++]=p.X,l[d++]=p.Z,l[d++]=-p.Y,l[d++]=m.X,l[d++]=m.Z,l[d++]=-m.Y});const g={source:o,localPoints:A.subarray(0,c),localCenters:a.subarray(0,h),localLines:l.subarray(0,d)};return this.snapModelCache.set(s,g),g}projectWorldPointToScreen(e,t,n,s,o,r){if(r.set(e.x,e.y,e.z,1).applyMatrix4(t),Math.abs(r.w)<1e-10)return null;const A=1/r.w,a=r.x*A,l=r.y*A;return!Number.isFinite(a)||!Number.isFinite(l)?null:(o.set(a*n*.5+n*.5,-l*s*.5+s*.5),o)}getDistanceSq(e,t,n,s){const o=e-n,r=t-s;return o*o+r*r}pointToLineDistanceSq(e,t,n){const s=this.pointToLineProjection(e,t,n),o=t.x+(n.x-t.x)*s,r=t.y+(n.y-t.y)*s;return this.getDistanceSq(e.x,e.y,o,r)}pointToLineProjection(e,t,n){const s=new Ne().subVectors(n,t),o=s.lengthSq();if(o<1e-10)return 0;const r=new Ne().subVectors(e,t);return Ai.clamp(r.dot(s)/o,0,1)}pointToLineProjection3D(e,t,n,s,o){const r=Ai.clamp(e,0,1);if(!this.engine.camera.isPerspectiveCamera)return o.lerpVectors(t,n,r);const A=new ji(t.x,t.y,t.z,1).applyMatrix4(s),l=new ji(n.x,n.y,n.z,1).applyMatrix4(s).w*(1-r)+r*A.w,c=Math.abs(l)>1e-10?r*A.w/l:r;return o.lerpVectors(t,n,Ai.clamp(c,0,1))}renderPointCandidate(e){const t=this.engine,n=e.pointxy;t.catchSvg.innerHTML="";const s=n.x+t.reactBoundingClientRect.left,o=n.y+t.reactBoundingClientRect.top,r=document.createElementNS("http://www.w3.org/2000/svg","polygon");switch(r.setAttribute("class","catchPoint"),e.style){case"default":r.setAttribute("points",`${s},${o-8} ${s-7},${o+4} ${s+7},${o+4}`);break;case"funnel":r.setAttribute("points",`${s-7},${o-10} ${s+7},${o-10} ${s+1},${o-1} ${s},${o} ${s+7},${o+10} ${s-7},${o+10} ${s-1},${o}`);break;case"vertical":r.setAttribute("points",`${s-12},${o} ${s},${o} ${s},${o-12}`),r.setAttribute("fill","none");break;case"rect":r.setAttribute("points",`${s-8},${o-8} ${s+8},${o-8} ${s+8},${o+8} ${s-8},${o+8}`);break}r.setAttribute("stroke","rgb(8, 223, 215)"),r.setAttribute("fill","transparent"),t.catchSvg.appendChild(r)}renderLineCandidate(e){const t=this.engine,n=e.pointxy,s=e.start,o=e.end;t.catchSvg.innerHTML="";const r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("class","catchLine"),r.setAttribute("x1",(s.x+t.reactBoundingClientRect.left).toString()),r.setAttribute("y1",(s.y+t.reactBoundingClientRect.top).toString()),r.setAttribute("x2",(o.x+t.reactBoundingClientRect.left).toString()),r.setAttribute("y2",(o.y+t.reactBoundingClientRect.top).toString()),r.setAttribute("stroke","rgb(8, 223, 215)"),r.setAttribute("stroke-width","2"),t.catchSvg.appendChild(r);const A=n.x+t.reactBoundingClientRect.left,a=n.y+t.reactBoundingClientRect.top,l=document.createElementNS("http://www.w3.org/2000/svg","polygon");l.setAttribute("class","catchPoint"),l.setAttribute("points",`${A-7},${a-10} ${A+7},${a-10} ${A+1},${a-1} ${A},${a} ${A+7},${a+10} ${A-7},${a+10} ${A-1},${a}`),l.setAttribute("stroke","rgb(8, 223, 215)"),l.setAttribute("fill","transparent"),t.catchSvg.appendChild(l)}renderFaceCandidate(e){const t=this.engine,n=e.point.clone(),s=e.normal||(e.face?e.face.normal:null),o=(s?s.clone():new N(0,0,1)).normalize(),r=Math.abs(o.y)<.9?new N(0,1,0):new N(1,0,0),A=new N().crossVectors(o,r).normalize(),a=new N().crossVectors(o,A).normalize(),l=20,c=new po(t.camera,t.renderer,t.scene),h=c.worldToScreen(n),d=c.worldToScreen(new N().copy(n).add(A)),g=Math.sqrt((d.x-h.x)**2+(d.y-h.y)**2),u=g>0?l/g:.2,I=[new N().copy(A).add(a).multiplyScalar(u),new N().copy(A).sub(a).multiplyScalar(u),new N().copy(A).multiplyScalar(-1).sub(a).multiplyScalar(u),new N().copy(A).multiplyScalar(-1).add(a).multiplyScalar(u)].map(y=>new N().copy(n).add(y)).map(y=>c.worldToScreen(y));t.catchSvg.innerHTML="";const B=document.createElementNS("http://www.w3.org/2000/svg","polygon");B.setAttribute("class","catchFace"),B.setAttribute("points",I.map(y=>`${y.x+t.reactBoundingClientRect.left},${y.y+t.reactBoundingClientRect.top}`).join(" ")),B.setAttribute("fill","rgba(1, 238, 255, 0.2)"),B.setAttribute("stroke","rgb(0, 255, 247)"),B.setAttribute("stroke-width","1"),t.catchSvg.appendChild(B)}}function Nse(i){const e={self:null,options:null,mouseDownTime:0,mouseDownPosition:null,lastClickTime:0,touchLongPressTimer:null,touchLongPressActive:!1,touchLatestEvent:null,touchStartPosition:null,touchMagnifierCanvas:null,touchMagnifierContext:null,touchInputMode:null,touchPointerId:null,touchControlsSnapshot:null,mouseMoveFrame:null,latestMouseMoveEvent:null},t=800,n=28,s=132,o=44,r=168,A=new Gvt(i);e.handle_catch=function(J,W,ee=!0,q=!0){const ne=e.options;e.options={...ne??{},showCatch:ee};try{return Ae(J,W,!0,q)}finally{e.options=ne}},e.init=function(J,W){e.self!=null&&e.self.disActive!=null&&e.self.type!=J.type&&e.self.disActive(),e.self=J,W==null&&(W={showCatch:!1}),I(),e.clearLastPoint(),e.options=W,e.isClickSimpleModel=!0},e.render=function(){e.self&&e.self.render!=null&&e.self.render()};function a(){e.mouseMoveFrame!=null&&(cancelAnimationFrame(e.mouseMoveFrame),e.mouseMoveFrame=null),e.latestMouseMoveEvent=null}e.active=function(){i.renderer.domElement.addEventListener("mousedown",C),i.renderer.domElement.addEventListener("mouseup",v),i.renderer.domElement.addEventListener("mousemove",S),i.renderer.domElement.addEventListener("touchstart",O,{capture:!0,passive:!1}),i.renderer.domElement.addEventListener("touchend",$,{capture:!0,passive:!1}),i.renderer.domElement.addEventListener("touchcancel",$,{capture:!0,passive:!1}),i.renderer.domElement.addEventListener("touchmove",V,{capture:!0,passive:!1}),i.renderer.domElement.addEventListener("pointerdown",z,!0),i.renderer.domElement.addEventListener("pointermove",ie,!0),i.renderer.domElement.addEventListener("pointerup",te,!0),i.renderer.domElement.addEventListener("pointercancel",te,!0),window.addEventListener("keydown",l),window.addEventListener("keyup",c)},e.disActive=function(){I(),a(),P(),i.renderer.domElement.removeEventListener("mousedown",C),i.renderer.domElement.removeEventListener("mouseup",v),i.renderer.domElement.removeEventListener("mousemove",S),i.renderer.domElement.removeEventListener("touchstart",O,!0),i.renderer.domElement.removeEventListener("touchend",$,!0),i.renderer.domElement.removeEventListener("touchcancel",$,!0),i.renderer.domElement.removeEventListener("touchmove",V,!0),i.renderer.domElement.removeEventListener("pointerdown",z,!0),i.renderer.domElement.removeEventListener("pointermove",ie,!0),i.renderer.domElement.removeEventListener("pointerup",te,!0),i.renderer.domElement.removeEventListener("pointercancel",te,!0),window.removeEventListener("keydown",l),window.removeEventListener("keyup",c)};function l(J){(J.keyCode===8||J.keyCode===46)&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),J.keyCode===27&&e.self&&e.self.handelKeyEscDown!=null&&e.self.handelKeyEscDown(),J.keyCode===13&&e.self&&e.self.handelKeyEnterDown!=null&&e.self.handelKeyEnterDown(),J.keyCode===32&&e.self&&e.self.handelKeySpaceDown!=null&&e.self.handelKeySpaceDown(J),J.key==="Tab"&&e.self&&e.self.handelKeyTabDown!=null&&e.self.handelKeyTabDown(J),J.key==="Control"&&e.self&&e.self.handelKeyCtrlDown!=null&&e.self.handelKeyCtrlDown(),J.key==="Delete"&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),J.key==="Shift"&&e.self&&e.self.handelKeyShiftDown!=null&&e.self.handelKeyShiftDown(),J.key==="Meta"&&e.self&&e.self.handelKeyMetaDown!=null&&e.self.handelKeyMetaDown()}function c(J){J.key==="Alt"&&e.self&&e.self.handelKeyAltUp!=null&&e.self.handelKeyAltUp(),J.key==="Tab"&&e.self&&e.self.handelKeyTabUp!=null&&e.self.handelKeyTabUp(),J.key==="Control"&&e.self&&e.self.handelKeyCtrlUp!=null&&e.self.handelKeyCtrlUp(),J.key==="Shift"&&e.self&&e.self.handelKeyShiftUp!=null&&e.self.handelKeyShiftUp(),J.key==="Meta"&&e.self&&e.self.handelKeyMetaUp!=null&&e.self.handelKeyMetaUp(),J.key==="Command"&&e.self&&e.self.handelKeyCommandUp!=null&&e.self.handelKeyCommandUp(),J.key==="Windows"&&e.self&&e.self.handelKeyWindowsUp!=null&&e.self.handelKeyWindowsUp()}function h(J){const W=new Ne,ee=i.renderer.domElement.clientWidth,q=i.renderer.domElement.clientHeight;return W.x=J.offsetX/ee*2-1,W.y=-(J.offsetY/q)*2+1,W}function d(J){const W=new Ao,ee=h(J);return W.setFromCamera(ee,i.camera),W}function g(){return i?.deviceModule?.isMobile?.()===!0||i?.deviceType==="mobile"}function u(){return g()&&e.options?.showCatch===!0}function p(J){const W=typeof TouchEvent<"u"&&J?.originalEvent instanceof TouchEvent;return u()&&!W}function m(){e.touchLongPressTimer!=null&&(clearTimeout(e.touchLongPressTimer),e.touchLongPressTimer=null)}function I(){m(),b(),w(),e.touchLongPressActive=!1,e.touchLatestEvent=null,e.touchStartPosition=null,e.touchInputMode=null,e.touchPointerId=null}function B(J){J?.preventDefault?.(),J?.stopPropagation?.(),J?.stopImmediatePropagation?.()}function y(){const J=i?.controls;!J||e.touchControlsSnapshot||(e.touchControlsSnapshot={controls:J,enabled:J.enabled!==!1},J.enabled=!1)}function w(){const J=e.touchControlsSnapshot;J&&(J.controls&&(M(J.controls),J.controls.enabled=J.enabled),e.touchControlsSnapshot=null)}function M(J){J?._pointers?.clear?.(),typeof J?.state=="number"&&(J.state=-1),J._isInteracting=!1,J._touchDistance=0,e.touchPointerId!=null&&J.domElement?.releasePointerCapture?.(e.touchPointerId)}function D(J){const W=J.touches[0]||J.changedTouches[0];return W?new Ne(W.clientX,W.clientY):null}function Q(){if(e.touchMagnifierCanvas)return e.touchMagnifierCanvas;const J=document.createElement("canvas"),W=Math.max(1,window.devicePixelRatio||1);return J.width=s*W,J.height=s*W,J.style.position="fixed",J.style.width=`${s}px`,J.style.height=`${s}px`,J.style.borderRadius="50%",J.style.border="2px solid rgba(0, 255, 247, 0.95)",J.style.boxShadow="0 8px 22px rgba(0, 0, 0, 0.32)",J.style.pointerEvents="none",J.style.zIndex="1002",J.style.display="none",J.style.background="#111",document.body.appendChild(J),e.touchMagnifierCanvas=J,e.touchMagnifierContext=J.getContext("2d"),J}function b(){const J=e.touchMagnifierCanvas;J&&(J.style.display="none")}function P(){e.touchMagnifierCanvas?.remove?.(),e.touchMagnifierCanvas=null,e.touchMagnifierContext=null}function F(J,W,ee,q,ne,Z){const K=i?.catchSvg;if(!K?.childElementCount)return;const re=i?.reactBoundingClientRect??W.getBoundingClientRect(),ue=le=>{const[ae,he]=le.split(",").map(Number);return Number.isFinite(ae)&&Number.isFinite(he)?[(ae-re.left-ee)/ne*s*Z,(he-re.top-q)/ne*s*Z]:null};Array.from(K.children).forEach(le=>{const ae=le.tagName.toLowerCase(),De=(ae==="line"?[`${le.getAttribute("x1")},${le.getAttribute("y1")}`,`${le.getAttribute("x2")},${le.getAttribute("y2")}`].map(ue):(le.getAttribute("points")||"").trim().split(/\s+/).map(ue)).filter(Boolean);De.length<2||(J.beginPath(),J.strokeStyle=le.getAttribute("stroke")||"rgb(8, 223, 215)",J.fillStyle=le.getAttribute("fill")||"transparent",J.lineWidth=Number(le.getAttribute("stroke-width")||2)*Z,J.moveTo(De[0][0],De[0][1]),De.slice(1).forEach(([Fe,Qe])=>J.lineTo(Fe,Qe)),ae==="polygon"&&(J.closePath(),["none","transparent"].includes(String(J.fillStyle))||J.fill()),J.stroke())})}function T(J){const W=i?.renderer?.domElement,ee=Q(),q=e.touchMagnifierContext;if(!W||!ee||!q)return;const ne=J?.catch?.point,Z=ne&&(i?.worldToScreen??new po(i.camera,i.renderer,i.scene)),K=Z?.worldToScreenIfVisible?.(ne)??Z?.worldToScreen?.(ne);if(!K||!Number.isFinite(K.x)||!Number.isFinite(K.y)||K.x<0||K.y<0||K.x>W.clientWidth||K.y>W.clientHeight){b();return}const re=ee.width/s,ue=Math.min(window.innerWidth-s/2-8,Math.max(s/2+8,J.clientX)),le=Math.min(window.innerHeight-s-8,Math.max(8,J.clientY-r));ee.style.left=`${ue-s/2}px`,ee.style.top=`${le}px`,ee.style.display="block";const ae=W.width/Math.max(1,W.clientWidth),he=W.height/Math.max(1,W.clientHeight),De=o,Fe=Math.max(0,Math.min(W.clientWidth-De,K.x-De/2)),Qe=Math.max(0,Math.min(W.clientHeight-De,K.y-De/2));q.save(),q.clearRect(0,0,ee.width,ee.height),q.beginPath(),q.arc(ee.width/2,ee.height/2,ee.width/2,0,Math.PI*2),q.clip(),q.fillStyle=window.getComputedStyle(W.parentElement??document.body).backgroundColor||"#dfe8f2",q.fillRect(0,0,ee.width,ee.height);try{q.drawImage(W,Fe*ae,Qe*he,De*ae,De*he,0,0,ee.width,ee.height),F(q,W,Fe,Qe,De,re)}catch{b(),q.restore();return}q.strokeStyle="rgba(0, 255, 247, 0.9)",q.lineWidth=1.5*re,q.beginPath(),q.moveTo(ee.width/2-10*re,ee.height/2),q.lineTo(ee.width/2+10*re,ee.height/2),q.moveTo(ee.width/2,ee.height/2-10*re),q.lineTo(ee.width/2,ee.height/2+10*re),q.stroke(),q.restore()}function x(J,W=!1,ee=!1,q=!0){const ne=d(J);if(J.raycaster=ne,W){const Z=Ae(ne,J,ee,q);J.catch=Z}}function C(J){p(J)||(e.mouseDownTime=Date.now(),e.mouseDownPosition=new N(J.offsetX,J.offsetY,0),e.self&&e.self.handleMouseDown!=null&&J.button==0&&(x(J,!0,!0),J.catch!=null&&(i.engineStatus.highlightModels==null||i.engineStatus.highlightModels.length==0)&&(i.engineStatus?.suppressNextOrbitOriginPick===!0?i.engineStatus.suppressNextOrbitOriginPick=!1:i.controlModule.orbitControls.origin.set(J.catch.point.x,J.catch.point.y,J.catch.point.z)),e.self.handleMouseDown(J)))}function S(J){p(J)||e.self&&e.self.handleMouseMove!=null&&(e.latestMouseMoveEvent=J,e.mouseMoveFrame==null&&(e.mouseMoveFrame=requestAnimationFrame(()=>{const W=e.latestMouseMoveEvent;e.latestMouseMoveEvent=null,e.mouseMoveFrame=null,W&&(i.engineStatus.isFree&&x(W,!0,!0,e.isClickSimpleModel),e.self.handleMouseMove(W))})))}function v(J){if(p(J))return;const W=Date.now(),ee=W-e.mouseDownTime,q=new N(J.offsetX,J.offsetY,0);e.self&&e.self.handleMouseUp!=null&&J.button==0&&(x(J,!1,!1,!1),e.self.handleMouseUp(J));const ne=q.distanceTo(e.mouseDownPosition);(ee<100||ne==0)&&e.self&&e.self.handleMouseClick!=null&&(x(J,!0,!0,!1),W-e.lastClickTime<200?e.self.handleMouseDoubleClick!=null&&J.button==0&&e.self.handleMouseDoubleClick(J):e.self.handleMouseClick!=null&&J.button==0?e.self.handleMouseClick(J):e.self.handleRightMouseClick!=null&&J.button==2&&e.self.handleRightMouseClick(J),e.lastClickTime=Date.now())}function Y(J){const W=J.touches[0]||J.changedTouches[0];if(!W)return null;const q=i.renderer.domElement.getBoundingClientRect(),ne=W.clientX-q.left,Z=W.clientY-q.top;return{offsetX:ne,offsetY:Z,button:0,clientX:W.clientX,clientY:W.clientY,preventDefault:()=>J.preventDefault(),stopPropagation:()=>J.stopPropagation(),originalEvent:J}}function k(J){const ee=i.renderer.domElement.getBoundingClientRect();return{offsetX:J.clientX-ee.left,offsetY:J.clientY-ee.top,button:J.button??0,clientX:J.clientX,clientY:J.clientY,preventDefault:()=>J.preventDefault(),stopPropagation:()=>J.stopPropagation(),originalEvent:J}}function j(J,W,ee,q=null){I(),e.touchInputMode=ee,e.touchPointerId=q,e.touchLatestEvent=J,e.touchStartPosition=W,e.touchLongPressTimer=window.setTimeout(()=>{const ne=e.touchLatestEvent;ne&&(e.touchLongPressActive=!0,y(),e.mouseDownTime=Date.now(),e.mouseDownPosition=new N(ne.offsetX,ne.offsetY,0),e.self?.handleMouseMove!=null&&(x(ne,!0,!0,e.isClickSimpleModel),e.self.handleMouseMove(ne)),T(ne))},t)}function R(J,W){e.touchLatestEvent=J;const ee=e.touchStartPosition;!e.touchLongPressActive&&ee&&W&&ee.distanceTo(W)>n&&m(),e.touchLongPressActive&&(e.self?.handleMouseMove!=null&&(x(J,!0,!0,e.isClickSimpleModel),e.self.handleMouseMove(J)),T(J))}function U(J){m(),e.touchLongPressActive&&(x(J,!0,!0,e.isClickSimpleModel),e.self?.handleMouseClick!=null&&e.self.handleMouseClick(J),e.self?.handleMouseUp!=null&&e.self.handleMouseUp(J)),I()}function O(J){if(J.preventDefault(),J.touches.length!==1){I();return}const W=Y(J);if(W){if(u()){j(W,D(J)??new Ne(W.clientX,W.clientY),"touch");return}C(W)}}function V(J){if(J.preventDefault(),J.touches.length!==1){I();return}const W=Y(J);if(W){if(u()){e.touchLongPressActive&&B(J),R(W,D(J));return}S(W)}}function $(J){J.preventDefault();const W=Y(J);if(W){if(u()){e.touchLongPressActive&&B(J),U(W);return}v(W)}}function z(J){if(J.pointerType!=="touch"||!u()||J.isPrimary===!1)return;const W=k(J);j(W,new Ne(J.clientX,J.clientY),"pointer",J.pointerId)}function ie(J){J.pointerType!=="touch"||!u()||(e.touchLongPressActive&&B(J),e.touchInputMode==="pointer"&&(e.touchPointerId!=null&&J.pointerId!==e.touchPointerId||R(k(J),new Ne(J.clientX,J.clientY))))}function te(J){J.pointerType!=="touch"||!u()||(e.touchLongPressActive&&B(J),e.touchInputMode==="pointer"&&(e.touchPointerId!=null&&J.pointerId!==e.touchPointerId||U(k(J))))}function Ae(J,W,ee=!1,q=!0){if(!i.engineStatus.isFree&&ee==!1){i.hoverHighLight.clearHighlight();return}if(i.engineStatus.editorMode=="simple")return;i.catchSvg.innerHTML="";let ne=i.octreeBox.rayInterationModel(J,ee,q);if(ne=i.clipping?.filterIntersectionsByClipping(ne)??ne,ne.length!==0)return e.options.showCatch?A.applySnapPreview(ne[0],W,e.lastPoint):ne[0]}return e.setLastPoint=function(J){e.lastPoint=J},e.clearLastPoint=function(){e.lastPoint=null},e}class jvt{engine;orbitControls;firstPersonControls;thirdPersonControls;isActive=!0;originDiv=null;mobileRoamControlsEl=null;mobileMovePointerId=null;mobileMoveActiveKeys=new Set;mobileMoveIntensity=0;mobileMoveSpeedBase=new WeakMap;mobileLookPointerId=null;mobileLookOffset={x:0,y:0};handelBehaved;pendingThirdPersonOptions=null;prevContainerCursor=null;roamLookDirection={horizontal:1,vertical:1};isDragging=!1;isDown=!1;containerOffset={left:0,top:0};constructor(e){this.engine=e,this.init(),this.handelBehaved=Nse(this.engine),this.handelBehaved.init(this,null),this.handelBehaved.active()}init(){this.orbitControls=new N2e(this.engine,this.engine.camera,this.engine.renderer.domElement),this.orbitControls.showOriginIcon=!0,this.firstPersonControls=new Y2e(this.engine,this.engine.camera,this.engine.renderer.domElement),this.thirdPersonControls=new G2e(this.engine,this.engine.camera,this.engine.renderer.domElement),this.applyRoamLookDirection(this.firstPersonControls),this.applyRoamLookDirection(this.thirdPersonControls);const e=document.createElement("div");this.originDiv=e,e.className="originDiv",e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.width="30px",e.style.height="30px",e.style.borderRadius="50%",e.style.pointerEvents="none",e.style.backgroundImage=`url(${bn("/assets/svg/rotate-orbit.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href)})`,this.engine.container.appendChild(this.originDiv)}active(){this.isActive=!0,this.orbitControls.enabled=!0}disActive(){this.isActive=!1,this.orbitControls.enabled=!1}setEngineControls(e){this.engine.controls=e,this.engine.bindControlEvents?.(e)}setMoveSpeed(e){const t=e*.1;this.firstPersonControls&&(this.firstPersonControls.moveSpeed=t,this.setMobileMoveBaseSpeed(this.firstPersonControls,t)),this.thirdPersonControls&&(this.thirdPersonControls.moveSpeed=t,this.setMobileMoveBaseSpeed(this.thirdPersonControls,t))}getMoveSpeed(){const e=this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls;return this.getMobileMoveBaseSpeed(e)*10}setApplyCollision(e){this.firstPersonControls&&(this.firstPersonControls.applyCollision=e),this.thirdPersonControls&&(this.thirdPersonControls.applyCollision=e)}getApplyCollision(){return(this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls)?.applyCollision}setApplyGravity(e){this.firstPersonControls&&(this.firstPersonControls.applyGravity=e),this.thirdPersonControls&&(this.thirdPersonControls.applyGravity=e),this.updateMobileVerticalControlsVisibility()}getApplyGravity(){return(this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls)?.applyGravity}setRoamLookDirection(e){(e?.horizontal===1||e?.horizontal===-1)&&(this.roamLookDirection.horizontal=e.horizontal),(e?.vertical===1||e?.vertical===-1)&&(this.roamLookDirection.vertical=e.vertical),this.applyRoamLookDirection(this.firstPersonControls),this.applyRoamLookDirection(this.thirdPersonControls)}getRoamLookDirection(){return{...this.roamLookDirection}}applyRoamLookDirection(e){e?.setLookDirection?.(this.roamLookDirection)}toggleMinMap(){this.engine.minMap.toggle()}switchFirstPersonMode(){this.engine.cameraModule.switchToPerspectiveCamera(),this.firstPersonControls&&(this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1),this.firstPersonControls=new Y2e(this.engine,this.engine.camera,this.engine.renderer.domElement,[]),this.applyRoamLookDirection(this.firstPersonControls),this.orbitControls.enabled=!1,this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!0,this.firstPersonControls.isActive=!0,this.firstPersonControls.syncRotationStateFromCamera?.(),this.firstPersonControls.syncSharedTargetFromCamera?.(),this.setEngineControls(this.firstPersonControls),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene),this.ensureMobileRoamControls()}switchThirdPersonMode(e){this.firstPersonControls&&(this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1),this.beginThirdPersonPlacement(e)}createThirdPersonControl(e){const t=this.thirdPersonControls,n={moveSpeed:t?.moveSpeed,applyCollision:t?.applyCollision,applyGravity:t?.applyGravity};return t?.dispose?.(),this.thirdPersonControls=new G2e(this.engine,this.engine.camera,this.engine.renderer.domElement,{...n,...e}),this.applyRoamLookDirection(this.thirdPersonControls),this.thirdPersonControls}beginThirdPersonPlacement(e){this.pendingThirdPersonOptions=e||{},this.orbitControls.enabled=!0,this.setEngineControls(this.orbitControls),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene),this.removeMobileRoamControls(),this.engine.container&&(this.prevContainerCursor=this.engine.container.style.cursor||"",this.engine.container.style.cursor="crosshair")}isWaitingThirdPersonPlacement(){return this.pendingThirdPersonOptions!=null}applyThirdPersonPlacement(e){if(!this.pendingThirdPersonOptions||!(e instanceof N))return!1;const t=this.pendingThirdPersonOptions;this.pendingThirdPersonOptions=null,this.engine.container&&this.prevContainerCursor!=null&&(this.engine.container.style.cursor=this.prevContainerCursor),this.prevContainerCursor=null,this.engine.cameraModule.switchToPerspectiveCamera();const n=this.createThirdPersonControl(t);return n.placeAvatarAtPoint?.(e,{updateCamera:!1}),this.orbitControls.enabled=!1,n.enabled=!0,n.isActive=!0,n.placeAvatarAtPoint?.(e),this.setEngineControls(n),this.engine.minMap?.show?.(),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene),this.ensureMobileRoamControls(),!0}setThirdPersonAvatar(e,t){this.thirdPersonControls?.setAvatarModel?.(e,t)}setThirdPersonMoveSpeed(e){this.thirdPersonControls&&(this.thirdPersonControls.moveSpeed=e*.1,this.setMobileMoveBaseSpeed(this.thirdPersonControls,this.thirdPersonControls.moveSpeed))}setThirdPersonApplyCollision(e){this.thirdPersonControls&&(this.thirdPersonControls.applyCollision=e)}setThirdPersonApplyGravity(e){this.thirdPersonControls&&(this.thirdPersonControls.applyGravity=e),this.updateMobileVerticalControlsVisibility()}getOrbitTargetFromCamera(e=10){const t=this.engine.camera,n=new N;return t.getWorldDirection(n),n.lengthSq()<=1e-8&&n.set(0,0,-1),t.position.clone().add(n.normalize().multiplyScalar(e))}switchDefaultMode(e){const t=e?.preserveCameraPose===!0;this.pendingThirdPersonOptions=null,this.engine.container&&this.prevContainerCursor!=null&&(this.engine.container.style.cursor=this.prevContainerCursor),this.prevContainerCursor=null,this.firstPersonControls&&(t||this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1);const n=this.engine.camera,s=t?this.orbitControls.target.clone():this.getOrbitTargetFromCamera(10),o=t&&this.orbitControls.origin?.clone?this.orbitControls.origin.clone():s.clone(),r=t&&this.orbitControls._referenceUp?.clone?this.orbitControls._referenceUp.clone():void 0,A=t&&this.orbitControls._viewRight?.clone?this.orbitControls._viewRight.clone():void 0;this.orbitControls.object=n,this.orbitControls.target.copy(s),this.orbitControls.syncStateFromCamera?.(n,s,{origin:o,referenceUp:r,viewRight:A}),this.orbitControls.enabled=!0,this.setEngineControls(this.orbitControls),this.orbitControls.update(!0),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene),this.removeMobileRoamControls()}handleMouseUp(e){this.isDragging=!1,this.isDown=!1}handleMouseMove(e){this.isDown?this.isDragging=!0:this.isDragging=!1}handleMouseDown(e){this.isDown=!0}handleMouseClick(e){this.isDragging=!1,this.isDown=!1}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getActiveRoamControl(){return this.firstPersonControls?.enabled?this.firstPersonControls:this.thirdPersonControls?.enabled?this.thirdPersonControls:null}getMobileMoveBaseSpeed(e){return!e||typeof e.moveSpeed!="number"?0:(this.mobileMoveSpeedBase.has(e)||this.mobileMoveSpeedBase.set(e,e.moveSpeed),this.mobileMoveSpeedBase.get(e)??e.moveSpeed)}setMobileMoveBaseSpeed(e,t){!e||typeof t!="number"||this.mobileMoveSpeedBase.set(e,t)}restoreMobileMoveSpeed(){[this.firstPersonControls,this.thirdPersonControls].forEach(e=>{e&&typeof e.moveSpeed=="number"&&this.mobileMoveSpeedBase.has(e)&&(e.moveSpeed=this.mobileMoveSpeedBase.get(e)??e.moveSpeed)})}updateMobileMoveSpeed(){const e=this.getActiveRoamControl();if(!e||typeof e.moveSpeed!="number")return;const t=this.getMobileMoveBaseSpeed(e);if(this.mobileMovePointerId==null||this.mobileMoveActiveKeys.size===0||this.mobileMoveIntensity<=0){e.moveSpeed=t;return}const n=.25;e.moveSpeed=t*(n+(1-n)*this.mobileMoveIntensity)}createVirtualKeyEvent(e,t){const s={w:{keyCode:87,code:"KeyW",key:"w"},a:{keyCode:65,code:"KeyA",key:"a"},s:{keyCode:83,code:"KeyS",key:"s"},d:{keyCode:68,code:"KeyD",key:"d"},q:{keyCode:81,code:"KeyQ",key:"q"},e:{keyCode:69,code:"KeyE",key:"e"}}[e];return{key:s.key,code:s.code,keyCode:s.keyCode,type:t?"keydown":"keyup",preventDefault(){},stopPropagation(){}}}setVirtualKey(e,t){const n=this.getActiveRoamControl();if(!n||!e)return;n._isMouseInElement=!0;const s=this.createVirtualKeyEvent(e,t);t?n.onKeyDown?.(s):n.onKeyUp?.(s)}updateMobileMoveKeys(e){const t=new Set(e);this.mobileMoveActiveKeys.forEach(n=>{t.has(n)||this.setVirtualKey(n,!1)}),t.forEach(n=>{this.mobileMoveActiveKeys.has(n)||this.setVirtualKey(n,!0)}),this.mobileMoveActiveKeys=t}releaseMobileMoveKeys(){this.mobileMoveIntensity=0,this.updateMobileMoveKeys([]),this.restoreMobileMoveSpeed()}bindVirtualButton(e,t){let n=!1,s=null;const o=()=>{n&&(n=!1,s=null,e.classList.remove("is-active"),this.setVirtualKey(t,!1))},r=a=>{a.preventDefault(),a.stopPropagation(),!n&&(n=!0,s=a.pointerId,e.classList.add("is-active"),e.setPointerCapture?.(a.pointerId),this.setVirtualKey(t,!0))},A=a=>{a.preventDefault(),a.stopPropagation(),!(!n||s!==a.pointerId)&&(e.releasePointerCapture?.(a.pointerId),o())};e.addEventListener("pointerdown",r),e.addEventListener("pointerup",A),e.addEventListener("pointercancel",A),e.addEventListener("lostpointercapture",o)}createMobileRoamButton(e,t,n=""){const s=document.createElement("button");return s.type="button",s.className=`bim-mobile-roam-button ${n}`.trim(),s.innerHTML=e,s.setAttribute("aria-label",t==="q"?"Move up":t==="e"?"Move down":e),this.bindVirtualButton(s,t),s}bindMovePad(e){const t=e.querySelector(".bim-mobile-roam-move-knob"),n=o=>{const r=e.getBoundingClientRect(),A=Math.min(r.width,r.height)*.5,a=A*.48,l=A*.22,c=o.clientX-r.left-A,h=o.clientY-r.top-A,d=Math.hypot(c,h),g=Math.min(d,a),u=d>a?a/d:1,p=c*u,m=h*u;t&&(t.style.transform=`translate(${p}px, ${m}px)`);const I=[];h<-l?I.push("w"):h>l&&I.push("s"),c<-l?I.push("a"):c>l&&I.push("d"),this.mobileMoveIntensity=I.length===0?0:Math.max(0,Math.min(1,(g-l)/(a-l))),this.updateMobileMoveKeys(I)};e.addEventListener("pointerdown",o=>{o.preventDefault(),o.stopPropagation(),this.mobileMovePointerId=o.pointerId,e.classList.add("is-active"),e.setPointerCapture?.(o.pointerId),n(o)}),e.addEventListener("pointermove",o=>{this.mobileMovePointerId===o.pointerId&&(o.preventDefault(),o.stopPropagation(),n(o))});const s=o=>{this.mobileMovePointerId===o.pointerId&&(o.preventDefault(),o.stopPropagation(),e.classList.remove("is-active"),e.releasePointerCapture?.(o.pointerId),this.mobileMovePointerId=null,t&&(t.style.transform=""),this.releaseMobileMoveKeys())};e.addEventListener("pointerup",s),e.addEventListener("pointercancel",s)}rotateActiveRoamView(e,t){const n=this.getActiveRoamControl();n&&(typeof n.rotateByPointerDelta=="function"?n.rotateByPointerDelta(e,t):(n.rotateX?.(e),n.rotateY?.(t*2),n.dispatchEvent?.({type:"change"}),window.dispatchEvent(new CustomEvent("bimengine:camerachange",{detail:""}))))}updateMobileLookRotation(){if(this.mobileLookPointerId==null||this.mobileLookOffset.x===0&&this.mobileLookOffset.y===0)return;const e=2.8;this.rotateActiveRoamView(this.mobileLookOffset.x*e,this.mobileLookOffset.y*e)}updateMobileVerticalControlsVisibility(){const e=this.mobileRoamControlsEl?.querySelector(".bim-mobile-roam-vertical-pad");e&&(e.style.display=this.getActiveRoamControl()?.applyGravity?"none":"flex")}ensureMobileRoamControls(){if(!this.isMobileDevice()){this.removeMobileRoamControls();return}if(this.mobileRoamControlsEl){this.mobileMovePointerId=null,this.releaseMobileMoveKeys(),this.mobileLookPointerId=null,this.mobileLookOffset={x:0,y:0},this.getActiveRoamControl()?.setExternalLookActive?.(!1),this.mobileRoamControlsEl.querySelectorAll(".is-active").forEach(o=>o.classList.remove("is-active")),this.mobileRoamControlsEl.querySelectorAll(".bim-mobile-roam-look-knob, .bim-mobile-roam-move-knob").forEach(o=>o.style.transform=""),this.firstPersonControls?.resetMovementState?.(),this.thirdPersonControls?.resetMovementState?.(),this.mobileRoamControlsEl.style.display="flex",this.updateMobileVerticalControlsVisibility();return}const e=document.createElement("div");e.className="bim-mobile-roam-controls",e.addEventListener("contextmenu",o=>o.preventDefault());const t=document.createElement("div");t.className="bim-mobile-roam-pad bim-mobile-roam-move-pad";const n=document.createElement("span");n.className="bim-mobile-roam-move-knob",t.appendChild(n),this.bindMovePad(t);const s=document.createElement("div");s.className="bim-mobile-roam-vertical-pad",s.appendChild(this.createMobileRoamButton("&#8593;","q","is-round")),s.appendChild(this.createMobileRoamButton("&#8595;","e","is-round")),e.appendChild(t),e.appendChild(s),this.engine.container.appendChild(e),this.mobileRoamControlsEl=e,this.updateMobileVerticalControlsVisibility()}removeMobileRoamControls(){this.mobileMovePointerId=null,this.releaseMobileMoveKeys(),this.mobileLookPointerId=null,this.mobileLookOffset={x:0,y:0},this.getActiveRoamControl()?.setExternalLookActive?.(!1),this.mobileRoamControlsEl&&(this.mobileRoamControlsEl.remove(),this.mobileRoamControlsEl=null),this.firstPersonControls?.resetMovementState?.(),this.thirdPersonControls?.resetMovementState?.()}update(){if(this.updateMobileMoveSpeed(),this.updateMobileLookRotation(),this.firstPersonControls.enabled&&this.firstPersonControls.update(),this.thirdPersonControls?.enabled&&this.thirdPersonControls.update(),this.orbitControls.enabled){const e=this.engine.controlModule.orbitControls.origin,n=this.engine.worldToScreen.worldToScreen(e);this.originDiv&&this.isDragging?(this.originDiv.style.left=n.x-15+this.engine.reactBoundingClientRect.left+"px",this.originDiv.style.top=n.y-15+this.engine.reactBoundingClientRect.top+"px",this.originDiv.style.display="block"):this.originDiv&&(this.originDiv.style.display="none")}}dispose(){this.isActive=!1,this.handelBehaved?.disActive?.(),this.orbitControls?.dispose?.(),this.firstPersonControls?.dispose?.(),this.thirdPersonControls?.dispose?.(),this.removeMobileRoamControls(),this.originDiv?.remove(),this.originDiv=null,this.orbitControls=null,this.firstPersonControls=null,this.thirdPersonControls=null,this.handelBehaved=null}}const xS={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
5980
+ `,c},e.publicKeyToOpenSSH=function(o,r){var A="ssh-rsa";r=r||"";var a=i.util.createBuffer();return n(a,A),t(a,o.e),t(a,o.n),A+" "+i.util.encode64(a.bytes())+" "+r},e.privateKeyToOpenSSH=function(o,r){return r?i.pki.encryptRsaPrivateKey(o,r,{legacy:!0,algorithm:"aes128"}):i.pki.privateKeyToPem(o)},e.getPublicKeyFingerprint=function(o,r){r=r||{};var A=r.md||i.md.md5.create(),a="ssh-rsa",l=i.util.createBuffer();n(l,a),t(l,o.e),t(l,o.n),A.start(),A.update(l.getBytes());var c=A.digest();if(r.encoding==="hex"){var h=c.toHex();return r.delimiter?h.match(/.{2}/g).join(r.delimiter):h}else{if(r.encoding==="binary")return c.getBytes();if(r.encoding)throw new Error('Unknown encoding "'+r.encoding+'".')}return c};function t(o,r){var A=r.toString(16);A[0]>="8"&&(A="00"+A);var a=i.util.hexToBytes(A);o.putInt32(a.length),o.putBytes(a)}function n(o,r){o.putInt32(r.length),o.putString(r)}function s(){for(var o=i.md.sha1.create(),r=arguments.length,A=0;A<r;++A)o.update(arguments[A]);return o.digest()}return Dse.exports}var Sse,D2e;function hvt(){return D2e||(D2e=1,Sse=ao(),DS(),nvt(),xC(),Wne(),GX(),ovt(),vY(),rvt(),Avt(),avt(),A2e(),nse(),p_(),q_e(),d2e(),lvt(),u2e(),e2e(),K_e(),mse(),bI(),Z_e(),cvt(),p2e(),Br()),Sse}var xse=hvt();const dvt="evtrsa1",Tse=new Map;function S2e(i){return i.replace(/\/+$/,"")}function gvt(i){return new TextEncoder().encode(i)}function LX(i){let e="";return i.forEach(t=>{e+=String.fromCharCode(t)}),btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function uvt(i,e){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),e):void 0;try{const s=await fetch(i,{method:"GET",headers:{Accept:"application/json"},signal:t?.signal}),o=await s.json().catch(()=>({}));if(!s.ok){const r=o?.error?.message??o?.message??`ViewToken public key request failed with status ${s.status}`;throw new Error(r)}return o}finally{n!=null&&clearTimeout(n)}}function Pse(i){const e=globalThis.crypto;if(!e?.getRandomValues)throw new Error("[BimEngine] crypto.getRandomValues is required to encrypt viewToken");return e.getRandomValues(new Uint8Array(i))}function fvt(i){let e="";return i.forEach(t=>{e+=String.fromCharCode(t)}),e}function pvt(i){const e=new Uint8Array(i.length);for(let t=0;t<i.length;t+=1)e[t]=i.charCodeAt(t)&255;return e}async function Ivt(i,e){const t=`${S2e(i)}/models/view-token/public-key`,n=await uvt(t,e);if(n.algorithm!=="RSA-OAEP-256"||!n.publicKey)throw new Error("[BimEngine] OpenAPI returned an invalid viewToken public key");return xse.pki.publicKeyFromPem(n.publicKey)}function mvt(i,e){const t=S2e(i),n=Tse.get(t);if(n)return n;const s=Ivt(i,e).catch(o=>{throw Tse.delete(t),o});return Tse.set(t,s),s}async function Cvt(i,e,t){const n=await mvt(i,t),s=Pse(32),o=Pse(12),r=Pse(16),A=JSON.stringify({viewToken:e,timestamp:Date.now(),nonce:LX(r)}),a=n.encrypt(fvt(s),"RSA-OAEP",{md:xse.md.sha256.create(),mgf1:{md:xse.md.sha256.create()}}),l=U4(s,o).encrypt(gvt(A));return[dvt,LX(pvt(a)),LX(o),LX(l)].join(".")}function Evt(i){return i.replace(/\/+$/,"")}async function Bvt(i,e,t){const n=typeof AbortController<"u"?new AbortController:void 0,s=n?setTimeout(()=>n.abort(),t):void 0;try{const o=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),signal:n?.signal}),r=await o.json().catch(()=>({}));if(!o.ok){const A=r?.error?.message??r?.message??`ViewToken resolve failed with status ${o.status}`;throw new Error(A)}return r}finally{s!=null&&clearTimeout(s)}}function yvt(i){switch(i){case"2d":return"cad_model";case"720":return"panorama";case"gis":return"gis_scene";case"gaussian":return"gaussian_model";case"3d":default:return"model"}}function wvt(i){return{models:[{modelType:i.toLowerCase().endsWith(".json")?"3dtiles":"glb",url:i}]}}function bvt(i,e){return{applicationId:0,engineType:e,assetCategory:yvt(e),url:i,urls:[i],info:e==="gis"?wvt(i):void 0}}async function I_(i,e,t){const n=i?.sdkAuth;if(!n?.endpoint)return bvt(e,t);let s;(n.token||n.appId&&n.appKey&&n.appSecret)&&(s=(await evt(i,t))?.sdkToken);const r={viewToken:await Cvt(n.endpoint,e,n.timeoutMs??8e3),engineType:t};return s&&(r.sdkToken=s),Bvt(`${Evt(n.endpoint)}/models/view-token/resolve`,r,n.timeoutMs??8e3)}function Qvt(i){const e=i.postProcessing??{},t=n=>n===!0||n!=null&&typeof n=="object"&&n.enabled===!0?n:!1;i.postProcessing={...e,vxgi:t(e.vxgi),ssgi:t(e.ssgi),traa:t(e.traa),ssr:t(e.ssr),bloom:t(e.bloom),gtao:t(e.gtao),colorGrading:{colorTemperature:6500,saturation:1,contrast:1,sharpen:0,...e.colorGrading??{}}}}class Mvt{version=SC;options;container;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;handelBehaved;viewCube;octreeBox;controls;worldToScreen;modelProperties;hoverHighLight;autoExposureModule;rxQuotaListMapper;filterLoaderModel;engineModelModule;viewTree;merge2d;rangeScale;setting;measure;modelTree;engineInfo;search;modelMapperBatch;modelEdge;nodeBox;pathRoaming;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;fabricDraw;drawingPin;modelLink3d;label;annotation3d;calibration;modelPlace;modelComparison;materialTool;pathDraw;clipping;collector;modelEditor;modelQuantityList;roomSpace;materialReplacement;stats;models=[];reactBoundingClientRect={left:0,top:0};catchSvg;sectionPlane=[];ready;modelExplode;isDisposed=!1;isRenderingPaused=!1;pendingComposerRender=!0;frameLockEnabled=!0;idleFrameInterval=1e3;lastIdleFrameTime=0;idleFrameRateExemptionReasons=new Set;temporalRenderingRequired=!1;controlsEnabledBeforePause=!0;boundControl=null;controlEventHandlers=null;resizeObserver;renderStatsEl=null;renderTrianglesValueEl=null;renderDrawCallsValueEl=null;versionEl=null;constructor(e){window.THREE=uD,ebt(),this.options=e,this.container=this.resolveContainer(e),this.rxQuotaListMapper=new vQt(this),this.filterLoaderModel=new mQt(this),this.deviceModule=new DEt(this),this.deviceModule.isMobile()&&Qvt(this.options),this.cameraModule=new YCt(this),this.sceneModule=new IQt(this),this.scene=this.sceneModule.scene,this.renderModule=new pQt(this),this.renderer=this.renderModule.createRenderer(),this.autoExposureModule=new yCt(this),this.camera=this.cameraModule.perspectiveCamera,this.scene.camera=this.camera;const t=this.renderer;t.interactionCullingEnabled=!0,t.interactionActive=!1,t.interactionRenderScene=this.scene,t.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,t.interactionSkipShadows=this.options.interactionSkipShadows??!0,this.controlModule=new MEt(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.composerModule=new ECt(this),this.composerModule.init(),this.engineModelModule=new jQt(this),this.clipping=new MMt(this),this.clipping.init(),this.events=new SEt;const n=this.events.trigger.bind(this.events);this.events.trigger=((s,o)=>{n(s,o),String(s)!==String(Qs.EngineBusy)&&this.requestComposerRender(),this.updateTemporalFrameRateExemption()}),this.engineStatus=new CQt(this),this.engineStatus.init(),this.updateTemporalFrameRateExemption(),this.materialReplacement=new jbe(this,this.options.materialReplacementOptions),this.materialReplacement.init(),this.loaderModule=new zbt(this),this.lightModule=new PEt(this),this.lightModule.init(),this.engineModelModule.init(),this.initializeVersionDisplay(),this.viewCube=new PQt(this),this.viewCube.init(),this.options.showViewCube===!1&&this.viewCube.hide(),this.octreeBox=_Qt(this),this.handelBehaved=Tee(this),this.modelToolModule=new AQt(this),this.modelProperties=new FQt(this),this.rangeScale=new UQt(this),this.rangeScale.init(),this.setting=new cMt(this),this.modelMapperBatch=new _Mt(this),this.measure=new EMt(this),this.modelLink3d=new G2t(this,this.options.linkOptions??{}),this.modelLink3d.init(),this.search=new PMt(this),this.modelEdge=new rMt(this),this.events.on(Qs.LoadingCompleted,()=>{this.modelEdge.active(),this.composerModule.markSceneDirty()}),this.nodeBox=new RMt(this),this.modelTree=new DMt(this),this.viewTree=new nDt(this),this.merge2d=new WPt(this),this.engineInfo=new SMt(this),this.pathRoaming=new jMt(this),this.pathRoaming.init(),this.oneClickEncoding=new KMt(this),this.minMap=new UMt(this),this.linkElement2d3d=new OMt(this),this.linkView2d3d=new LMt(this),this.grid=new OQt(this),this.level=new zQt(this),this.issueReport=new kMt(this),this.fabricDraw=new R2t(this),this.drawingPin=new N2t(this),this.label=new j2t(this),this.annotation3d=new BFt(this),this.calibration=new yFt(this),this.modelPlace=new MFt(this),this.modelComparison=new DFt(this),this.modelExplode=new SFt(this),this.materialTool=new vFt(this,this.options.materialEditorOptions??{}),this.materialTool.init(),this.pathDraw=new UFt(this),this.collector=new kFt(this),this.modelEditor=new WFt(this),this.modelQuantityList=new OFt(this),this.roomSpace=new LFt(this),this.text=new WMt(this),this.hdr=new VQt(this),this.ground=new LQt(this),this.ground.init(),this.skyManager=new lMt(this),this.setting.init(),this.interactionModule=new _Et(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new KFt(this),this.worldToScreen=new po(this.camera,this.renderer,this.scene),this.catchSvg=this.createCatchSvg(),this.initializeStats(),this.bindControlEvents(this.controls),this.resizeObserver=typeof ResizeObserver>"u"?null:new ResizeObserver(s=>{const o=s[0];o&&this.handleWindowResize(o.contentRect.width,o.contentRect.height)}),this.resizeObserver?.observe(this.container),this.ready=this.initialize().catch(s=>{throw this.dispose(),s})}updateVersionDisplay(){if(this.versionEl==null)return;const e=this.engineModelModule?.getQualityLevel?.()??"";this.versionEl.textContent=`v${this.version} | ${e}`}initializeVersionDisplay(){if(this.versionEl!=null)return;const e=document.createElement("div");e.className="versionText",this.versionEl=e,this.updateVersionDisplay(),this.container.appendChild(e)}bindControlEvents(e){if(this.boundControl===e||(this.boundControl?.removeEventListener&&this.controlEventHandlers&&(this.boundControl.removeEventListener("start",this.controlEventHandlers.start),this.boundControl.removeEventListener("end",this.controlEventHandlers.end),this.boundControl.removeEventListener("change",this.controlEventHandlers.change)),this.boundControl=e,this.controlEventHandlers=null,!e?.addEventListener))return;const t=()=>{this.renderer.interactionActive=!0,this.events.trigger(Qs.EngineBusy),this.container.style.cursor="none"},n=()=>{this.renderer.interactionActive=!1,this.events.trigger(Qs.EngineFree),this.container.style.cursor="default"},s=()=>{this.requestComposerRender(),this.modelEdge?.update?.();const o=new N;this.camera.getWorldDirection(o),window.dispatchEvent(new CustomEvent("D3ViewUpdate",{detail:{position:this.camera.position,rotation:Math.atan2(o.x,-o.z),type:this.camera.type}}))};e.addEventListener("start",t),e.addEventListener("end",n),e.addEventListener("change",s),this.controlEventHandlers={start:t,end:n,change:s}}requestComposerRender(){this.pendingComposerRender=!0}requestRender(){this.requestComposerRender()}async loadModelByViewToken(e,t){const n=await I_(this.options,e,"3d"),s=Array.isArray(n.urls)&&n.urls.length>0?n.urls:[n.url];await this.loaderModule.loadModels(s,t)}requestShadowUpdate(){this.lightModule?.requestShadowUpdate?.(),this.requestComposerRender()}setFrameLock(e){this.frameLockEnabled=e,this.lastIdleFrameTime=0,this.requestComposerRender()}isFrameLockEnabled(){return this.frameLockEnabled}setTemporalRenderingRequired(e){this.temporalRenderingRequired=e,this.updateTemporalFrameRateExemption()}setIdleFrameRateExempt(e,t){if(e){if(t){this.idleFrameRateExemptionReasons.add(e),this.requestComposerRender();return}this.idleFrameRateExemptionReasons.delete(e)}}updateTemporalFrameRateExemption(){this.setIdleFrameRateExempt("webgpu-temporal-post-processing",this.temporalRenderingRequired&&this.engineStatus?.isFree===!1)}pauseRendering(){this.isRenderingPaused||(this.isRenderingPaused=!0,this.controlsEnabledBeforePause=this.controls?.enabled!==!1,this.controls&&(this.controls.enabled=!1))}resumeRendering(){this.isRenderingPaused&&(this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.requestComposerRender())}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(this.isDisposed)return;const n=this.container.getBoundingClientRect(),s=Math.max(1,Math.round(n.width||e||this.container.clientWidth)),o=Math.max(1,Math.round(n.height||t||this.container.clientHeight)),r=this.camera.position.clone(),A=this.camera.quaternion.clone(),a=this.camera.up.clone(),l=this.controls?.target?.clone?.(),c=this.controlModule.orbitControls?.origin?.clone?.();this.renderer.setPixelRatio(bSe(this)),this.renderer.setSize(s,o,!1);const h=s/o;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=h,this.cameraModule.perspectiveCamera.updateProjectionMatrix();else{const d=this.cameraModule.getOrthographicVisibleHeight(this.cameraModule.orthographicCamera);this.cameraModule.setOrthographicVisibleHeight(d,this.cameraModule.orthographicCamera,h)}this.camera.position.copy(r),this.camera.quaternion.copy(A),this.camera.up.copy(a),this.camera.updateMatrixWorld(!0),l&&this.controls?.target&&this.controls.target.copy(l),c&&this.controlModule.orbitControls?.origin&&this.controlModule.orbitControls.origin.copy(c),this.catchSvg.setAttribute("viewBox",`0 0 ${s} ${o}`),this.catchSvg.style.width=`${s}px`,this.catchSvg.style.height=`${o}px`,this.viewCube?.cubeTool?.Resize?.(),this.fabricDraw?.resize?.(s,o),this.events.trigger(Qs.ViewportResize,{width:s,height:o}),this.requestComposerRender()}dispose(){if(this.isDisposed)return;this.isDisposed=!0,this.resizeObserver?.disconnect(),this.renderer.setAnimationLoop(null),this.rangeScale?.dispose?.(),this.measure?.dispose?.(),this.clipping?.dispose?.(),this.pathRoaming?.dispose?.(),this.linkElement2d3d?.dispose?.(),this.linkView2d3d?.dispose?.(),this.skyManager?.close?.(!0),this.hdr?.dispose?.(),this.minMap?.dispose?.(),this.grid?.dispose?.(),this.level?.dispose?.(),this.ground?.dispose?.(),this.issueReport?.dispose?.(),this.fabricDraw?.dispose?.(),this.modelLink3d?.dispose?.(),this.label?.dispose?.(),this.annotation3d?.dispose?.(),this.calibration?.dispose?.(),this.search?.dispose?.(),this.modelPlace?.dispose?.(),this.modelComparison?.dispose?.(),this.modelExplode?.dispose?.(),this.materialTool?.dispose?.(),this.materialReplacement?.dispose?.(),this.pathDraw?.dispose?.(),this.nodeBox?.dispose?.(),this.interactionModule?.dispose?.(),this.hoverHighLight?.dispose?.(),gbt(this),this.handelBehaved?.disActive?.(),this.viewCube?.cubeTool?.dispose?.(),this.controlModule?.dispose?.(),this.engineStatus?.dispose?.(),this.events?.dispose?.(),this.cameraModule?.dispose?.(),this.composerModule?.dispose?.(),this.engineModelModule?.dispose?.(),this.autoExposureModule?.dispose?.(),this.catchSvg?.remove(),this.stats?.dom?.remove(),this.stats=void 0,this.renderStatsEl?.remove(),this.renderStatsEl=null,this.renderTrianglesValueEl=null,this.renderDrawCallsValueEl=null,this.versionEl?.remove(),this.versionEl=null;const e=new Set,t=new Set,n=new Set,s=new Set,o=r=>{if(!(r==null||typeof r!="object"||s.has(r))){if(s.add(r),r.isTexture===!0&&typeof r.dispose=="function"){n.add(r);return}if(Array.isArray(r)){r.forEach(o);return}Object.values(r).forEach(o)}};this.scene.traverse(r=>{const A=r;A.geometry&&e.add(A.geometry),(Array.isArray(A.material)?A.material:A.material?[A.material]:[]).forEach(l=>{t.add(l),o(l)})}),e.forEach(r=>r.dispose()),t.forEach(r=>r.dispose()),n.forEach(r=>r.dispose()),this.scene.clear(),this.renderModule.disposeRenderer()}async initialize(){if(await this.renderModule.initRenderer(),this.options.backgroundColor===void 0&&(this.hdr.setHdr("1"),this.hdr.setIntensity(.5),this.hdr.setBackgroundIntensity(2)),this.isDisposed)throw new Error("EngineKernelV3 在初始化完成前已被销毁。");return await this.renderer.setAnimationLoop(this.animate),this.requestComposerRender(),this}animate=e=>{if(this.isDisposed||this.isRenderingPaused)return;const t=this.engineStatus?.isFree===!0;this.frameLockEnabled&&t&&this.idleFrameRateExemptionReasons.size===0&&!this.pendingComposerRender&&e-this.lastIdleFrameTime<this.idleFrameInterval||(this.lastIdleFrameTime=e,this.stats?.begin(),this.modelEdge?.update?.(),this.controlModule.update(),this.autoExposureModule?.update(e),dbt(this,this.camera,this.container.clientHeight)&&this.requestShadowUpdate(),this.skyManager?.update?.(e),this.composerModule.render(),this.renderModule.drawWatermark(),this.viewCube?.cubeTool?.RenderScene?.(),this.hoverHighLight.update(),this.measure?.update?.(),this.ground?.update?.(),this.modelPlace?.update?.(),this.pathDraw?.update?.(),this.minMap?.update?.(),this.grid?.update?.(),this.level?.update?.(),this.text?.update?.(),this.label?.update?.(),this.annotation3d?.updateFrame?.(1/60),this.modelExplode?.update?.(),this.updateRenderStats(),this.stats?.end(),this.pendingComposerRender=this.options.continuousRendering===!0)};initializeStats(){if(this.options.showStats!==!0)return;this.stats=new Cee,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0",this.stats.dom.style.left="0",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom);const e=document.createElement("div");e.className="bim-render-stats";const t=document.createElement("span");t.textContent="三角面";const n=document.createElement("span");n.textContent="0";const s=document.createElement("span");s.textContent="Draw Calls";const o=document.createElement("span");o.textContent="0",e.append(t,n,s,o),this.container.appendChild(e),this.renderStatsEl=e,this.renderTrianglesValueEl=n,this.renderDrawCallsValueEl=o}updateRenderStats(){if(this.renderStatsEl==null)return;const e=this.renderer?.info?.render,t=Number.isFinite(e?.triangles)?e.triangles:0,n=Number.isFinite(e?.drawCalls)?e.drawCalls:0;this.renderTrianglesValueEl!=null&&(this.renderTrianglesValueEl.textContent=Math.round(t).toLocaleString()),this.renderDrawCallsValueEl!=null&&(this.renderDrawCallsValueEl.textContent=Math.round(n).toLocaleString())}createCatchSvg(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");return e.classList.add("catchSvg"),e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.pointerEvents="none",window.getComputedStyle(this.container).position==="static"&&(this.container.style.position="relative"),this.container.appendChild(e),e}resolveContainer(e){if(e.container instanceof HTMLElement)return e.container;const t=e.containerId?document.getElementById(e.containerId):null;if(!t)throw new Error(`Container ${e.containerId??""} not found`);return t}}const Dvt=Object.freeze(Object.defineProperty({__proto__:null,EngineKernelV3:Mvt},Symbol.toStringTag,{value:"Module"}));class Svt{engine;scene;constructor(e){this.engine=e,this.scene=new ld;let t=new qn;t.name="groupEdge",this.scene.add(t)}}var Rb=(i=>(i.PERSPECTIVE="perspective",i.ORTHOGRAPHIC="orthographic",i))(Rb||{});class aa{static MIN_VISIBLE_HEIGHT=1e-4;static MIN_CAMERA_DISTANCE=1e-4;static CAMERA_ANIMATION_IDLE_EXEMPT_REASON="camera-module-animation";engine;perspectiveCamera;orthographicCamera;cameraAnimationFrame=null;constructor(e){this.engine=e,this.perspectiveCamera=new Yo(45,this.engine.container.clientWidth/this.engine.container.clientHeight,.1,1e3),this.perspectiveCamera.position.set(2,2,2),this.perspectiveCamera.lookAt(0,0,0);const t=50,n=this.engine.container.clientWidth/this.engine.container.clientHeight;this.orthographicCamera=new Zo(t*n/-2,t*n/2,t/2,t/-2,.1,1e3)}exitDrawingPinView(){this.engine.drawingPin?.exitViewMode?.()}getCameraAspect(e){const t=e?.width??this.engine.container?.clientWidth??1,n=e?.height??this.engine.container?.clientHeight??1;return n>0?t/n:1}getPerspectiveVisibleHeight(e,t){const n=Math.max(e.position.distanceTo(t),aa.MIN_CAMERA_DISTANCE),s=Ai.degToRad(e.getEffectiveFOV()*.5);return Math.max(2*n*Math.tan(s),aa.MIN_VISIBLE_HEIGHT)}getOrthographicVisibleHeight(e=this.orthographicCamera){return Math.max((e.top-e.bottom)/e.zoom,aa.MIN_VISIBLE_HEIGHT)}setOrthographicVisibleHeight(e,t=this.orthographicCamera,n){const s=Math.max(e,aa.MIN_VISIBLE_HEIGHT),o=Number.isFinite(n)&&n>0?n:this.getCameraAspect(),r=Math.max(t.zoom||1,aa.MIN_CAMERA_DISTANCE),A=s*r*.5,a=A*o;t.left=-a,t.right=a,t.top=A,t.bottom=-A}getViewDirection(e,t,n){const s=new N().subVectors(e,t);return s.lengthSq()>aa.MIN_CAMERA_DISTANCE?s.normalize():new N(0,0,1).applyQuaternion(n).normalize()}getStableCameraUp(e){const t=e.clone().normalize();if(t.lengthSq()<=aa.MIN_CAMERA_DISTANCE)return new N(0,1,0);const n=[new N(0,1,0),new N(0,0,1),new N(1,0,0)];for(const s of n){const o=s.clone().sub(t.clone().multiplyScalar(s.dot(t)));if(o.lengthSq()>aa.MIN_CAMERA_DISTANCE)return o.normalize()}return new N(0,1,0)}updateComposerCamera(){if(!this.engine.composerModule?.composer)return;const e=this.engine.camera,t=this.engine.composerModule.composer;if(t.passes)for(const n of t.passes)n.camera!==void 0&&(n.camera=e)}applySwitchedCamera(e,t){this.engine.camera=e,this.engine.scene.camera=e,this.engine.controls?.target&&this.engine.controls.target.copy(t),this.engine.controls&&(this.engine.controls.object=e),this.engine.controlModule.orbitControls.object=e,this.engine.controlModule.firstPersonControls.camera=e,this.engine.controlModule.firstPersonControls.object=e,this.engine.controlModule.firstPersonControls.syncRotationStateFromCamera?.(),this.engine.controlModule.firstPersonControls.syncSharedTargetFromCamera?.(),this.engine.controlModule.thirdPersonControls&&(this.engine.controlModule.thirdPersonControls.camera=e,this.engine.controlModule.thirdPersonControls.object=e,this.engine.controlModule.thirdPersonControls.syncRotationStateFromCamera?.(),this.engine.controlModule.thirdPersonControls.syncSharedTargetFromAvatar?.()),e.updateProjectionMatrix?.(),e.updateMatrixWorld(),this.updateComposerCamera(),this.engine.controls?.update&&this.engine.controls.update(),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene)}resolvePoseReferenceUp(e,t){if(e.referenceUp){const a=new N(e.referenceUp.x,e.referenceUp.y,e.referenceUp.z);if(a.lengthSq()>aa.MIN_CAMERA_DISTANCE)return a.normalize()}if(!e.up||!t)return;const n=new N(e.up.x,e.up.y,e.up.z);if(n.lengthSq()<=aa.MIN_CAMERA_DISTANCE)return;const s=t.clone().sub(this.engine.camera.position);if(s.lengthSq()<=aa.MIN_CAMERA_DISTANCE)return;s.normalize(),n.normalize();const o=[new N(0,1,0),new N(0,-1,0),new N(0,0,1),new N(0,0,-1),new N(1,0,0),new N(-1,0,0)];let r,A=-1/0;for(const a of o){const l=a.clone().sub(s.clone().multiplyScalar(a.dot(s)));if(l.lengthSq()<=aa.MIN_CAMERA_DISTANCE)continue;const c=l.normalize().dot(n);c>A&&(A=c,r=a.clone())}return r}syncControlsAfterPoseRestore(e,t,n,s){const o=this.engine.camera;if(!o)return;e&&this.engine.controls?.target&&this.engine.controls.target.copy(e);const r=this.engine.controlModule?.orbitControls;r&&(e&&typeof r.syncStateFromCamera=="function"?r.syncStateFromCamera(o,e,{origin:t??"target",referenceUp:n,viewRight:s}):(r.object=o,e&&r.target&&r.target.copy(e),t&&r.origin?r.origin.copy(t):e&&r.origin&&r.origin.copy(e),n&&r._referenceUp?.copy&&r._referenceUp.copy(n).normalize(),s&&r._viewRight?.copy&&r._viewRight.copy(s).normalize(),r._rotateVelocity?.set?.(0,0),r._panVelocity?.set?.(0,0),typeof r._zoomVelocity=="number"&&(r._zoomVelocity=0),r._lastPosition?.copy?.(o.position),r._lastTarget?.copy?.(r.target),r._lastUp?.copy?.(o.up),r._lastQuaternion?.copy?.(o.quaternion),r._lastZoom=o.zoom,r.saveState?.()));const A=this.engine.controlModule?.firstPersonControls;A&&(A.camera=o,A.object=o,A.syncRotationStateFromCamera?.(),A.syncSharedTargetFromCamera?.());const a=this.engine.controlModule?.thirdPersonControls;a&&(a.camera=o,a.object=o,a.syncRotationStateFromCamera?.(),a.syncSharedTargetFromAvatar?.()),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene)}inferTargetFromRestoredCamera(e){const t=new N;e.getWorldDirection(t),t.lengthSq()<=aa.MIN_CAMERA_DISTANCE&&t.set(0,0,-1);const s=this.engine.controls?.target?.distanceTo?.(e.position),o=this.engine.octreeBox?.getBoundingBox?.(),r=o?.min&&o?.max?o.max.distanceTo(o.min)*.8:0;let A=10;return typeof s=="number"&&Number.isFinite(s)&&s>aa.MIN_CAMERA_DISTANCE?A=s:r>aa.MIN_CAMERA_DISTANCE&&(A=r),e.position.clone().add(t.normalize().multiplyScalar(A))}switchCurrentCamera(){this.engine.camera===this.perspectiveCamera?this.switchToOrthographicCamera():this.switchToPerspectiveCamera()}setPerspectiveFov(e,t){const n=this.perspectiveCamera,s=n.fov,o=Math.max(1,Math.min(120,e));if(t?.adjustDistance!==!1&&this.engine.camera===n&&this.engine.controls?.target){const A=this.engine.controls.target.clone(),a=n.position.clone(),l=a.distanceTo(A);if(l>1e-6){const c=Ai.degToRad(s*.5),h=Ai.degToRad(o*.5),d=Math.tan(c)/Math.tan(h),g=l*d,u=new N().subVectors(a,A).normalize();n.position.copy(A).add(u.multiplyScalar(g))}}n.fov=o,n.updateProjectionMatrix()}switchToPerspectiveCamera(){if(this.exitDrawingPinView(),!this.engine.controls)return;const e=this.engine.camera;if(!e)return;const t=e.position.clone(),n=this.engine.controls.target.clone(),s=e.quaternion.clone(),o=e.up.clone(),r=this.perspectiveCamera,A=this.getViewDirection(t,n,s),a=e instanceof Zo?this.getOrthographicVisibleHeight(e):this.getPerspectiveVisibleHeight(e,n),l=Ai.degToRad(r.getEffectiveFOV()*.5),c=Math.max(a/(2*Math.tan(l)),aa.MIN_CAMERA_DISTANCE);r.near=e.near,r.far=e.far,r.aspect=this.getCameraAspect(),r.up.copy(o),r.position.copy(n).add(A.multiplyScalar(c)),r.lookAt(n),this.engine.camera=r,this.applySwitchedCamera(r,n)}switchToOrthographicCamera(){if(this.exitDrawingPinView(),!this.engine.controls)return;const e=this.engine.camera;if(!e)return;const t=e.position.clone(),n=this.engine.controls.target.clone(),s=e.quaternion.clone(),o=e.up.clone(),r=this.orthographicCamera,A=this.getViewDirection(t,n,s),a=e instanceof Yo?this.getPerspectiveVisibleHeight(e,n):this.getOrthographicVisibleHeight(e),l=Ai.degToRad(e.getEffectiveFOV()*.5),c=Math.max(a/(2*Math.tan(l)),aa.MIN_CAMERA_DISTANCE);r.near=e.near,r.far=e.far,r.zoom=1,this.setOrthographicVisibleHeight(a,r),r.up.copy(o);const h=this.engine.octreeBox?.getBoundingBox?.(),d=h?h.max.distanceTo(h.min)*.8:c,g=Math.max(d,aa.MIN_CAMERA_DISTANCE);r.position.copy(n).add(A.clone().multiplyScalar(g)),r.quaternion.copy(s),this.engine.camera=r,this.applySwitchedCamera(r,n)}getCameraType(){return this.engine.camera===this.perspectiveCamera?"perspective":this.engine.camera===this.orthographicCamera?"orthographic":"perspective"}getCameraPose(){const e=this.engine.camera,t=this.getCameraType(),n={type:t,position:{x:e.position.x,y:e.position.y,z:e.position.z},rotation:{x:e.rotation.x,y:e.rotation.y,z:e.rotation.z},quaternion:{x:e.quaternion.x,y:e.quaternion.y,z:e.quaternion.z,w:e.quaternion.w},up:{x:e.up.x,y:e.up.y,z:e.up.z}};this.engine.controls?.target&&(n.target={x:this.engine.controls.target.x,y:this.engine.controls.target.y,z:this.engine.controls.target.z});const s=this.engine.controlModule?.orbitControls;return s?.origin&&(n.origin={x:s.origin.x,y:s.origin.y,z:s.origin.z}),s?._referenceUp&&(n.referenceUp={x:s._referenceUp.x,y:s._referenceUp.y,z:s._referenceUp.z}),s?._viewRight&&(n.viewRight={x:s._viewRight.x,y:s._viewRight.y,z:s._viewRight.z}),t==="orthographic"&&(n.zoom=e.zoom,n.orthographicHeight=this.getOrthographicVisibleHeight(e)),n}restoreCameraPose(e){this.exitDrawingPinView(),this.getCameraType()!==e.type&&(e.type==="perspective"?this.switchToPerspectiveCamera():this.switchToOrthographicCamera());const n=this.engine.camera;n.position.set(e.position.x,e.position.y,e.position.z),e.up&&n.up.set(e.up.x,e.up.y,e.up.z),e.quaternion?n.quaternion.set(e.quaternion.x,e.quaternion.y,e.quaternion.z,e.quaternion.w):e.rotation&&n.rotation.set(e.rotation.x,e.rotation.y,e.rotation.z);let s;e.target&&(s=new N(e.target.x,e.target.y,e.target.z));const o=e.origin?new N(e.origin.x,e.origin.y,e.origin.z):s?.clone();if(e.type==="orthographic"){const a=n;e.zoom!==void 0&&(a.zoom=e.zoom),e.orthographicHeight!==void 0&&this.setOrthographicVisibleHeight(e.orthographicHeight,a),a.updateProjectionMatrix()}n.updateMatrix(),n.updateMatrixWorld(!0),s||(s=this.inferTargetFromRestoredCamera(n));const r=this.resolvePoseReferenceUp(e,s),A=e.viewRight?new N(e.viewRight.x,e.viewRight.y,e.viewRight.z):void 0;this.syncControlsAfterPoseRestore(s,o,r,A)}setViewFromOriginAndDirection(e,t,n=null,s,o=0,r){this.exitDrawingPinView();const A=new N(t.x,t.y,t.z).normalize(),a=new N(e.x,e.y,e.z);let l=s??null;if(l==null||l<=0){const d=this.engine.octreeBox?.getBoundingBox?.();if(d&&d.min&&d.max){const g=new N().subVectors(d.max,d.min);l=Math.max(g.x,g.y,g.z)*1.2}else l=50}const c=a.clone().add(A.clone().negate().multiplyScalar(l));if(this.engine.camera){if(n||(n=this.getStableCameraUp(A)),o>0){this.animateCameraToTarget(c,a,n,o,r);return}this.applyCameraPose(c,a,n),r?.()}}rotateToTarget(e,t=0,n){const s=this.engine.camera;if(!s)return;const o=new N(e.x,e.y,e.z);if(s.position.distanceToSquared(o)<=aa.MIN_CAMERA_DISTANCE){n?.();return}const r=s.position.clone(),A=s.up.lengthSq()>aa.MIN_CAMERA_DISTANCE?s.up.clone().normalize():this.getStableCameraUp(o.clone().sub(r));if(t>0){this.animateCameraToTarget(r,o,A,t,n);return}this.applyCameraPose(r,o,A),n?.()}applyCameraPose(e,t,n){const s=this.engine.camera;s&&(s.position.copy(e),s.up.copy(n),this.engine.controls?.target&&this.engine.controls.target.copy(t),typeof this.engine.controls?.setScreenUp=="function"?this.engine.controls.setScreenUp(n):s.lookAt(t),this.engine.controls?.update&&this.engine.controls.update(),s.updateMatrix(),s.updateMatrixWorld(!0))}animateCameraToTarget(e,t,n,s,o){const r=this.engine.camera,A=this.engine.controls;if(!r||!A?.target){this.applyCameraPose(e,t,n),o?.();return}const a=()=>{this.engine.renderer&&(this.engine.renderer.interactionActive=!0),this.engine.setIdleFrameRateExempt?.(aa.CAMERA_ANIMATION_IDLE_EXEMPT_REASON,!0),this.engine.events?.trigger?.("engine-busy"),this.engine.requestComposerRender?.()},l=()=>{this.engine.renderer&&(this.engine.renderer.interactionActive=!1),this.engine.setIdleFrameRateExempt?.(aa.CAMERA_ANIMATION_IDLE_EXEMPT_REASON,!1),this.engine.events?.trigger?.("engine-free")};this.cameraAnimationFrame!=null&&(cancelAnimationFrame(this.cameraAnimationFrame),this.cameraAnimationFrame=null,l());const c=new qg.Tween({px:r.position.x,py:r.position.y,pz:r.position.z,tx:A.target.x,ty:A.target.y,tz:A.target.z,ux:r.up.x,uy:r.up.y,uz:r.up.z}).to({px:e.x,py:e.y,pz:e.z,tx:t.x,ty:t.y,tz:t.z,ux:n.x,uy:n.y,uz:n.z},s);c.easing(qg.Easing.Cubic.InOut),c.onUpdate(d=>{r.position.set(d.px,d.py,d.pz),A.target.set(d.tx,d.ty,d.tz),r.up.set(d.ux,d.uy,d.uz).normalize(),typeof A.setScreenUp=="function"?A.setScreenUp(r.up.clone()):r.lookAt(A.target),A.auto=!0,A.update?.(),r.updateMatrix(),r.updateMatrixWorld(!0),this.engine.requestComposerRender?.()}),c.onComplete(()=>{A.auto=!1,this.cameraAnimationFrame=null,this.applyCameraPose(e,t,n),this.engine.requestComposerRender?.(),l(),o?.()});const h=()=>{c.update()&&(this.cameraAnimationFrame=requestAnimationFrame(h))};a(),c.start(),h()}}class xvt{engine;deviceType;constructor(e){this.engine=e,this.deviceType=this.detectDeviceType()}detectDeviceType(){const e=[/Android/i,/webOS/i,/iPhone/i,/iPad/i,/iPod/i,/BlackBerry/i,/Windows Phone/i,/Mobile/i],t=navigator.userAgent||globalThis.opera,n=e.some(c=>c.test(t)),s="ontouchstart"in globalThis||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0,o=globalThis.screen.width,r=globalThis.screen.height,A=o<=768||r<=768,l=(globalThis.devicePixelRatio||1)>=2;return n||s&&A||s&&l?"mobile":"PC"}getDeviceType(){return this.deviceType}isMobile(){return this.deviceType==="mobile"}isPC(){return this.deviceType==="PC"}redetectDeviceType(){return this.deviceType=this.detectDeviceType(),this.deviceType}getContainerSize(){return{width:this.engine.container.clientWidth,height:this.engine.container.clientHeight}}}const _se=1.1;function x2e(i){if(i?.deviceModule?.isMobile?.()!==!0)return window.devicePixelRatio||1;const e=Number(i?.options?.limit_memory);return!Number.isFinite(e)||e<=4?.8:e>=8||e>=6?2:1}function T2e(i){if(i?.deviceModule?.isMobile?.()!==!0)return!0;const e=Number(i?.options?.limit_memory);return!(!Number.isFinite(e)||e<=4)}class Tvt{engine;renderer;watermark;constructor(e){this.engine=e,this.renderer=null,this.watermark=new NN(uD)}createRenderer(){const{width:e,height:t}=this.engine.deviceModule.getContainerSize();return this.engine.deviceModule.isMobile(),In.enabled=!0,this.renderer=new Rm({antialias:this.engine.options.antialias??!0,alpha:!0,premultipliedAlpha:!1,stencil:!0,preserveDrawingBuffer:T2e(this.engine)}),this.renderer.setClearColor(0,0),this.renderer.setSize(e,t,!1),this.renderer.setPixelRatio(x2e(this.engine)),this.renderer.domElement.style.width="100%",this.renderer.domElement.style.width="100%",this.renderer.domElement.style.height="100%",this.renderer.domElement.style.display="block",this.renderer.shadowMap.enabled=T2e(this.engine),this.renderer.shadowMap.type=P0,this.renderer.localClippingEnabled=!0,this.renderer.outputColorSpace=Cs,this.renderer.toneMapping=v0,this.renderer.toneMappingExposure=_se,this.engine.container.appendChild(this.renderer.domElement),this.renderer}disposeRenderer(){this.watermark.dispose(),this.renderer?.dispose()}drawWatermark(){this.renderer&&this.watermark.render(this.renderer)}}const Pvt={type:"change"},P2e={type:"start"},_2e={type:"end"},yr=1e-6,Fse=Math.PI*2,Qc={NONE:-1,ROTATE:0,PAN:1,DOLLY:2,TOUCH_ROTATE:3,TOUCH_DOLLY_PAN:4},vse=new N(1,0,0),_vt=new N(0,1,0),Fvt=new N(0,0,1),m_=new N,KX=new N,fg=new N,Ar=new N,Sp=new N,rh=new N,xp=new N,vvt=new N,XX=new nn,Rse=new nn,F2e=new Set(["KeyW","KeyA","KeyS","KeyD","KeyQ","KeyE","ArrowUp","ArrowLeft","ArrowDown","ArrowRight","ShiftLeft","ShiftRight"]);function VX(i,e,t){return Math.max(e,Math.min(t,i))}function v2e(i){return{width:Math.max(i?.clientWidth||1,1),height:Math.max(i?.clientHeight||1,1)}}function Nb(i){return i&&typeof i.x=="number"&&typeof i.y=="number"&&typeof i.z=="number"}function R2e(i){const e=i?.tagName?.toLowerCase?.();return i?.isContentEditable===!0||e==="input"||e==="textarea"||e==="select"}class N2e extends GO{constructor(e,t,n=null){super(t,n),this.engine=e,this.target=new N,this.origin=new N,this.cursor=new N,this.showOriginIcon=!0,this.auto=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.enableRotate=!0,this.enablePan=!0,this.enableZoom=!0,this.enableDamping=!1,this.rotateSpeed=.51,this.panSpeed=1,this.zoomSpeed=1,this.touchZoomSpeed=1.35,this.dampingFactor=.08,this.keyRotateSpeed=1,this.keyPanSpeed=7,this.keyMoveSpeed=.5,this.keyMoveBoost=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:uc.ROTATE,MIDDLE:uc.DOLLY,RIGHT:uc.PAN},this.state=Qc.NONE,this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this.up0=this.object.up.clone(),this.origin0=this.origin.clone(),this._lastZoom=this.object.zoom,this._lastPosition=this.object.position.clone(),this._lastTarget=this.target.clone(),this._lastUp=this.object.up.clone(),this._lastQuaternion=this.object.quaternion.clone(),this._referenceUp=this.object.up.clone().normalize(),this._viewRight=new N(1,0,0).applyQuaternion(this.object.quaternion).normalize(),this._rotateVelocity=new Ne,this._panVelocity=new Ne,this._zoomVelocity=0,this._mouseStart=new Ne,this._touchCenter=new Ne,this._touchDistance=0,this._pointers=new Map,this._pressedKeys=new Set,this._keyboardAnimationId=null,this._lastKeyboardMoveTime=0,this._isInteracting=!1,this._keyDomElement=null,this._touchAction="",this._onContextMenu=this._handleContextMenu.bind(this),this._onPointerDown=this._handlePointerDown.bind(this),this._onPointerMove=this._handlePointerMove.bind(this),this._onPointerUp=this._handlePointerUp.bind(this),this._onPointerCancel=this._handlePointerUp.bind(this),this._onWheel=this._handleWheel.bind(this),this._onKeyDown=this._handleKeyDown.bind(this),this._onKeyUp=this._handleKeyUp.bind(this),this.domElement&&this.connect(this.domElement),this.update(),this.saveState()}connect(e){e&&(this.disconnect(),this.domElement=e,this._touchAction=e.style.touchAction,e.style.touchAction="none",e.addEventListener("contextmenu",this._onContextMenu),e.addEventListener("pointerdown",this._onPointerDown),e.addEventListener("pointermove",this._onPointerMove),e.addEventListener("pointerup",this._onPointerUp),e.addEventListener("pointercancel",this._onPointerCancel),e.addEventListener("wheel",this._onWheel,{passive:!1}),this.listenToKeyEvents(window))}disconnect(){this.domElement&&(this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerCancel),this.domElement.removeEventListener("wheel",this._onWheel),this.domElement.style.touchAction=this._touchAction,this.stopListenToKeyEvents())}dispose(){this.disconnect(),this._pointers.clear(),this._pressedKeys.clear(),this._stopKeyboardMoveLoop(),this.state=Qc.NONE}listenToKeyEvents(e){this.stopListenToKeyEvents(),this._keyDomElement=e,this._keyDomElement?.addEventListener("keydown",this._onKeyDown),this._keyDomElement?.addEventListener("keyup",this._onKeyUp)}stopListenToKeyEvents(){this._keyDomElement&&(this._keyDomElement.removeEventListener("keydown",this._onKeyDown),this._keyDomElement.removeEventListener("keyup",this._onKeyUp),this._keyDomElement=null,this._pressedKeys.clear(),this._stopKeyboardMoveLoop())}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom,this.up0.copy(this.object.up),Nb(this.origin)&&this.origin0.copy(this.origin)}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.up.copy(this.up0),Nb(this.origin)&&this.origin.copy(this.origin0),this._rotateVelocity.set(0,0),this._panVelocity.set(0,0),this._zoomVelocity=0,this.object.updateProjectionMatrix?.(),this.update(!0),this.state=Qc.NONE}setScreenUp(e){return!Nb(e)||(rh.copy(this.target).sub(this.object.position),rh.lengthSq()<yr)||(rh.normalize(),Sp.copy(e).normalize(),Ar.crossVectors(rh,Sp),Ar.lengthSq()<yr)?!1:(this._viewRight.copy(Ar.normalize()),this.update(!0),!0)}syncStateFromCamera(e=this.object,t=this.target,n={}){if(!e)return!1;this.object=e,Nb(t)&&this.target.copy(t),n.origin==="target"?this.origin.copy(this.target):Nb(n.origin)&&this.origin.copy(n.origin);const s=this.target.clone().sub(e.position),o=Nb(n.referenceUp)?new N(n.referenceUp.x,n.referenceUp.y,n.referenceUp.z).normalize():e.up.clone().normalize();return o.lengthSq()>yr&&this._referenceUp.copy(o),Nb(n.viewRight)?this._viewRight.copy(n.viewRight).normalize():s.lengthSq()>yr&&(s.normalize(),Ar.crossVectors(s,this._referenceUp),Ar.lengthSq()>yr?this._viewRight.copy(Ar.normalize()):this._viewRight.set(1,0,0).applyQuaternion(e.quaternion).normalize()),this._rotateVelocity.set(0,0),this._panVelocity.set(0,0),this._zoomVelocity=0,this._mouseStart.set(0,0),this._touchCenter.set(0,0),this._touchDistance=0,this._pointers.clear(),this._pressedKeys.clear(),this._isInteracting=!1,this.state=Qc.NONE,this._lastPosition.copy(e.position),this._lastTarget.copy(this.target),this._lastUp.copy(e.up),this._lastQuaternion.copy(e.quaternion),this._lastZoom=e.zoom,this.saveState(),!0}update(e=null,t=!1){const n=typeof e=="number"?e:null,s=typeof e=="boolean"?e:!!t,o=this._applyPendingMotion(n);this._alignCamera();const r=s||o||this._hasCameraStateChanged();return r&&(this.dispatchEvent(Pvt),this._rememberState()),r}_applyPendingMotion(e){let t=!1;this.autoRotate&&this.state===Qc.NONE&&this.auto===!1&&(this._rotateVelocity.x+=this._getAutoRotateAngle(e)),this._applyKeyboardMove(e)&&(t=!0);const n=this._consumeVector2(this._rotateVelocity);n.lengthSq()>yr&&this.enableRotate&&(this._applyRotation(n.x,n.y),t=!0);const s=this._consumeVector2(this._panVelocity);s.lengthSq()>yr&&this.enablePan&&(this._applyPan(s.x,s.y),t=!0);const o=this._consumeNumber("_zoomVelocity");return Math.abs(o)>yr&&this.enableZoom&&(this._applyZoom(o),t=!0),t}_applyKeyboardMove(e){if(!this.enabled||!this.object?.isPerspectiveCamera||this._pressedKeys.size===0||(xp.set(0,0,0),(this._pressedKeys.has("KeyW")||this._pressedKeys.has("ArrowUp"))&&(xp.z+=1),(this._pressedKeys.has("KeyS")||this._pressedKeys.has("ArrowDown"))&&(xp.z-=1),(this._pressedKeys.has("KeyA")||this._pressedKeys.has("ArrowLeft"))&&(xp.x-=1),(this._pressedKeys.has("KeyD")||this._pressedKeys.has("ArrowRight"))&&(xp.x+=1),this._pressedKeys.has("KeyQ")&&(xp.y+=1),this._pressedKeys.has("KeyE")&&(xp.y-=1),xp.lengthSq()<=yr)||(xp.normalize(),Ar.copy(vse).applyQuaternion(this.object.quaternion).normalize(),rh.set(0,0,-1).applyQuaternion(this.object.quaternion).normalize(),Sp.copy(this._referenceUp).normalize(),Sp.lengthSq()<=yr&&Sp.copy(this.object.up).normalize(),fg.set(0,0,0),fg.addScaledVector(Ar,xp.x),fg.addScaledVector(rh,xp.z),fg.addScaledVector(Sp,xp.y),fg.lengthSq()<=yr))return!1;fg.normalize();const t=Number.isFinite(e)&&e>0?e:1/60,n=Math.max(this.object.position.distanceTo(this.target),1),s=this._pressedKeys.has("ShiftLeft")||this._pressedKeys.has("ShiftRight")?this.keyMoveBoost:1,o=Math.max(n*.8,1)*this.keyMoveSpeed*t*s;return fg.multiplyScalar(o),this.object.position.add(fg),this.target.add(fg),this.origin.add(fg),!0}_startKeyboardMoveLoop(){if(this._keyboardAnimationId!=null)return;this._lastKeyboardMoveTime=performance.now();const e=t=>{if(this._keyboardAnimationId=null,!this.enabled||this._pressedKeys.size===0){this._lastKeyboardMoveTime=0;return}const n=Math.min(Math.max((t-this._lastKeyboardMoveTime)/1e3,0),.05);this._lastKeyboardMoveTime=t,this.update(n),this._keyboardAnimationId=requestAnimationFrame(e)};this._keyboardAnimationId=requestAnimationFrame(e)}_stopKeyboardMoveLoop(){this._keyboardAnimationId!=null&&(cancelAnimationFrame(this._keyboardAnimationId),this._keyboardAnimationId=null),this._lastKeyboardMoveTime=0}_consumeVector2(e){if(!this.enableDamping){const s=e.clone();return e.set(0,0),s}const t=VX(this.dampingFactor,0,1),n=e.clone().multiplyScalar(t);return e.sub(n),e.lengthSq()<yr&&e.set(0,0),n}_consumeNumber(e){if(!this.enableDamping){const s=this[e];return this[e]=0,s}const t=VX(this.dampingFactor,0,1),n=this[e]*t;return this[e]-=n,Math.abs(this[e])<yr&&(this[e]=0),n}_applyRotation(e,t){const n=this._getRotatePivot(),s=this.object.position;m_.copy(s).sub(n),m_.lengthSq()<yr&&m_.set(0,0,Math.max(this.minDistance,1)),KX.copy(this.target).sub(n),rh.copy(this.target).sub(s).normalize(),Math.abs(e)>yr&&(XX.setFromAxisAngle(this._referenceUp,-e),m_.applyQuaternion(XX),KX.applyQuaternion(XX),rh.applyQuaternion(XX).normalize()),Ar.copy(this._getStableRightAxis(rh)),Math.abs(t)>yr&&Ar.lengthSq()>yr&&(Rse.setFromAxisAngle(Ar,-t),m_.applyQuaternion(Rse),KX.applyQuaternion(Rse)),s.copy(n).add(m_),this.target.copy(n).add(KX)}_applyPan(e,t){const{width:n,height:s}=v2e(this.domElement);Ar.copy(vse).applyQuaternion(this.object.quaternion).normalize(),Sp.copy(_vt).applyQuaternion(this.object.quaternion).normalize();let o=0,r=0;if(this.object.isPerspectiveCamera){const a=2*Math.max(this.object.position.distanceTo(this.target),yr)*Math.tan(Ai.degToRad(this.object.getEffectiveFOV()*.5)),l=a*this.object.aspect;o=e/n*l*this.panSpeed,r=t/s*a*this.panSpeed}else if(this.object.isOrthographicCamera){const A=(this.object.right-this.object.left)/this.object.zoom,a=(this.object.top-this.object.bottom)/this.object.zoom;o=e/n*A*this.panSpeed,r=t/s*a*this.panSpeed}else return;fg.set(0,0,0),fg.addScaledVector(Ar,-o),fg.addScaledVector(Sp,r),this.object.position.add(fg),this.target.add(fg)}_applyZoom(e){const t=Math.pow(.95,this.zoomSpeed*e);if(this.object.isPerspectiveCamera){rh.copy(this.object.position).sub(this.target);const n=Math.max(rh.length(),yr),s=VX(n/t,this.minDistance,this.maxDistance);rh.setLength(s),this.object.position.copy(this.target).add(rh);return}this.object.isOrthographicCamera&&(this.object.zoom=VX(this.object.zoom*t,this.minZoom,this.maxZoom),this.object.updateProjectionMatrix())}_alignCamera(){rh.copy(this.target).sub(this.object.position),!(rh.lengthSq()<yr)&&(rh.normalize(),Ar.copy(this._getStableRightAxis(rh)),Sp.crossVectors(Ar,rh).normalize(),Sp.lengthSq()<yr&&Sp.copy(this._referenceUp),this._viewRight.copy(Ar),this.object.up.copy(Sp),this.object.lookAt(this.target),this.object.updateMatrixWorld())}_getStableRightAxis(e){return Ar.crossVectors(e,this._referenceUp),Ar.lengthSq()<yr&&(Ar.copy(this._viewRight),Ar.addScaledVector(e,-Ar.dot(e))),Ar.lengthSq()<yr&&(Ar.copy(vse),Ar.addScaledVector(e,-Ar.dot(e))),Ar.lengthSq()<yr&&(Ar.copy(Fvt),Ar.addScaledVector(e,-Ar.dot(e))),Ar.normalize(),this._viewRight.lengthSq()>yr&&Ar.dot(this._viewRight)<0&&Ar.negate(),Ar}_getRotatePivot(){return Nb(this.origin)?this.origin.distanceToSquared(this.target)<yr?this.target:vvt.copy(this.origin):this.target}_hasCameraStateChanged(){const e=this.object.isOrthographicCamera&&Math.abs(this.object.zoom-this._lastZoom)>yr;return this._lastPosition.distanceToSquared(this.object.position)>yr||this._lastTarget.distanceToSquared(this.target)>yr||this._lastUp.distanceToSquared(this.object.up)>yr||8*(1-Math.abs(this._lastQuaternion.dot(this.object.quaternion)))>yr||e}_rememberState(){this._lastPosition.copy(this.object.position),this._lastTarget.copy(this.target),this._lastUp.copy(this.object.up),this._lastQuaternion.copy(this.object.quaternion),this._lastZoom=this.object.zoom}_getAutoRotateAngle(e){return e!=null?Fse/60*this.autoRotateSpeed*e:Fse/3600*this.autoRotateSpeed}_beginInteraction(e){this._isInteracting||(this.dispatchEvent(P2e),this._isInteracting=!0),this.state=e}_endInteraction(){this._isInteracting&&(this._isInteracting=!1,this.state=Qc.NONE,this.dispatchEvent(_2e))}_handleContextMenu(e){e.preventDefault()}_handlePointerDown(e){if(!this.enabled||!this.domElement)return;if(this.domElement.setPointerCapture?.(e.pointerId),this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY,pointerType:e.pointerType,button:e.button}),e.pointerType==="touch"){this._handleTouchStart();return}const t=this._resolveMouseAction(e);t!=null&&(this._mouseStart.set(e.clientX,e.clientY),this._beginInteraction(t))}_handlePointerMove(e){const t=this._pointers.get(e.pointerId);if(!t)return;if(e.pointerType==="touch"){t.x=e.clientX,t.y=e.clientY,this._handleTouchMove();return}if(!this.enabled||this.state===Qc.NONE)return;const n=e.clientX-this._mouseStart.x,s=e.clientY-this._mouseStart.y;this._mouseStart.set(e.clientX,e.clientY),this.state===Qc.ROTATE?this._queueRotate(n,s):this.state===Qc.PAN?this._queuePan(n,s):this.state===Qc.DOLLY&&this._queueZoom(s*.01),this.update()}_handlePointerUp(e){if(this._pointers.has(e.pointerId)){if(this.domElement?.releasePointerCapture?.(e.pointerId),this._pointers.delete(e.pointerId),e.pointerType==="touch"){this._pointers.size>0?this._restartTouchGesture():this._endInteraction();return}this._endInteraction()}}_handleWheel(e){!this.enabled||!this.enableZoom||(e.preventDefault(),this.dispatchEvent(P2e),this._queueZoom(Math.sign(e.deltaY)),this.update(),this.dispatchEvent(_2e))}_handleKeyDown(e){if(!this.enabled)return;const t=e.code||e.key;if(this.object?.isPerspectiveCamera&&F2e.has(t)){R2e(e.target)||(this._pressedKeys.add(t),this._startKeyboardMoveLoop(),e.preventDefault());return}let n=!1;switch(t){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this._queuePan(0,this.keyPanSpeed):this._queueRotate(0,this.keyRotateSpeed),n=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this._queuePan(0,-this.keyPanSpeed):this._queueRotate(0,-this.keyRotateSpeed),n=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this._queuePan(this.keyPanSpeed,0):this._queueRotate(this.keyRotateSpeed,0),n=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this._queuePan(-this.keyPanSpeed,0):this._queueRotate(-this.keyRotateSpeed,0),n=!0;break}n&&(e.preventDefault(),this.update())}_handleKeyUp(e){const t=e.code||e.key;F2e.has(t)&&(this._pressedKeys.delete(t),this._pressedKeys.size===0&&this._stopKeyboardMoveLoop(),this.object?.isPerspectiveCamera&&!R2e(e.target)&&e.preventDefault())}_handleTouchStart(){const e=Array.from(this._pointers.values());if(e.length===1){this._touchCenter.set(e[0].x,e[0].y),this._touchDistance=0,this._beginInteraction(Qc.TOUCH_ROTATE);return}if(e.length>=2){const t=(e[0].x+e[1].x)*.5,n=(e[0].y+e[1].y)*.5,s=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y);this._touchCenter.set(t,n),this._touchDistance=s,this._beginInteraction(Qc.TOUCH_DOLLY_PAN)}}_restartTouchGesture(){const e=Array.from(this._pointers.values());if(e.length===1){this.state=Qc.TOUCH_ROTATE,this._touchCenter.set(e[0].x,e[0].y),this._touchDistance=0;return}e.length>=2&&(this.state=Qc.TOUCH_DOLLY_PAN,this._touchCenter.set((e[0].x+e[1].x)*.5,(e[0].y+e[1].y)*.5),this._touchDistance=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y))}_handleTouchMove(){if(!this.enabled)return;const e=Array.from(this._pointers.values());if(e.length===1&&this.state===Qc.TOUCH_ROTATE){const o=e[0].x-this._touchCenter.x,r=e[0].y-this._touchCenter.y;this._touchCenter.set(e[0].x,e[0].y),this._queueRotate(o,r),this.update();return}if(e.length<2||this.state!==Qc.TOUCH_DOLLY_PAN)return;const t=(e[0].x+e[1].x)*.5,n=(e[0].y+e[1].y)*.5,s=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y);if(this._queuePan(t-this._touchCenter.x,n-this._touchCenter.y),this._touchCenter.set(t,n),this._touchDistance>0&&s>0){const o=s/this._touchDistance,r=Math.pow(o,Math.max(this.touchZoomSpeed||1,yr));this._queueZoom(Math.log(r)/Math.log(.95))}this._touchDistance=s,this.update()}_resolveMouseAction(e){let t=null;return e.button===0?t=e.ctrlKey||e.metaKey||e.shiftKey?this.mouseButtons.RIGHT:this.mouseButtons.LEFT:e.button===1?t=this.mouseButtons.MIDDLE:e.button===2&&(t=this.mouseButtons.RIGHT),t===uc.ROTATE&&this.enableRotate?Qc.ROTATE:t===uc.PAN&&this.enablePan?Qc.PAN:t===uc.DOLLY&&this.enableZoom?Qc.DOLLY:null}_queueRotate(e,t){if(!this.enableRotate||!this.domElement)return;const{height:n}=v2e(this.domElement),s=Fse/n;this._rotateVelocity.x+=e*s*this.rotateSpeed,this._rotateVelocity.y+=t*s*this.rotateSpeed}_queuePan(e,t){this.enablePan&&(this._panVelocity.x+=e,this._panVelocity.y+=t)}_queueZoom(e){this.enableZoom&&(this._zoomVelocity+=e)}}class Y2e extends wl{constructor(e,t,n,s){super(),this._Engine=e,this.camera=t,this.object=t,this.domElement=n,this._isEnabled=!1,this._rayOriginOffset=new N(0,-1,0),this._camerLocalDirection=new N,this._tmpVector=new N,this._lookDirection=new N,this._rayCaster=new Ao,this._fallingTime=0,this._isMouseInElement=!1,this._euler=new Gr(0,0,0,"YZX"),this._prevMouseX=0,this._prevMouseY=0,this._pointerLookActive=!1,this._externalLookActive=!1,this._interactionActive=!1,this._sharedTargetDistance=10,this.target=this.camera.position.clone().add(new N(0,0,-1).applyQuaternion(this.camera.quaternion).normalize().multiplyScalar(this._sharedTargetDistance)),this.applyGravity=!1,this.gravityMinHeight=!0,this.applyCollision=!0,this.positionEasing=!0,this.lookflag=1,this.lookHorizontalFlag=1,this.lookSpeed=.003,this.moveSpeed=.02,this.playerHeight=1.6,this.jumpSpeed=.24,this.jumpGravity=.012,this.maxRotateX=Math.PI*.5-.01,this.g=9.8,this.bindmousedown=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchStart.bind(this):this.onMouseDown.bind(this),this.bindmouseup=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchEnd.bind(this):this.onMouseUp.bind(this),this.bindmousemove=this._Engine&&this._Engine.deviceType!=="PC"?this.onTouchMove.bind(this):this.onMouseMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindWindowBlur=this.onWindowBlur.bind(this),this.bindVisibilityChange=this.onVisibilityChange.bind(this),this.bindMousewheel=this.onMousewheel.bind(this),this.bindMouseEnter=this.onMouseEnter.bind(this),this.bindMouseLeave=this.onMouseLeave.bind(this),this.needMousewheel=!1,this.moveWheelRun=!0,this.moveWheelStop=!1,this.wheelClock,this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this._jumpStartHeight=this.camera.position.y,this.gravityTestCount=5,this.catchTestCount=10,this.GetEngine=()=>e,this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera()}set colliders(e){this._rayCastObjects=e}set enabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?(this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera(),this.addEvents()):(this.removeEvents(),this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState?.(),this.syncRotationStateFromCamera(),this.syncSharedTargetFromCamera()))}get enabled(){return this._isEnabled}hasMoveInput(){return this._camerLocalDirection.lengthSq()>1e-8}setPointerLookActive(e){this._pointerLookActive=e===!0,this.syncInteractionState()}setExternalLookActive(e){this._externalLookActive=e===!0,this.syncInteractionState()}syncInteractionState(){const e=this._pointerLookActive||this._externalLookActive||this.hasMoveInput()||this._isJumping;this._interactionActive!==e&&(this._interactionActive=e,this.dispatchEvent({type:e?"start":"end"}))}dispatchCameraChange(){window.dispatchEvent(new CustomEvent("bimengine:camerachange",{detail:""})),this.dispatchEvent({type:"change"})}isPcDevice(){const e=this._Engine?.deviceModule?.getDeviceType?.()??this._Engine?.deviceType??this._Engine?.DeviceType;return e==="PC"||!e}addEvents(){this.isPcDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),window.addEventListener("blur",this.bindWindowBlur,!1),document.addEventListener("visibilitychange",this.bindVisibilityChange,!1),this.needMousewheel&&(document.addEventListener&&document.addEventListener("DOMMouseScroll",this.bindMousewheel,!1),window.addEventListener("mousewheel",this.bindMousewheel,!1))}removeEvents(){this.isPcDevice()?(this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove)):(this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove)),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),window.removeEventListener("blur",this.bindWindowBlur),document.removeEventListener("visibilitychange",this.bindVisibilityChange),this.needMousewheel&&(document.addEventListener&&document.removeEventListener("DOMMouseScroll",this.bindMousewheel),window.removeEventListener("mousewheel",this.bindMousewheel))}onMouseEnter(e){this._isMouseInElement=!0}onMouseLeave(e){this._isMouseInElement=!1,this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onWindowBlur(){this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onVisibilityChange(){document.hidden&&(this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState())}onMousewheel(e){let t;switch(e.wheelDelta?(e.wheelDelta>0&&(t="up"),e.wheelDelta<0&&(t="down")):e.detail&&(e.detail<0&&(t="up"),e.detail>0&&(t="down")),t){case"up":this._camerLocalDirection.z=1;break;case"down":this._camerLocalDirection.z=-1;break}this.moveWheelRun==!0?(this.moveWheelRun=!1,this.moveWheelStop=!0,this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0,this.syncInteractionState())},200)):(clearTimeout(this.wheelClock),this.wheelClock=setTimeout(()=>{this.moveWheelStop==!0&&(this.moveWheelStop=!1,this.moveWheelRun=!0,this._camerLocalDirection.z=0,this.syncInteractionState())},150)),this.syncInteractionState()}onMouseDown(e){console.log("[FirstPersonCameraControl] onMouseDown",e),this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this.syncRotationStateFromCamera(),this.setPointerLookActive(!0),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY}onMouseMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?e.screenX-this._prevMouseX:0,n=this._prevMouseY?e.screenY-this._prevMouseY:0,s=this._euler.x-n*this.lookflag*this.lookSpeed;s>=0?s<this.maxRotateX?this._euler.x=s:this._euler.x=this.maxRotateX:s>-this.maxRotateX?this._euler.x=s:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY;let o=this.GetEngine();o.movefirst=!0,this.dispatchCameraChange()}onMouseUp(e){let t=this.GetEngine();t.movefirst=!1,this.setPointerLookActive(!1),this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(e){this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this.syncRotationStateFromCamera(),this.setPointerLookActive(!0),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY}onTouchMove(e){if(this._isEnabled==!1)return;let t=this._prevMouseX?this._prevMouseX-e.targetTouches[0].clientX:0,n=this._prevMouseY?this._prevMouseY-e.targetTouches[0].clientY:0,s=this._euler.x-n*this.lookflag*this.lookSpeed;s>=0?s<this.maxRotateX?this._euler.x=s:this._euler.x=this.maxRotateX:s>-this.maxRotateX?this._euler.x=s:this._euler.x=-this.maxRotateX,this._euler.y-=t*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this._prevMouseX=e.targetTouches[0].clientX,this._prevMouseY=e.targetTouches[0].clientY;let o=this.GetEngine();o.movefirst=!0,this.dispatchCameraChange()}onTouchEnd(e){let t=this.GetEngine();t.movefirst=!1,this.setPointerLookActive(!1),this.domElement.removeEventListener("touchmove",this.bindmousemove)}onKeyDown(e){if(!this._isMouseInElement)return;let t=this.GetEngine();switch(t.movefirst=!0,this.dispatchCameraChange(),e.keyCode){case 38:this._camerLocalDirection.z=1;break;case 81:if(this.applyGravity){this.keydown=!1,this._camerLocalDirection.y=0;break}this.keydown=!0,this._camerLocalDirection.y=1;break;case 69:if(this.applyGravity){this.keydown=!1,this._camerLocalDirection.y=0;break}this._camerLocalDirection.y=-1;break;case 87:this._camerLocalDirection.z=1;break;case 37:this._camerLocalDirection.x=-1;break;case 65:this._camerLocalDirection.x=-1;break;case 40:this._camerLocalDirection.z=-1;break;case 83:this._camerLocalDirection.z=-1;break;case 39:this._camerLocalDirection.x=1;break;case 68:this._camerLocalDirection.x=1;break;case 32:e.preventDefault?.(),e.stopPropagation?.(),this._isJumpKeyDown||(this._isJumpKeyDown=!0,this.jump());break;case 16:this.shiftDown=!0;break}this.syncInteractionState()}onKeyUp(e){let t=this.GetEngine();switch(e.keyCode){case 38:case 87:this._camerLocalDirection.z=0;break;case 37:case 65:this._camerLocalDirection.x=0;break;case 40:case 83:this._camerLocalDirection.z=0;break;case 39:case 68:this._camerLocalDirection.x=0;break;case 81:case 69:this.keydown=!1,this._camerLocalDirection.y=0;break;case 32:e.preventDefault?.(),e.stopPropagation?.(),this._isJumpKeyDown=!1;break;case 16:this.shiftDown=!1;break}t.movefirst=this._camerLocalDirection.x!==0||this._camerLocalDirection.y!==0||this._camerLocalDirection.z!==0,this.syncInteractionState()}rotateX(e){this.syncRotationStateFromCamera(),this._euler.y-=e*this.lookHorizontalFlag*this.lookSpeed,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this.dispatchCameraChange()}rotateY(e){this.syncRotationStateFromCamera();let t=this._euler.x-e*this.lookflag*.5*this.lookSpeed;t>=0?t<this.maxRotateX?this._euler.x=t:this._euler.x=this.maxRotateX:t>-this.maxRotateX?this._euler.x=t:this._euler.x=-this.maxRotateX,this.camera.quaternion.setFromEuler(this._euler),this.syncSharedTargetFromCamera(),this.dispatchCameraChange()}setLookDirection({horizontal:e,vertical:t}={}){(e===1||e===-1)&&(this.lookHorizontalFlag=e),(t===1||t===-1)&&(this.lookflag=t)}update(){const e=this.camera.position.clone(),t=this.camera.quaternion.clone();this.applyGravity&&(this.keydown=!1,this._camerLocalDirection.y=0),this.updateJump(),!this.keydown&&!this._isJumping&&this.gravityTest(),this.collisionTest(),this.syncSharedTargetFromCamera(),this.syncInteractionState(),(e.distanceToSquared(this.camera.position)>1e-12||1-Math.abs(t.dot(this.camera.quaternion))>1e-12)&&this.dispatchCameraChange()}syncRotationStateFromCamera(){this.camera&&(this.object=this.camera,this.camera.updateMatrixWorld?.(),this._euler.setFromQuaternion(this.camera.quaternion,"YZX"))}sanitizeCameraOrientation(){this.camera&&(this.syncRotationStateFromCamera(),this._euler.x=Ai.clamp(this._euler.x,-this.maxRotateX,this.maxRotateX),this._euler.z=0,this.camera.up.set(0,1,0),this.camera.quaternion.setFromEuler(this._euler),this.camera.updateMatrixWorld?.(!0))}syncSharedTargetFromCamera(){if(!this.camera)return;this.object=this.camera;let e=this.GetEngine();const t=[],n=s=>{!s?.target||t.includes(s)||t.push(s)};if(n(this),n(e?.controls),n(e?.controlModule?.orbitControls),t.length!==0){this.camera.getWorldDirection(this._lookDirection);for(const s of t){const o=this.camera.position.distanceTo(s.target);Number.isFinite(o)&&o>.001&&(this._sharedTargetDistance=o),s.target.copy(this.camera.position).addScaledVector(this._lookDirection,this._sharedTargetDistance)}}}setScreenUp(e){return!e||typeof e.x!="number"||typeof e.y!="number"||typeof e.z!="number"||!this.camera?!1:(this.camera.up.copy(e).normalize(),this.target&&this.camera.lookAt(this.target),this.camera.updateMatrixWorld?.(!0),this.syncRotationStateFromCamera(),this.sanitizeCameraOrientation(),this.syncSharedTargetFromCamera(),!0)}resetMovementState(){this._camerLocalDirection.set(0,0,0),this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1;let e=this.GetEngine();e&&(e.movefirst=!1),this.syncInteractionState()}resetMovementState(){this._camerLocalDirection.set(0,0,0),this.keydown=!1,this.shiftDown=!1,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1;let e=this.GetEngine();e&&(e.movefirst=!1),this.syncInteractionState()}jump(){this._isJumping||(this._jumpStartHeight=this.camera.position.y,this._verticalVelocity=this.jumpSpeed,this._isJumping=!0,this.syncInteractionState())}updateJump(){if(!this._isJumping)return;this.setCameraHeight(this.camera.position.y+this._verticalVelocity),this._verticalVelocity-=this.jumpGravity;const e=this.getJumpFloorCameraHeight();this._verticalVelocity<=0&&this.camera.position.y<=e&&(this.setCameraHeight(e),this._verticalVelocity=0,this._isJumping=!1,this._fallingTime=0,this.syncInteractionState())}getJumpFloorCameraHeight(){const e=this.hitTest(new N(0,-1,0),this.playerHeight+3);if(e?.point)return e.point.y+this.playerHeight;const t=this.getMinHeight();return Math.max(this._jumpStartHeight,t??-1/0)}gravityTest(){if(!(this._camerLocalDirection.y==0&&this._camerLocalDirection.z==0&&this._camerLocalDirection.x==0))if(this.applyGravity){let e=!0;this._fallingTime+=.01,this._tmpVector.set(0,-1,0);const t=this.hitTest(this._tmpVector,this.playerHeight+3);if(t==null)return;if(t){const n=t.point.add(new N(0,this.playerHeight,0));if(this.positionEasing){if(n.y>=this.camera.position.y||n.y-this.camera.position.y<.2){this.setCameraHeight(this.camera.position.y+(n.y-this.camera.position.y)*.08),this._fallingTime=0,e=!1;return}}else t.distance<this.playerHeight&&(this.setCameraHeight(n.y),this._fallingTime=0,e=!1)}e&&this.setCameraHeight(this.camera.position.y-this.g*Math.pow(this._fallingTime,2))}else this.setCameraHeight(this.camera.position.y)}collisionTest(){this._camerLocalDirection.x!==0&&this.collisionTestX(),this._camerLocalDirection.z!==0&&this.collisionTestZ(),!this.applyGravity&&this._camerLocalDirection.y!==0&&this.collisionTestY()}collisionTestX(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.x),this._tmpVector.set(this._tmpVector.x,0,this._tmpVector.z),this._tmpVector=this._tmpVector.normalize(),this.applyCollision){const t=this.hitTest(this._tmpVector);if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1))}collisionTestZ(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector.crossVectors(this.camera.up,this._tmpVector),this._tmpVector.multiplyScalar(this._camerLocalDirection.z),this._tmpVector.set(this._tmpVector.x,0,this._tmpVector.z),this._tmpVector=this._tmpVector.normalize(),this.applyCollision){const t=this.hitTest(this._tmpVector);if(t&&t.distance<.3)return}this.camera.position.addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1))}collisionTestY(){let e=this.GetEngine();if(e.movefirst=!0,this._tmpVector.setFromMatrixColumn(this.camera.matrix,0),this._tmpVector=new N(0,1,0),this._tmpVector.multiplyScalar(this._camerLocalDirection.y),this.applyCollision){const n=this.hitTest(this._tmpVector);if(n&&n.distance<.3)return}let t=this.camera.position.clone().addScaledVector(this._tmpVector,this.moveSpeed*(this.shiftDown?2:1));this.setCameraHeight(t.y)}setCameraHeight(e){let t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&e<t?this.camera.position.y=t:this.camera.position.y=e}getMinHeight(){let e,t=this.GetEngine(),n=t.ToolUntils?t.ToolUntils.GetBoundingBox(t):null;return t&&n&&(e=n.min.y),e}hitTest(e=this._tmpVector,t=1/0){const n=this.camera.position.clone().add(this._rayOriginOffset);this._rayCaster.ray.origin=n,this._rayCaster.ray.direction=e,this._rayCaster.far=t;let s=this.GetEngine();var o=s.scene.ground;o&&o.material.type;let r={},A=s.handelBehaved.handle_catch(this._rayCaster,r,!1);if(this._rayCaster.far=1/0,A==null)return null;let a=A.object.name,l=A.object.url,c=s.models.find(h=>h.url==l);if(c!=null){let h=c.nodesMap.get(a);if(h.infos!=null&&h.infos.length!=0&&h.infos[0].name&&(h.infos[0].name.includes("门")||h.infos[0].name.includes("門")||h.infos[0].name.includes("door")))return null}return A}}const Rvt=bn("/assets/worker_walk.glb",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href),Nvt=Math.PI,Yvt={16:"ShiftLeft",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",65:"KeyA",68:"KeyD",69:"KeyE",81:"KeyQ",32:"Space",83:"KeyS",87:"KeyW"},Uh={forward:["KeyW","ArrowUp"],backward:["KeyS","ArrowDown"],left:["KeyA","ArrowLeft"],right:["KeyD","ArrowRight"],up:["KeyQ"],down:["KeyE"],jump:["Space"],boost:["ShiftLeft","ShiftRight"]};class G2e extends wl{constructor(e,t,n,s={}){super(),this._Engine=e,this.camera=t,this.object=t,this.domElement=n,this._isEnabled=!1,this.target=new N,this.auto=!1,this.applyGravity=s.applyGravity??!0,this.gravityMinHeight=!0,this.applyCollision=s.applyCollision??!0,this.positionEasing=!0,this.lookflag=1,this.lookHorizontalFlag=1,this.lookSpeed=s.lookSpeed??.003,this.moveSpeed=s.moveSpeed??.02,this.playerHeight=s.playerHeight??1.6,this.playerRadius=s.playerRadius??.3,this.cameraDistance=s.cameraDistance??2,this.cameraHeight=s.cameraHeight??0,this.targetHeight=s.targetHeight??this.playerHeight,this.cameraCollisionTargetHeight=s.cameraCollisionTargetHeight??this.playerHeight+.1,this.cameraCollisionInterval=Math.max(1,Math.floor(s.cameraCollisionInterval??20)),this.cameraCollisionPadding=s.cameraCollisionPadding??.15,this.minCameraCollisionDistance=s.minCameraCollisionDistance??.35,this.jumpSpeed=s.jumpSpeed??.24,this.jumpGravity=s.jumpGravity??.012,this.maxRotateX=s.maxPitch??Math.PI*.45,this.minPitch=s.minPitch??-Math.PI*.38,this.g=9.8,this._moveInput=new N,this._moveDirection=new N,this._rayCaster=new Ao,this._cameraRayCaster=new Ao,this._cameraCollisionFrame=0,this._lastCameraSafeDistance=null,this._fallingTime=0,this._isMouseInElement=!1,this._prevMouseX=0,this._prevMouseY=0,this._dragRotateThreshold=s.dragRotateThreshold??2,this._pointerLookActive=!1,this._externalLookActive=!1,this._scriptedMotionActive=!1,this._interactionActive=!1,this._yaw=0,this._pitch=s.initialPitch??0,this._pressedKeys=new Set,this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this._jumpStartHeight=0,this.avatarRoot=new qn,this.avatarRoot.name="ThirdPersonAvatarRoot",this.avatarRoot.visible=s.visible??!0,this.avatarMixer=null,this.avatarWalkAction=null,this._isWalkActionPlaying=!1,this._avatarAnimationTimer=new AD,this._avatarAnimationTimer.connect(document),this._avatarLoadRequestId=0,this.defaultAvatarUrl=s.avatarUrl??Rvt,this._ownsAvatarResources=!s.avatar,this.avatar=s.avatar||this.createDefaultAvatar(),this.avatar.name=this.avatar.name||"ThirdPersonAvatar",this.avatarRoot.add(this.avatar),!s.avatar&&this.defaultAvatarUrl&&this.loadAvatarModel(this.defaultAvatarUrl,s.avatarOptions);const o=this.isPcDevice();this.bindmousedown=o?this.onMouseDown.bind(this):this.onTouchStart.bind(this),this.bindmouseup=o?this.onMouseUp.bind(this):this.onTouchEnd.bind(this),this.bindmousemove=o?this.onMouseMove.bind(this):this.onTouchMove.bind(this),this.bindonKeyDown=this.onKeyDown.bind(this),this.bindonKeyUp=this.onKeyUp.bind(this),this.bindWindowBlur=this.onWindowBlur.bind(this),this.bindVisibilityChange=this.onVisibilityChange.bind(this),this.bindMouseEnter=this.onMouseEnter.bind(this),this.bindMouseLeave=this.onMouseLeave.bind(this),this.initAvatarPoseFromCamera()}set enabled(e){this._isEnabled!==e&&(this._isEnabled=e,e?(this.ensureAvatarInScene(),this.syncRotationStateFromCamera(),this._avatarAnimationTimer.reset(),this.addEvents(),this.updateCameraFromAvatar()):(this.removeEvents(),this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.setScriptedMotionActive(!1),this.resetMovementState(),this.avatarRoot.visible=!1))}get enabled(){return this._isEnabled}setPointerLookActive(e){this._pointerLookActive=e===!0,this.syncInteractionState()}setExternalLookActive(e){this._externalLookActive=e===!0,this.syncInteractionState()}setScriptedMotionActive(e){this._scriptedMotionActive=e===!0,this.syncInteractionState()}syncInteractionState(){const e=this._pointerLookActive||this._externalLookActive||this._scriptedMotionActive||this.hasMoveInput()||this._isJumping;this._interactionActive!==e&&(this._interactionActive=e,this.dispatchEvent({type:e?"start":"end"}))}isPcDevice(){const e=this._Engine?.DeviceType??this._Engine?.deviceType;return e==="PC"||!e}createDefaultAvatar(){const e=new qn;return e.name="ThirdPersonEmptyAvatar",e.visible=!1,e}setAvatarModel(e,t={}){if(e){if(this.clearAvatarAnimation(),this.avatar&&(this.avatarRoot.remove(this.avatar),this._ownsAvatarResources&&this.disposeObjectResources(this.avatar)),this.avatar=e,this._ownsAvatarResources=t.ownsResources===!0,e.rotation.y+=t.yawOffset??0,t.alignToFeet!==!1){const n=new Wt().setFromObject(e),s=n.max.y-n.min.y;if(t.fitToPlayerHeight!==!1&&Number.isFinite(s)&&s>1e-6){const r=(t.targetHeight??this.playerHeight)/s;e.scale.multiplyScalar(r),n.setFromObject(e)}Number.isFinite(n.min.y)&&(e.position.y-=n.min.y)}e.traverse(n=>{(n.isMesh||n.isSkinnedMesh)&&(n.castShadow=!0,n.receiveShadow=!0,n.frustumCulled=!1)}),this.avatarRoot.add(e)}}loadAvatarModel(e,t={}){const n=++this._avatarLoadRequestId;new S1().load(e,o=>{if(n!==this._avatarLoadRequestId||!o?.scene)return;const r=o.scene;r.name="ThirdPersonWorkerAvatar",this.setAvatarModel(r,{alignToFeet:!0,fitToPlayerHeight:!0,ownsResources:!0,yawOffset:Nvt,...t}),this.setupAvatarAnimation(r,o.animations||[])},void 0,o=>{console.warn("[ThirdPersonCameraControl] failed to load avatar model",e,o)})}setupAvatarAnimation(e,t){if(!t.length)return;this.avatarMixer=new Xv(e);const n=t.find(s=>/walk|run|move/i.test(s.name))||t[0];this.avatarWalkAction=this.avatarMixer.clipAction(n),this.avatarWalkAction.enabled=!0,this.avatarWalkAction.clampWhenFinished=!1,this.avatarWalkAction.setEffectiveWeight(1),this.avatarWalkAction.paused=!0,this.avatarWalkAction.play(),this._avatarAnimationTimer.reset()}clearAvatarAnimation(){this.avatarMixer&&(this.avatarMixer.stopAllAction(),this.avatarMixer.uncacheRoot(this.avatar)),this.avatarMixer=null,this.avatarWalkAction=null,this._isWalkActionPlaying=!1}ensureAvatarInScene(){this._Engine?.scene&&(this.avatarRoot.parent||this._Engine.scene.add(this.avatarRoot),this.avatarRoot.visible=!0)}initAvatarPoseFromCamera(){if(!this.camera)return;const e=new N;this.camera.getWorldDirection(e),e.y=0,e.lengthSq()<1e-6&&e.set(0,0,-1),e.normalize(),this.setViewYaw(Math.atan2(e.x,-e.z));const t=this.targetHeight+this.cameraHeight+Math.sin(this._pitch)*this.cameraDistance,n=this.camera.position.clone().addScaledVector(e,this.cameraDistance).add(new N(0,-t,0)),s=this.getMinHeight();s!==void 0&&n.y<s&&(n.y=s),this.avatarRoot.position.copy(n),this.setViewYaw(this._yaw)}addEvents(){this.isPcDevice()?(this.domElement.addEventListener("mousedown",this.bindmousedown,!1),this.domElement.addEventListener("mouseup",this.bindmouseup,!1)):(this.domElement.addEventListener("touchstart",this.bindmousedown,!1),this.domElement.addEventListener("touchend",this.bindmouseup,!1)),this.domElement.addEventListener("mouseenter",this.bindMouseEnter,!1),this.domElement.addEventListener("mouseleave",this.bindMouseLeave,!1),window.addEventListener("keydown",this.bindonKeyDown,!1),window.addEventListener("keyup",this.bindonKeyUp,!1),window.addEventListener("blur",this.bindWindowBlur,!1),document.addEventListener("visibilitychange",this.bindVisibilityChange,!1)}removeEvents(){this.domElement.removeEventListener("touchstart",this.bindmousedown),this.domElement.removeEventListener("touchend",this.bindmouseup),this.domElement.removeEventListener("touchmove",this.bindmousemove),this.domElement.removeEventListener("mousedown",this.bindmousedown),this.domElement.removeEventListener("mouseup",this.bindmouseup),this.domElement.removeEventListener("mousemove",this.bindmousemove),this.domElement.removeEventListener("mouseenter",this.bindMouseEnter),this.domElement.removeEventListener("mouseleave",this.bindMouseLeave),window.removeEventListener("keydown",this.bindonKeyDown),window.removeEventListener("keyup",this.bindonKeyUp),window.removeEventListener("blur",this.bindWindowBlur),document.removeEventListener("visibilitychange",this.bindVisibilityChange)}onMouseEnter(){this._isMouseInElement=!0}onMouseLeave(){this._isMouseInElement=!1,this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onWindowBlur(){this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState()}onVisibilityChange(){document.hidden&&(this.setPointerLookActive(!1),this.setExternalLookActive(!1),this.resetMovementState())}onMouseDown(e){this._isMouseInElement=!0,this.domElement.addEventListener("mousemove",this.bindmousemove,!1),this.setPointerLookActive(!0),e.preventDefault?.(),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY}onMouseMove(e){if(!this._isEnabled)return;const t=e.screenX-this._prevMouseX,n=e.screenY-this._prevMouseY;Math.abs(t)+Math.abs(n)<this._dragRotateThreshold||(this.rotateByPointerDelta(t,n),this._prevMouseX=e.screenX,this._prevMouseY=e.screenY)}onMouseUp(){this.updateEngineMovingFlag(),this.setPointerLookActive(!1),this.domElement.removeEventListener("mousemove",this.bindmousemove)}onTouchStart(e){const t=e.targetTouches?.[0];t&&(this._isMouseInElement=!0,this.domElement.addEventListener("touchmove",this.bindmousemove,!1),this.setPointerLookActive(!0),e.preventDefault?.(),this._prevMouseX=t.clientX,this._prevMouseY=t.clientY)}onTouchMove(e){if(!this._isEnabled)return;const t=e.targetTouches?.[0];if(!t)return;const n=t.clientX-this._prevMouseX,s=t.clientY-this._prevMouseY;Math.abs(n)+Math.abs(s)<this._dragRotateThreshold||(this.rotateByPointerDelta(n,s),this._prevMouseX=t.clientX,this._prevMouseY=t.clientY)}onTouchEnd(){this.updateEngineMovingFlag(),this.setPointerLookActive(!1),this.domElement.removeEventListener("touchmove",this.bindmousemove)}setViewYaw(e){this._yaw=e,this.updateAvatarFacing()}getAvatarFacingYaw(){const e=-this._yaw,t=Math.sign(this._moveInput.x);return t!==0?e-t*Math.PI*.5:this._moveInput.z<0?e+Math.PI:e}updateAvatarFacing(){this.avatarRoot.rotation.y=this.getAvatarFacingYaw()}setViewPitch(e){this._pitch=Ai.clamp(e,this.minPitch,this.maxRotateX)}rotateByPointerDelta(e,t){this.setViewYaw(this._yaw+e*this.lookHorizontalFlag*this.lookSpeed),this.setViewPitch(this._pitch+t*this.lookflag*this.lookSpeed),this.updateCameraFromAvatar(),this.dispatchCameraChange()}onKeyDown(e){if(!this._isEnabled||!this._isMouseInElement)return;const t=this.getEventCode(e);if(this.isManagedKey(t)){if(e.preventDefault?.(),this.hasCodeInGroup(t,Uh.jump)){e.stopPropagation?.(),this._isJumpKeyDown||(this._isJumpKeyDown=!0,this.jump());return}this._pressedKeys.add(t),this.updateEngineMovingFlag(),this.dispatchCameraChange()}}onKeyUp(e){const t=this.getEventCode(e);if(this.isManagedKey(t)){if(e.preventDefault?.(),this.hasCodeInGroup(t,Uh.jump)){e.stopPropagation?.(),this._isJumpKeyDown=!1;return}this._pressedKeys.delete(t),this.updateEngineMovingFlag()}}getEventCode(e){return e.code||Yvt[e.keyCode]||e.key||""}hasPressed(e){return e.some(t=>this._pressedKeys.has(t))}isManagedKey(e){return this.hasCodeInGroup(e,Uh.forward)||this.hasCodeInGroup(e,Uh.backward)||this.hasCodeInGroup(e,Uh.left)||this.hasCodeInGroup(e,Uh.right)||this.hasCodeInGroup(e,Uh.up)||this.hasCodeInGroup(e,Uh.down)||this.hasCodeInGroup(e,Uh.jump)||this.hasCodeInGroup(e,Uh.boost)}hasCodeInGroup(e,t){return t.includes(e)}updateMoveInputFromKeys(){const e=(this.hasPressed(Uh.right)?1:0)-(this.hasPressed(Uh.left)?1:0),t=(this.hasPressed(Uh.forward)?1:0)-(this.hasPressed(Uh.backward)?1:0),n=this.applyGravity?0:(this.hasPressed(Uh.up)?1:0)-(this.hasPressed(Uh.down)?1:0);return this._moveInput.set(e,n,t),this._moveInput}hasMoveInput(){return this.updateMoveInputFromKeys().lengthSq()>0}updateEngineMovingFlag(){const e=this.hasMoveInput();this.updateAvatarFacing(),this._Engine&&(this._Engine.movefirst=e),this.syncInteractionState()}rotateX(e){this.setViewYaw(this._yaw-e*this.lookHorizontalFlag*this.lookSpeed),this.updateCameraFromAvatar()}rotateY(e){this.setViewPitch(this._pitch+e*this.lookflag*.5*this.lookSpeed),this.updateCameraFromAvatar()}setLookDirection({horizontal:e,vertical:t}={}){(e===1||e===-1)&&(this.lookHorizontalFlag=e),(t===1||t===-1)&&(this.lookflag=t)}update(){this._isEnabled&&(this.auto||(this.updateAvatarAnimation(),this.updateMoveInputFromKeys(),this.updateJump(),this.applyGravity&&!this._isJumping&&this.gravityTest(),this.moveAvatar(),this.updateCameraFromAvatar()))}moveAvatar(){this._moveDirection.set(0,0,0);const e=this.getFlatForward(),t=new N(-e.z,0,e.x).normalize();if(this._moveInput.z!==0&&this._moveDirection.addScaledVector(e,this._moveInput.z),this._moveInput.x!==0&&this._moveDirection.addScaledVector(t,this._moveInput.x),!this.applyGravity&&this._moveInput.y!==0&&(this._moveDirection.y+=this._moveInput.y),this._moveDirection.lengthSq()<=0){this.setAvatarWalking(!1),this.updateAvatarFacing(),this.updateEngineMovingFlag();return}this._moveDirection.normalize();const n=this.moveSpeed*(this.hasPressed(Uh.boost)?2:1);if(this.applyCollision&&this.isBlocked(this._moveDirection,n)){this.setAvatarWalking(!1),this.updateAvatarFacing(),this.updateEngineMovingFlag();return}this.avatarRoot.position.addScaledVector(this._moveDirection,n),this.updateAvatarFacing(),this.setAvatarWalking(this._moveInput.x!==0||this._moveInput.z!==0),this._Engine&&(this._Engine.movefirst=!0)}jump(){this._isJumping||(this._jumpStartHeight=this.avatarRoot.position.y,this._verticalVelocity=this.jumpSpeed,this._isJumping=!0,this.syncInteractionState())}updateJump(){if(!this._isJumping)return;this.avatarRoot.position.y+=this._verticalVelocity,this._verticalVelocity-=this.jumpGravity;const e=this.getJumpFloorHeight();this._verticalVelocity<=0&&this.avatarRoot.position.y<=e&&(this.setAvatarHeight(e),this._verticalVelocity=0,this._isJumping=!1,this._fallingTime=0,this.syncInteractionState())}getJumpFloorHeight(){const e=this.hitTest(new N(0,-1,0),this.playerHeight+3);if(e?.point)return e.point.y;const t=this.getMinHeight();return Math.max(this._jumpStartHeight,t??-1/0)}setAvatarWalking(e){!this.avatarWalkAction||this._isWalkActionPlaying===e||(this._isWalkActionPlaying=e,this.avatarWalkAction.paused=!1,e?this.avatarWalkAction.reset().fadeIn(.12).play():this.avatarWalkAction.fadeOut(.16))}updateAvatarAnimation(){this.avatarMixer&&(this._avatarAnimationTimer.update(),this.avatarMixer.update(this._avatarAnimationTimer.getDelta()))}getFlatForward(){return new N(Math.sin(this._yaw),0,-Math.cos(this._yaw)).normalize()}updateCameraFromAvatar(){if(!this.camera)return;const e=this.avatarRoot.position.clone().add(new N(0,this.targetHeight,0)),t=Math.cos(this._pitch)*this.cameraDistance,n=new N(-Math.sin(this._yaw)*t,this.cameraHeight+Math.sin(this._pitch)*this.cameraDistance,Math.cos(this._yaw)*t),s=e.clone().add(n);this.camera.position.copy(this.resolveCameraPosition(s)),this.camera.up.set(0,1,0),this.camera.lookAt(e),this.camera.updateMatrixWorld(!0),this.target.copy(e),this.syncSharedTargetFromAvatar(),this.dispatchEvent({type:"change"})}resolveCameraPosition(e){const t=this.getCameraCollisionTarget(),n=e.clone().sub(t),s=n.length();if(s<=1e-6)return e;const o=n.normalize();if(!this.shouldDetectCameraCollision()&&Number.isFinite(this._lastCameraSafeDistance))return t.clone().addScaledVector(o,Math.min(this._lastCameraSafeDistance,s));const r=this.hitCameraObstacle(t,o,s);if(!r)return this._lastCameraSafeDistance=s,e;const A=Math.max(r.distance-this.cameraCollisionPadding,this.minCameraCollisionDistance);return this._lastCameraSafeDistance=Math.min(A,s),t.clone().addScaledVector(o,this._lastCameraSafeDistance)}getCameraCollisionTarget(){return this.avatarRoot.position.clone().add(new N(0,this.cameraCollisionTargetHeight,0))}shouldDetectCameraCollision(){return this._cameraCollisionFrame+=1,Number.isFinite(this._lastCameraSafeDistance)?this._cameraCollisionFrame%this.cameraCollisionInterval===0:!0}getControlPosition(){return this.avatarRoot.position.clone()}setAvatarXZ(e,t,n={}){return!Number.isFinite(e)||!Number.isFinite(t)?!1:(this.avatarRoot.position.x=e,this.avatarRoot.position.z=t,n.updateCamera!==!1&&this.updateCameraFromAvatar(),this.dispatchCameraChange(),!0)}placeAvatarAtPoint(e,t={}){return e instanceof N?(this.avatarRoot.position.copy(e),this.setAvatarHeight(this.avatarRoot.position.y),this.syncRotationStateFromCamera(),this.setViewYaw(this._yaw),t.updateCamera!==!1&&(this.updateCameraFromAvatar(),this.dispatchCameraChange()),!0):!1}rotateYaw(e){return Number.isFinite(e)?(this.setViewYaw(this._yaw+e),this.updateCameraFromAvatar(),this.dispatchCameraChange(),!0):!1}syncAvatarFromCameraTarget(e=this.target,t={}){if(!this.camera||!(e instanceof N))return!1;this.target.copy(e),this.avatarRoot.position.set(e.x,e.y-this.targetHeight,e.z);const n=this.camera.position.clone().sub(e),s=Math.hypot(n.x,n.z);if(s>1e-6&&this.setViewYaw(Math.atan2(-n.x,n.z)),t.preserveCameraDistance!==!1){const o=n.y-this.cameraHeight,r=Math.hypot(s,o);Number.isFinite(r)&&r>1e-6&&(this.cameraDistance=r,this._pitch=Ai.clamp(Math.atan2(o,s),this.minPitch,this.maxRotateX))}else this.syncRotationStateFromCamera();return this.syncSharedTargetFromAvatar(),this.dispatchEvent({type:"change"}),!0}flyToPoint(e,t={}){if(!(e instanceof N))return!1;const n=t.duration??500,s=this.avatarRoot.position.clone(),o=this.resolveAvatarFlightTarget(e),r=performance.now();this.resetMovementState(),this.setScriptedMotionActive(!0);const A=()=>{const a=performance.now()-r,l=Math.min(a/n,1),c=l<.5?2*l*l:1-Math.pow(-2*l+2,2)/2;this.avatarRoot.position.lerpVectors(s,o,c),this.updateCameraFromAvatar(),l<1?requestAnimationFrame(A):(this.setAvatarHeight(o.y),this.updateCameraFromAvatar(),this.setScriptedMotionActive(!1))};return requestAnimationFrame(A),!0}resolveAvatarFlightTarget(e){const t=e.clone(),n=e.clone().sub(this.avatarRoot.position);n.y=0,n.lengthSq()>1e-6&&(n.normalize(),t.addScaledVector(n,-(this.playerRadius+.2)));const s=this.getMinHeight();return this.gravityMinHeight&&s!==void 0&&t.y<s&&(t.y=s),t}syncRotationStateFromCamera(){if(!this.camera)return;const e=new N;this.camera.getWorldDirection(e);const t=e.clone();t.y=0,t.lengthSq()>1e-6&&(t.normalize(),this.setViewYaw(Math.atan2(t.x,-t.z))),this.setViewPitch(-Math.asin(e.y)),this.setViewYaw(this._yaw)}syncSharedTargetFromAvatar(){const e=[],t=n=>{!n?.target||e.includes(n)||e.push(n)};t(this),t(this._Engine?.controls),t(this._Engine?.controlModule?.orbitControls);for(const n of e)n.target.copy(this.target)}setScreenUp(e){return!e||!this.camera?!1:(this.camera.up.copy(e).normalize(),this.updateCameraFromAvatar(),!0)}gravityTest(){if(!this.applyGravity){this.setAvatarHeight(this.avatarRoot.position.y);return}let e=!0;this._fallingTime+=.01;const t=this.hitTest(new N(0,-1,0),this.playerHeight+2);if(!t)return;const n=t.point.y;if(this.positionEasing){if(n>=this.avatarRoot.position.y||n-this.avatarRoot.position.y<.2){this.setAvatarHeight(this.avatarRoot.position.y+(n-this.avatarRoot.position.y)*.08),this._fallingTime=0,e=!1;return}}else t.distance<this.playerHeight&&(this.setAvatarHeight(n),this._fallingTime=0,e=!1);e&&this.setAvatarHeight(this.avatarRoot.position.y-this.g*Math.pow(this._fallingTime,2))}setAvatarHeight(e){const t=this.getMinHeight();this.gravityMinHeight&&t!==void 0&&e<t?this.avatarRoot.position.y=t:this.avatarRoot.position.y=e}getMinHeight(){const e=this._Engine?.ToolUntils?this._Engine.ToolUntils.GetBoundingBox(this._Engine):null;return e?e.min.y:void 0}isBlocked(e,t){const n=this.hitTest(e,this.playerRadius+t+.05);return!!(n&&n.distance<this.playerRadius+t+.05)}hitCameraObstacle(e,t,n){if(!this._Engine?.handelBehaved?.handle_catch)return null;this._cameraRayCaster.ray.origin.copy(e),this._cameraRayCaster.ray.direction.copy(t).normalize(),this._cameraRayCaster.far=n;const s={},o=this._Engine.handelBehaved.handle_catch(this._cameraRayCaster,s,!1);return this._cameraRayCaster.far=1/0,!o||o.distance>=n?null:o}hitTest(e,t=1/0){const n=this.avatarRoot.position.clone().add(new N(0,this.playerHeight*.5,0));this._rayCaster.ray.origin.copy(n),this._rayCaster.ray.direction.copy(e).normalize(),this._rayCaster.far=t;const s={},o=this._Engine?.handelBehaved?.handle_catch?.(this._rayCaster,s,!1);if(this._rayCaster.far=1/0,o==null)return null;const r=o.object?.name,A=o.object?.url,a=this._Engine?.models?.find?.(l=>l.url===A);if(a&&r){const c=a.nodesMap?.get?.(r)?.infos?.[0]?.name;if(c&&(c.includes("门")||c.includes("門")||c.toLowerCase().includes("door")))return null}return o}dispatchCameraChange(){const e=new CustomEvent("bimengine:camerachange",{detail:""});window.dispatchEvent(e),this.dispatchEvent({type:"change"})}resetMovementState(){this._pressedKeys.clear(),this._moveInput.set(0,0,0),this._verticalVelocity=0,this._isJumping=!1,this._isJumpKeyDown=!1,this.updateAvatarFacing(),this.setAvatarWalking(!1),this._Engine&&(this._Engine.movefirst=!1),this.syncInteractionState()}dispose(){this.enabled=!1,this._avatarAnimationTimer.dispose(),this.avatarRoot?.parent&&this.avatarRoot.parent.remove(this.avatarRoot),this._avatarLoadRequestId++,this.clearAvatarAnimation(),this._ownsAvatarResources&&this.avatar&&this.disposeObjectResources(this.avatar)}disposeObjectResources(e){e.traverse(t=>{t.geometry&&t.geometry.dispose?.(),t.material&&(Array.isArray(t.material)?t.material.forEach(n=>n.dispose?.()):t.material.dispose?.())})}}class Gvt{constructor(e){this.engine=e}snapModelCache=new Map;applySnapPreview(e,t,n){const s=this.engine,o=e.object.url,r=e.object.name;let A=s.modelEdge.getModelEdge(o,r);A||(A=[0,0,[]]);const a=Nu(s,o),l=this.getModelSnapCache(o,r,A);s.camera.updateMatrixWorld(!0);const c=new nt().multiplyMatrices(s.camera.projectionMatrix,s.camera.matrixWorldInverse),h=s.renderer.domElement.clientWidth,d=s.renderer.domElement.clientHeight,g=new Ne(t.offsetX,t.offsetY),u=new ji,p=new N,m=new N,I=new Ne,B=new Ne,y=new N;let w="face",M=null,D=null,Q=100;if(n!=null){const b=e.point.clone(),P=e.normal||(e.face?e.face.normal:null);if(P&&e.object?.matrixWorld?.elements){const F=P.clone().transformDirection(e.object.matrixWorld).normalize(),x=new N().subVectors(n,b).dot(F),C=n.clone().sub(F.clone().multiplyScalar(x)),S=this.projectWorldPointToScreen(C,c,h,d,I,u);if(S!=null){const v=this.getDistanceSq(S.x,S.y,g.x,g.y);v<Q*4&&(Q=v,M={point:C,distanceSq:v,pointxy:S.clone(),style:"vertical"},w="point")}}}for(let b=0;b<l.localPoints.length;b+=3){if(p.set(l.localPoints[b],l.localPoints[b+1],l.localPoints[b+2]).applyMatrix4(a),s.clipping&&!s.clipping.isPointInClippingRange(p))continue;const P=this.projectWorldPointToScreen(p,c,h,d,I,u);if(P==null)continue;const F=this.getDistanceSq(P.x,P.y,g.x,g.y);F<Q&&(Q=F,M={point:p.clone(),distanceSq:F,pointxy:P.clone(),style:"rect"})}for(let b=0;b<l.localCenters.length;b+=3){if(p.set(l.localCenters[b],l.localCenters[b+1],l.localCenters[b+2]).applyMatrix4(a),s.clipping&&!s.clipping.isPointInClippingRange(p))continue;const P=this.projectWorldPointToScreen(p,c,h,d,I,u);if(P==null)continue;const F=this.getDistanceSq(P.x,P.y,g.x,g.y);F<Q&&(Q=F,M={point:p.clone(),distanceSq:F,pointxy:P.clone(),style:"default"})}if(M!=null)w="point";else{for(let b=0;b<l.localLines.length;b+=6){p.set(l.localLines[b],l.localLines[b+1],l.localLines[b+2]).applyMatrix4(a),m.set(l.localLines[b+3],l.localLines[b+4],l.localLines[b+5]).applyMatrix4(a);const P=this.projectWorldPointToScreen(p,c,h,d,I,u),F=this.projectWorldPointToScreen(m,c,h,d,B,u);if(P==null||F==null)continue;const T=this.pointToLineProjection(g,P,F),x=this.pointToLineDistanceSq(g,P,F);if(x<Q){const C=this.pointToLineProjection3D(T,p,m,c,y);if(s.clipping&&!s.clipping.isPointInClippingRange(C))continue;D={distanceSq:x,point:C.clone(),pointxy:this.projectWorldPointToScreen(C,c,h,d,I,u)?.clone()??P.clone(),start:P.clone(),end:F.clone(),style:"funnel"},Q=x}}D!=null&&(w="line")}return w==="point"&&M!=null?(this.renderPointCandidate(M),e.point=M.point,e):w==="line"&&D!=null?(this.renderLineCandidate(D),e.point=D.point,e):(this.renderFaceCandidate(e),e)}getModelSnapCache(e,t,n){const s=`${e}::${t}`,o=Array.isArray(n?.[2])?n[2]:[],r=this.snapModelCache.get(s);if(r&&r.source===o)return r;const A=new Float32Array(o.length*3),a=new Float32Array(o.length*3),l=new Float32Array(o.length*6);let c=0,h=0,d=0;o.forEach(u=>{if(u?.[0]==null||u?.[1]==null)return;const p=u[0],m=u[1];A[c++]=p.X,A[c++]=p.Z,A[c++]=-p.Y,a[h++]=(p.X+m.X)*.5,a[h++]=(p.Z+m.Z)*.5,a[h++]=(-p.Y-m.Y)*.5,l[d++]=p.X,l[d++]=p.Z,l[d++]=-p.Y,l[d++]=m.X,l[d++]=m.Z,l[d++]=-m.Y});const g={source:o,localPoints:A.subarray(0,c),localCenters:a.subarray(0,h),localLines:l.subarray(0,d)};return this.snapModelCache.set(s,g),g}projectWorldPointToScreen(e,t,n,s,o,r){if(r.set(e.x,e.y,e.z,1).applyMatrix4(t),Math.abs(r.w)<1e-10)return null;const A=1/r.w,a=r.x*A,l=r.y*A;return!Number.isFinite(a)||!Number.isFinite(l)?null:(o.set(a*n*.5+n*.5,-l*s*.5+s*.5),o)}getDistanceSq(e,t,n,s){const o=e-n,r=t-s;return o*o+r*r}pointToLineDistanceSq(e,t,n){const s=this.pointToLineProjection(e,t,n),o=t.x+(n.x-t.x)*s,r=t.y+(n.y-t.y)*s;return this.getDistanceSq(e.x,e.y,o,r)}pointToLineProjection(e,t,n){const s=new Ne().subVectors(n,t),o=s.lengthSq();if(o<1e-10)return 0;const r=new Ne().subVectors(e,t);return Ai.clamp(r.dot(s)/o,0,1)}pointToLineProjection3D(e,t,n,s,o){const r=Ai.clamp(e,0,1);if(!this.engine.camera.isPerspectiveCamera)return o.lerpVectors(t,n,r);const A=new ji(t.x,t.y,t.z,1).applyMatrix4(s),l=new ji(n.x,n.y,n.z,1).applyMatrix4(s).w*(1-r)+r*A.w,c=Math.abs(l)>1e-10?r*A.w/l:r;return o.lerpVectors(t,n,Ai.clamp(c,0,1))}renderPointCandidate(e){const t=this.engine,n=e.pointxy;t.catchSvg.innerHTML="";const s=n.x+t.reactBoundingClientRect.left,o=n.y+t.reactBoundingClientRect.top,r=document.createElementNS("http://www.w3.org/2000/svg","polygon");switch(r.setAttribute("class","catchPoint"),e.style){case"default":r.setAttribute("points",`${s},${o-8} ${s-7},${o+4} ${s+7},${o+4}`);break;case"funnel":r.setAttribute("points",`${s-7},${o-10} ${s+7},${o-10} ${s+1},${o-1} ${s},${o} ${s+7},${o+10} ${s-7},${o+10} ${s-1},${o}`);break;case"vertical":r.setAttribute("points",`${s-12},${o} ${s},${o} ${s},${o-12}`),r.setAttribute("fill","none");break;case"rect":r.setAttribute("points",`${s-8},${o-8} ${s+8},${o-8} ${s+8},${o+8} ${s-8},${o+8}`);break}r.setAttribute("stroke","rgb(8, 223, 215)"),r.setAttribute("fill","transparent"),t.catchSvg.appendChild(r)}renderLineCandidate(e){const t=this.engine,n=e.pointxy,s=e.start,o=e.end;t.catchSvg.innerHTML="";const r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("class","catchLine"),r.setAttribute("x1",(s.x+t.reactBoundingClientRect.left).toString()),r.setAttribute("y1",(s.y+t.reactBoundingClientRect.top).toString()),r.setAttribute("x2",(o.x+t.reactBoundingClientRect.left).toString()),r.setAttribute("y2",(o.y+t.reactBoundingClientRect.top).toString()),r.setAttribute("stroke","rgb(8, 223, 215)"),r.setAttribute("stroke-width","2"),t.catchSvg.appendChild(r);const A=n.x+t.reactBoundingClientRect.left,a=n.y+t.reactBoundingClientRect.top,l=document.createElementNS("http://www.w3.org/2000/svg","polygon");l.setAttribute("class","catchPoint"),l.setAttribute("points",`${A-7},${a-10} ${A+7},${a-10} ${A+1},${a-1} ${A},${a} ${A+7},${a+10} ${A-7},${a+10} ${A-1},${a}`),l.setAttribute("stroke","rgb(8, 223, 215)"),l.setAttribute("fill","transparent"),t.catchSvg.appendChild(l)}renderFaceCandidate(e){const t=this.engine,n=e.point.clone(),s=e.normal||(e.face?e.face.normal:null),o=(s?s.clone():new N(0,0,1)).normalize(),r=Math.abs(o.y)<.9?new N(0,1,0):new N(1,0,0),A=new N().crossVectors(o,r).normalize(),a=new N().crossVectors(o,A).normalize(),l=20,c=new po(t.camera,t.renderer,t.scene),h=c.worldToScreen(n),d=c.worldToScreen(new N().copy(n).add(A)),g=Math.sqrt((d.x-h.x)**2+(d.y-h.y)**2),u=g>0?l/g:.2,I=[new N().copy(A).add(a).multiplyScalar(u),new N().copy(A).sub(a).multiplyScalar(u),new N().copy(A).multiplyScalar(-1).sub(a).multiplyScalar(u),new N().copy(A).multiplyScalar(-1).add(a).multiplyScalar(u)].map(y=>new N().copy(n).add(y)).map(y=>c.worldToScreen(y));t.catchSvg.innerHTML="";const B=document.createElementNS("http://www.w3.org/2000/svg","polygon");B.setAttribute("class","catchFace"),B.setAttribute("points",I.map(y=>`${y.x+t.reactBoundingClientRect.left},${y.y+t.reactBoundingClientRect.top}`).join(" ")),B.setAttribute("fill","rgba(1, 238, 255, 0.2)"),B.setAttribute("stroke","rgb(0, 255, 247)"),B.setAttribute("stroke-width","1"),t.catchSvg.appendChild(B)}}function Nse(i){const e={self:null,options:null,mouseDownTime:0,mouseDownPosition:null,lastClickTime:0,touchLongPressTimer:null,touchLongPressActive:!1,touchLatestEvent:null,touchStartPosition:null,touchMagnifierCanvas:null,touchMagnifierContext:null,touchInputMode:null,touchPointerId:null,touchControlsSnapshot:null,mouseMoveFrame:null,latestMouseMoveEvent:null},t=800,n=28,s=132,o=44,r=168,A=new Gvt(i);e.handle_catch=function(J,W,ee=!0,q=!0){const ne=e.options;e.options={...ne??{},showCatch:ee};try{return Ae(J,W,!0,q)}finally{e.options=ne}},e.init=function(J,W){e.self!=null&&e.self.disActive!=null&&e.self.type!=J.type&&e.self.disActive(),e.self=J,W==null&&(W={showCatch:!1}),I(),e.clearLastPoint(),e.options=W,e.isClickSimpleModel=!0},e.render=function(){e.self&&e.self.render!=null&&e.self.render()};function a(){e.mouseMoveFrame!=null&&(cancelAnimationFrame(e.mouseMoveFrame),e.mouseMoveFrame=null),e.latestMouseMoveEvent=null}e.active=function(){i.renderer.domElement.addEventListener("mousedown",C),i.renderer.domElement.addEventListener("mouseup",v),i.renderer.domElement.addEventListener("mousemove",S),i.renderer.domElement.addEventListener("touchstart",O,{capture:!0,passive:!1}),i.renderer.domElement.addEventListener("touchend",$,{capture:!0,passive:!1}),i.renderer.domElement.addEventListener("touchcancel",$,{capture:!0,passive:!1}),i.renderer.domElement.addEventListener("touchmove",V,{capture:!0,passive:!1}),i.renderer.domElement.addEventListener("pointerdown",z,!0),i.renderer.domElement.addEventListener("pointermove",ie,!0),i.renderer.domElement.addEventListener("pointerup",te,!0),i.renderer.domElement.addEventListener("pointercancel",te,!0),window.addEventListener("keydown",l),window.addEventListener("keyup",c)},e.disActive=function(){I(),a(),P(),i.renderer.domElement.removeEventListener("mousedown",C),i.renderer.domElement.removeEventListener("mouseup",v),i.renderer.domElement.removeEventListener("mousemove",S),i.renderer.domElement.removeEventListener("touchstart",O,!0),i.renderer.domElement.removeEventListener("touchend",$,!0),i.renderer.domElement.removeEventListener("touchcancel",$,!0),i.renderer.domElement.removeEventListener("touchmove",V,!0),i.renderer.domElement.removeEventListener("pointerdown",z,!0),i.renderer.domElement.removeEventListener("pointermove",ie,!0),i.renderer.domElement.removeEventListener("pointerup",te,!0),i.renderer.domElement.removeEventListener("pointercancel",te,!0),window.removeEventListener("keydown",l),window.removeEventListener("keyup",c)};function l(J){(J.keyCode===8||J.keyCode===46)&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),J.keyCode===27&&e.self&&e.self.handelKeyEscDown!=null&&e.self.handelKeyEscDown(),J.keyCode===13&&e.self&&e.self.handelKeyEnterDown!=null&&e.self.handelKeyEnterDown(),J.keyCode===32&&e.self&&e.self.handelKeySpaceDown!=null&&e.self.handelKeySpaceDown(J),J.key==="Tab"&&e.self&&e.self.handelKeyTabDown!=null&&e.self.handelKeyTabDown(J),J.key==="Control"&&e.self&&e.self.handelKeyCtrlDown!=null&&e.self.handelKeyCtrlDown(),J.key==="Delete"&&e.self&&e.self.handelKeyDeleteDown!=null&&e.self.handelKeyDeleteDown(),J.key==="Shift"&&e.self&&e.self.handelKeyShiftDown!=null&&e.self.handelKeyShiftDown(),J.key==="Meta"&&e.self&&e.self.handelKeyMetaDown!=null&&e.self.handelKeyMetaDown()}function c(J){J.key==="Alt"&&e.self&&e.self.handelKeyAltUp!=null&&e.self.handelKeyAltUp(),J.key==="Tab"&&e.self&&e.self.handelKeyTabUp!=null&&e.self.handelKeyTabUp(),J.key==="Control"&&e.self&&e.self.handelKeyCtrlUp!=null&&e.self.handelKeyCtrlUp(),J.key==="Shift"&&e.self&&e.self.handelKeyShiftUp!=null&&e.self.handelKeyShiftUp(),J.key==="Meta"&&e.self&&e.self.handelKeyMetaUp!=null&&e.self.handelKeyMetaUp(),J.key==="Command"&&e.self&&e.self.handelKeyCommandUp!=null&&e.self.handelKeyCommandUp(),J.key==="Windows"&&e.self&&e.self.handelKeyWindowsUp!=null&&e.self.handelKeyWindowsUp()}function h(J){const W=new Ne,ee=i.renderer.domElement.clientWidth,q=i.renderer.domElement.clientHeight;return W.x=J.offsetX/ee*2-1,W.y=-(J.offsetY/q)*2+1,W}function d(J){const W=new Ao,ee=h(J);return W.setFromCamera(ee,i.camera),W}function g(){return i?.deviceModule?.isMobile?.()===!0||i?.deviceType==="mobile"}function u(){return g()&&e.options?.showCatch===!0}function p(J){const W=typeof TouchEvent<"u"&&J?.originalEvent instanceof TouchEvent;return u()&&!W}function m(){e.touchLongPressTimer!=null&&(clearTimeout(e.touchLongPressTimer),e.touchLongPressTimer=null)}function I(){m(),b(),w(),e.touchLongPressActive=!1,e.touchLatestEvent=null,e.touchStartPosition=null,e.touchInputMode=null,e.touchPointerId=null}function B(J){J?.preventDefault?.(),J?.stopPropagation?.(),J?.stopImmediatePropagation?.()}function y(){const J=i?.controls;!J||e.touchControlsSnapshot||(e.touchControlsSnapshot={controls:J,enabled:J.enabled!==!1},J.enabled=!1)}function w(){const J=e.touchControlsSnapshot;J&&(J.controls&&(M(J.controls),J.controls.enabled=J.enabled),e.touchControlsSnapshot=null)}function M(J){J?._pointers?.clear?.(),typeof J?.state=="number"&&(J.state=-1),J._isInteracting=!1,J._touchDistance=0,e.touchPointerId!=null&&J.domElement?.releasePointerCapture?.(e.touchPointerId)}function D(J){const W=J.touches[0]||J.changedTouches[0];return W?new Ne(W.clientX,W.clientY):null}function Q(){if(e.touchMagnifierCanvas)return e.touchMagnifierCanvas;const J=document.createElement("canvas"),W=Math.max(1,window.devicePixelRatio||1);return J.width=s*W,J.height=s*W,J.style.position="fixed",J.style.width=`${s}px`,J.style.height=`${s}px`,J.style.borderRadius="50%",J.style.border="2px solid rgba(0, 255, 247, 0.95)",J.style.boxShadow="0 8px 22px rgba(0, 0, 0, 0.32)",J.style.pointerEvents="none",J.style.zIndex="1002",J.style.display="none",J.style.background="#111",document.body.appendChild(J),e.touchMagnifierCanvas=J,e.touchMagnifierContext=J.getContext("2d"),J}function b(){const J=e.touchMagnifierCanvas;J&&(J.style.display="none")}function P(){e.touchMagnifierCanvas?.remove?.(),e.touchMagnifierCanvas=null,e.touchMagnifierContext=null}function F(J,W,ee,q,ne,Z){const K=i?.catchSvg;if(!K?.childElementCount)return;const re=i?.reactBoundingClientRect??W.getBoundingClientRect(),ue=le=>{const[ae,he]=le.split(",").map(Number);return Number.isFinite(ae)&&Number.isFinite(he)?[(ae-re.left-ee)/ne*s*Z,(he-re.top-q)/ne*s*Z]:null};Array.from(K.children).forEach(le=>{const ae=le.tagName.toLowerCase(),De=(ae==="line"?[`${le.getAttribute("x1")},${le.getAttribute("y1")}`,`${le.getAttribute("x2")},${le.getAttribute("y2")}`].map(ue):(le.getAttribute("points")||"").trim().split(/\s+/).map(ue)).filter(Boolean);De.length<2||(J.beginPath(),J.strokeStyle=le.getAttribute("stroke")||"rgb(8, 223, 215)",J.fillStyle=le.getAttribute("fill")||"transparent",J.lineWidth=Number(le.getAttribute("stroke-width")||2)*Z,J.moveTo(De[0][0],De[0][1]),De.slice(1).forEach(([Fe,Qe])=>J.lineTo(Fe,Qe)),ae==="polygon"&&(J.closePath(),["none","transparent"].includes(String(J.fillStyle))||J.fill()),J.stroke())})}function T(J){const W=i?.renderer?.domElement,ee=Q(),q=e.touchMagnifierContext;if(!W||!ee||!q)return;const ne=J?.catch?.point,Z=ne&&(i?.worldToScreen??new po(i.camera,i.renderer,i.scene)),K=Z?.worldToScreenIfVisible?.(ne)??Z?.worldToScreen?.(ne);if(!K||!Number.isFinite(K.x)||!Number.isFinite(K.y)||K.x<0||K.y<0||K.x>W.clientWidth||K.y>W.clientHeight){b();return}const re=ee.width/s,ue=Math.min(window.innerWidth-s/2-8,Math.max(s/2+8,J.clientX)),le=Math.min(window.innerHeight-s-8,Math.max(8,J.clientY-r));ee.style.left=`${ue-s/2}px`,ee.style.top=`${le}px`,ee.style.display="block";const ae=W.width/Math.max(1,W.clientWidth),he=W.height/Math.max(1,W.clientHeight),De=o,Fe=Math.max(0,Math.min(W.clientWidth-De,K.x-De/2)),Qe=Math.max(0,Math.min(W.clientHeight-De,K.y-De/2));q.save(),q.clearRect(0,0,ee.width,ee.height),q.beginPath(),q.arc(ee.width/2,ee.height/2,ee.width/2,0,Math.PI*2),q.clip(),q.fillStyle=window.getComputedStyle(W.parentElement??document.body).backgroundColor||"#dfe8f2",q.fillRect(0,0,ee.width,ee.height);try{q.drawImage(W,Fe*ae,Qe*he,De*ae,De*he,0,0,ee.width,ee.height),F(q,W,Fe,Qe,De,re)}catch{b(),q.restore();return}q.strokeStyle="rgba(0, 255, 247, 0.9)",q.lineWidth=1.5*re,q.beginPath(),q.moveTo(ee.width/2-10*re,ee.height/2),q.lineTo(ee.width/2+10*re,ee.height/2),q.moveTo(ee.width/2,ee.height/2-10*re),q.lineTo(ee.width/2,ee.height/2+10*re),q.stroke(),q.restore()}function x(J,W=!1,ee=!1,q=!0){const ne=d(J);if(J.raycaster=ne,W){const Z=Ae(ne,J,ee,q);J.catch=Z}}function C(J){p(J)||(e.mouseDownTime=Date.now(),e.mouseDownPosition=new N(J.offsetX,J.offsetY,0),e.self&&e.self.handleMouseDown!=null&&J.button==0&&(x(J,!0,!0),J.catch!=null&&(i.engineStatus.highlightModels==null||i.engineStatus.highlightModels.length==0)&&(i.engineStatus?.suppressNextOrbitOriginPick===!0?i.engineStatus.suppressNextOrbitOriginPick=!1:i.controlModule.orbitControls.origin.set(J.catch.point.x,J.catch.point.y,J.catch.point.z)),e.self.handleMouseDown(J)))}function S(J){p(J)||e.self&&e.self.handleMouseMove!=null&&(e.latestMouseMoveEvent=J,e.mouseMoveFrame==null&&(e.mouseMoveFrame=requestAnimationFrame(()=>{const W=e.latestMouseMoveEvent;e.latestMouseMoveEvent=null,e.mouseMoveFrame=null,W&&(i.engineStatus.isFree&&x(W,!0,!0,e.isClickSimpleModel),e.self.handleMouseMove(W))})))}function v(J){if(p(J))return;const W=Date.now(),ee=W-e.mouseDownTime,q=new N(J.offsetX,J.offsetY,0);e.self&&e.self.handleMouseUp!=null&&J.button==0&&(x(J,!1,!1,!1),e.self.handleMouseUp(J));const ne=q.distanceTo(e.mouseDownPosition);(ee<100||ne==0)&&e.self&&e.self.handleMouseClick!=null&&(x(J,!0,!0,!1),W-e.lastClickTime<200?e.self.handleMouseDoubleClick!=null&&J.button==0&&e.self.handleMouseDoubleClick(J):e.self.handleMouseClick!=null&&J.button==0?e.self.handleMouseClick(J):e.self.handleRightMouseClick!=null&&J.button==2&&e.self.handleRightMouseClick(J),e.lastClickTime=Date.now())}function Y(J){const W=J.touches[0]||J.changedTouches[0];if(!W)return null;const q=i.renderer.domElement.getBoundingClientRect(),ne=W.clientX-q.left,Z=W.clientY-q.top;return{offsetX:ne,offsetY:Z,button:0,clientX:W.clientX,clientY:W.clientY,preventDefault:()=>J.preventDefault(),stopPropagation:()=>J.stopPropagation(),originalEvent:J}}function k(J){const ee=i.renderer.domElement.getBoundingClientRect();return{offsetX:J.clientX-ee.left,offsetY:J.clientY-ee.top,button:J.button??0,clientX:J.clientX,clientY:J.clientY,preventDefault:()=>J.preventDefault(),stopPropagation:()=>J.stopPropagation(),originalEvent:J}}function j(J,W,ee,q=null){I(),e.touchInputMode=ee,e.touchPointerId=q,e.touchLatestEvent=J,e.touchStartPosition=W,e.touchLongPressTimer=window.setTimeout(()=>{const ne=e.touchLatestEvent;ne&&(e.touchLongPressActive=!0,y(),e.mouseDownTime=Date.now(),e.mouseDownPosition=new N(ne.offsetX,ne.offsetY,0),e.self?.handleMouseMove!=null&&(x(ne,!0,!0,e.isClickSimpleModel),e.self.handleMouseMove(ne)),T(ne))},t)}function R(J,W){e.touchLatestEvent=J;const ee=e.touchStartPosition;!e.touchLongPressActive&&ee&&W&&ee.distanceTo(W)>n&&m(),e.touchLongPressActive&&(e.self?.handleMouseMove!=null&&(x(J,!0,!0,e.isClickSimpleModel),e.self.handleMouseMove(J)),T(J))}function U(J){m(),e.touchLongPressActive&&(x(J,!0,!0,e.isClickSimpleModel),e.self?.handleMouseClick!=null&&e.self.handleMouseClick(J),e.self?.handleMouseUp!=null&&e.self.handleMouseUp(J)),I()}function O(J){if(J.preventDefault(),J.touches.length!==1){I();return}const W=Y(J);if(W){if(u()){j(W,D(J)??new Ne(W.clientX,W.clientY),"touch");return}C(W)}}function V(J){if(J.preventDefault(),J.touches.length!==1){I();return}const W=Y(J);if(W){if(u()){e.touchLongPressActive&&B(J),R(W,D(J));return}S(W)}}function $(J){J.preventDefault();const W=Y(J);if(W){if(u()){e.touchLongPressActive&&B(J),U(W);return}v(W)}}function z(J){if(J.pointerType!=="touch"||!u()||J.isPrimary===!1)return;const W=k(J);j(W,new Ne(J.clientX,J.clientY),"pointer",J.pointerId)}function ie(J){J.pointerType!=="touch"||!u()||(e.touchLongPressActive&&B(J),e.touchInputMode==="pointer"&&(e.touchPointerId!=null&&J.pointerId!==e.touchPointerId||R(k(J),new Ne(J.clientX,J.clientY))))}function te(J){J.pointerType!=="touch"||!u()||(e.touchLongPressActive&&B(J),e.touchInputMode==="pointer"&&(e.touchPointerId!=null&&J.pointerId!==e.touchPointerId||U(k(J))))}function Ae(J,W,ee=!1,q=!0){if(!i.engineStatus.isFree&&ee==!1){i.hoverHighLight.clearHighlight();return}if(i.engineStatus.editorMode=="simple")return;i.catchSvg.innerHTML="";let ne=i.octreeBox.rayInterationModel(J,ee,q);if(ne=i.clipping?.filterIntersectionsByClipping(ne)??ne,ne.length!==0)return e.options.showCatch?A.applySnapPreview(ne[0],W,e.lastPoint):ne[0]}return e.setLastPoint=function(J){e.lastPoint=J},e.clearLastPoint=function(){e.lastPoint=null},e}class jvt{engine;orbitControls;firstPersonControls;thirdPersonControls;isActive=!0;originDiv=null;mobileRoamControlsEl=null;mobileMovePointerId=null;mobileMoveActiveKeys=new Set;mobileMoveIntensity=0;mobileMoveSpeedBase=new WeakMap;mobileLookPointerId=null;mobileLookOffset={x:0,y:0};handelBehaved;pendingThirdPersonOptions=null;prevContainerCursor=null;roamLookDirection={horizontal:1,vertical:1};isDragging=!1;isDown=!1;containerOffset={left:0,top:0};constructor(e){this.engine=e,this.init(),this.handelBehaved=Nse(this.engine),this.handelBehaved.init(this,null),this.handelBehaved.active()}init(){this.orbitControls=new N2e(this.engine,this.engine.camera,this.engine.renderer.domElement),this.orbitControls.showOriginIcon=!0,this.firstPersonControls=new Y2e(this.engine,this.engine.camera,this.engine.renderer.domElement),this.thirdPersonControls=new G2e(this.engine,this.engine.camera,this.engine.renderer.domElement),this.applyRoamLookDirection(this.firstPersonControls),this.applyRoamLookDirection(this.thirdPersonControls);const e=document.createElement("div");this.originDiv=e,e.className="originDiv",e.style.position="absolute",e.style.top="0px",e.style.left="0px",e.style.width="30px",e.style.height="30px",e.style.borderRadius="50%",e.style.pointerEvents="none",e.style.backgroundImage=`url(${bn("/assets/svg/rotate-orbit.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:it&&it.tagName.toUpperCase()==="SCRIPT"&&it.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href)})`,this.engine.container.appendChild(this.originDiv)}active(){this.isActive=!0,this.orbitControls.enabled=!0}disActive(){this.isActive=!1,this.orbitControls.enabled=!1}setEngineControls(e){this.engine.controls=e,this.engine.bindControlEvents?.(e)}setMoveSpeed(e){const t=e*.1;this.firstPersonControls&&(this.firstPersonControls.moveSpeed=t,this.setMobileMoveBaseSpeed(this.firstPersonControls,t)),this.thirdPersonControls&&(this.thirdPersonControls.moveSpeed=t,this.setMobileMoveBaseSpeed(this.thirdPersonControls,t))}getMoveSpeed(){const e=this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls;return this.getMobileMoveBaseSpeed(e)*10}setApplyCollision(e){this.firstPersonControls&&(this.firstPersonControls.applyCollision=e),this.thirdPersonControls&&(this.thirdPersonControls.applyCollision=e)}getApplyCollision(){return(this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls)?.applyCollision}setApplyGravity(e){this.firstPersonControls&&(this.firstPersonControls.applyGravity=e),this.thirdPersonControls&&(this.thirdPersonControls.applyGravity=e),this.updateMobileVerticalControlsVisibility()}getApplyGravity(){return(this.getActiveRoamControl()||this.firstPersonControls||this.thirdPersonControls)?.applyGravity}setRoamLookDirection(e){(e?.horizontal===1||e?.horizontal===-1)&&(this.roamLookDirection.horizontal=e.horizontal),(e?.vertical===1||e?.vertical===-1)&&(this.roamLookDirection.vertical=e.vertical),this.applyRoamLookDirection(this.firstPersonControls),this.applyRoamLookDirection(this.thirdPersonControls)}getRoamLookDirection(){return{...this.roamLookDirection}}applyRoamLookDirection(e){e?.setLookDirection?.(this.roamLookDirection)}toggleMinMap(){this.engine.minMap.toggle()}switchFirstPersonMode(){this.engine.cameraModule.switchToPerspectiveCamera(),this.firstPersonControls&&(this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1),this.firstPersonControls=new Y2e(this.engine,this.engine.camera,this.engine.renderer.domElement,[]),this.applyRoamLookDirection(this.firstPersonControls),this.orbitControls.enabled=!1,this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!0,this.firstPersonControls.isActive=!0,this.firstPersonControls.syncRotationStateFromCamera?.(),this.firstPersonControls.syncSharedTargetFromCamera?.(),this.setEngineControls(this.firstPersonControls),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene),this.ensureMobileRoamControls()}switchThirdPersonMode(e){this.firstPersonControls&&(this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1),this.beginThirdPersonPlacement(e)}createThirdPersonControl(e){const t=this.thirdPersonControls,n={moveSpeed:t?.moveSpeed,applyCollision:t?.applyCollision,applyGravity:t?.applyGravity};return t?.dispose?.(),this.thirdPersonControls=new G2e(this.engine,this.engine.camera,this.engine.renderer.domElement,{...n,...e}),this.applyRoamLookDirection(this.thirdPersonControls),this.thirdPersonControls}beginThirdPersonPlacement(e){this.pendingThirdPersonOptions=e||{},this.orbitControls.enabled=!0,this.setEngineControls(this.orbitControls),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene),this.removeMobileRoamControls(),this.engine.container&&(this.prevContainerCursor=this.engine.container.style.cursor||"",this.engine.container.style.cursor="crosshair")}isWaitingThirdPersonPlacement(){return this.pendingThirdPersonOptions!=null}applyThirdPersonPlacement(e){if(!this.pendingThirdPersonOptions||!(e instanceof N))return!1;const t=this.pendingThirdPersonOptions;this.pendingThirdPersonOptions=null,this.engine.container&&this.prevContainerCursor!=null&&(this.engine.container.style.cursor=this.prevContainerCursor),this.prevContainerCursor=null,this.engine.cameraModule.switchToPerspectiveCamera();const n=this.createThirdPersonControl(t);return n.placeAvatarAtPoint?.(e,{updateCamera:!1}),this.orbitControls.enabled=!1,n.enabled=!0,n.isActive=!0,n.placeAvatarAtPoint?.(e),this.setEngineControls(n),this.engine.minMap?.show?.(),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene),this.ensureMobileRoamControls(),!0}setThirdPersonAvatar(e,t){this.thirdPersonControls?.setAvatarModel?.(e,t)}setThirdPersonMoveSpeed(e){this.thirdPersonControls&&(this.thirdPersonControls.moveSpeed=e*.1,this.setMobileMoveBaseSpeed(this.thirdPersonControls,this.thirdPersonControls.moveSpeed))}setThirdPersonApplyCollision(e){this.thirdPersonControls&&(this.thirdPersonControls.applyCollision=e)}setThirdPersonApplyGravity(e){this.thirdPersonControls&&(this.thirdPersonControls.applyGravity=e),this.updateMobileVerticalControlsVisibility()}getOrbitTargetFromCamera(e=10){const t=this.engine.camera,n=new N;return t.getWorldDirection(n),n.lengthSq()<=1e-8&&n.set(0,0,-1),t.position.clone().add(n.normalize().multiplyScalar(e))}switchDefaultMode(e){const t=e?.preserveCameraPose===!0;this.pendingThirdPersonOptions=null,this.engine.container&&this.prevContainerCursor!=null&&(this.engine.container.style.cursor=this.prevContainerCursor),this.prevContainerCursor=null,this.firstPersonControls&&(t||this.firstPersonControls.sanitizeCameraOrientation?.(),this.firstPersonControls.enabled=!1),this.thirdPersonControls&&(this.thirdPersonControls.enabled=!1);const n=this.engine.camera,s=t?this.orbitControls.target.clone():this.getOrbitTargetFromCamera(10),o=t&&this.orbitControls.origin?.clone?this.orbitControls.origin.clone():s.clone(),r=t&&this.orbitControls._referenceUp?.clone?this.orbitControls._referenceUp.clone():void 0,A=t&&this.orbitControls._viewRight?.clone?this.orbitControls._viewRight.clone():void 0;this.orbitControls.object=n,this.orbitControls.target.copy(s),this.orbitControls.syncStateFromCamera?.(n,s,{origin:o,referenceUp:r,viewRight:A}),this.orbitControls.enabled=!0,this.setEngineControls(this.orbitControls),this.orbitControls.update(!0),this.engine.worldToScreen=new po(this.engine.camera,this.engine.renderer,this.engine.scene),this.removeMobileRoamControls()}handleMouseUp(e){this.isDragging=!1,this.isDown=!1}handleMouseMove(e){this.isDown?this.isDragging=!0:this.isDragging=!1}handleMouseDown(e){this.isDown=!0}handleMouseClick(e){this.isDragging=!1,this.isDown=!1}isMobileDevice(){return this.engine?.deviceModule?.isMobile?.()===!0||this.engine?.deviceType==="mobile"}getActiveRoamControl(){return this.firstPersonControls?.enabled?this.firstPersonControls:this.thirdPersonControls?.enabled?this.thirdPersonControls:null}getMobileMoveBaseSpeed(e){return!e||typeof e.moveSpeed!="number"?0:(this.mobileMoveSpeedBase.has(e)||this.mobileMoveSpeedBase.set(e,e.moveSpeed),this.mobileMoveSpeedBase.get(e)??e.moveSpeed)}setMobileMoveBaseSpeed(e,t){!e||typeof t!="number"||this.mobileMoveSpeedBase.set(e,t)}restoreMobileMoveSpeed(){[this.firstPersonControls,this.thirdPersonControls].forEach(e=>{e&&typeof e.moveSpeed=="number"&&this.mobileMoveSpeedBase.has(e)&&(e.moveSpeed=this.mobileMoveSpeedBase.get(e)??e.moveSpeed)})}updateMobileMoveSpeed(){const e=this.getActiveRoamControl();if(!e||typeof e.moveSpeed!="number")return;const t=this.getMobileMoveBaseSpeed(e);if(this.mobileMovePointerId==null||this.mobileMoveActiveKeys.size===0||this.mobileMoveIntensity<=0){e.moveSpeed=t;return}const n=.25;e.moveSpeed=t*(n+(1-n)*this.mobileMoveIntensity)}createVirtualKeyEvent(e,t){const s={w:{keyCode:87,code:"KeyW",key:"w"},a:{keyCode:65,code:"KeyA",key:"a"},s:{keyCode:83,code:"KeyS",key:"s"},d:{keyCode:68,code:"KeyD",key:"d"},q:{keyCode:81,code:"KeyQ",key:"q"},e:{keyCode:69,code:"KeyE",key:"e"}}[e];return{key:s.key,code:s.code,keyCode:s.keyCode,type:t?"keydown":"keyup",preventDefault(){},stopPropagation(){}}}setVirtualKey(e,t){const n=this.getActiveRoamControl();if(!n||!e)return;n._isMouseInElement=!0;const s=this.createVirtualKeyEvent(e,t);t?n.onKeyDown?.(s):n.onKeyUp?.(s)}updateMobileMoveKeys(e){const t=new Set(e);this.mobileMoveActiveKeys.forEach(n=>{t.has(n)||this.setVirtualKey(n,!1)}),t.forEach(n=>{this.mobileMoveActiveKeys.has(n)||this.setVirtualKey(n,!0)}),this.mobileMoveActiveKeys=t}releaseMobileMoveKeys(){this.mobileMoveIntensity=0,this.updateMobileMoveKeys([]),this.restoreMobileMoveSpeed()}bindVirtualButton(e,t){let n=!1,s=null;const o=()=>{n&&(n=!1,s=null,e.classList.remove("is-active"),this.setVirtualKey(t,!1))},r=a=>{a.preventDefault(),a.stopPropagation(),!n&&(n=!0,s=a.pointerId,e.classList.add("is-active"),e.setPointerCapture?.(a.pointerId),this.setVirtualKey(t,!0))},A=a=>{a.preventDefault(),a.stopPropagation(),!(!n||s!==a.pointerId)&&(e.releasePointerCapture?.(a.pointerId),o())};e.addEventListener("pointerdown",r),e.addEventListener("pointerup",A),e.addEventListener("pointercancel",A),e.addEventListener("lostpointercapture",o)}createMobileRoamButton(e,t,n=""){const s=document.createElement("button");return s.type="button",s.className=`bim-mobile-roam-button ${n}`.trim(),s.innerHTML=e,s.setAttribute("aria-label",t==="q"?"Move up":t==="e"?"Move down":e),this.bindVirtualButton(s,t),s}bindMovePad(e){const t=e.querySelector(".bim-mobile-roam-move-knob"),n=o=>{const r=e.getBoundingClientRect(),A=Math.min(r.width,r.height)*.5,a=A*.48,l=A*.22,c=o.clientX-r.left-A,h=o.clientY-r.top-A,d=Math.hypot(c,h),g=Math.min(d,a),u=d>a?a/d:1,p=c*u,m=h*u;t&&(t.style.transform=`translate(${p}px, ${m}px)`);const I=[];h<-l?I.push("w"):h>l&&I.push("s"),c<-l?I.push("a"):c>l&&I.push("d"),this.mobileMoveIntensity=I.length===0?0:Math.max(0,Math.min(1,(g-l)/(a-l))),this.updateMobileMoveKeys(I)};e.addEventListener("pointerdown",o=>{o.preventDefault(),o.stopPropagation(),this.mobileMovePointerId=o.pointerId,e.classList.add("is-active"),e.setPointerCapture?.(o.pointerId),n(o)}),e.addEventListener("pointermove",o=>{this.mobileMovePointerId===o.pointerId&&(o.preventDefault(),o.stopPropagation(),n(o))});const s=o=>{this.mobileMovePointerId===o.pointerId&&(o.preventDefault(),o.stopPropagation(),e.classList.remove("is-active"),e.releasePointerCapture?.(o.pointerId),this.mobileMovePointerId=null,t&&(t.style.transform=""),this.releaseMobileMoveKeys())};e.addEventListener("pointerup",s),e.addEventListener("pointercancel",s)}rotateActiveRoamView(e,t){const n=this.getActiveRoamControl();n&&(typeof n.rotateByPointerDelta=="function"?n.rotateByPointerDelta(e,t):(n.rotateX?.(e),n.rotateY?.(t*2),n.dispatchEvent?.({type:"change"}),window.dispatchEvent(new CustomEvent("bimengine:camerachange",{detail:""}))))}updateMobileLookRotation(){if(this.mobileLookPointerId==null||this.mobileLookOffset.x===0&&this.mobileLookOffset.y===0)return;const e=2.8;this.rotateActiveRoamView(this.mobileLookOffset.x*e,this.mobileLookOffset.y*e)}updateMobileVerticalControlsVisibility(){const e=this.mobileRoamControlsEl?.querySelector(".bim-mobile-roam-vertical-pad");e&&(e.style.display=this.getActiveRoamControl()?.applyGravity?"none":"flex")}ensureMobileRoamControls(){if(!this.isMobileDevice()){this.removeMobileRoamControls();return}if(this.mobileRoamControlsEl){this.mobileMovePointerId=null,this.releaseMobileMoveKeys(),this.mobileLookPointerId=null,this.mobileLookOffset={x:0,y:0},this.getActiveRoamControl()?.setExternalLookActive?.(!1),this.mobileRoamControlsEl.querySelectorAll(".is-active").forEach(o=>o.classList.remove("is-active")),this.mobileRoamControlsEl.querySelectorAll(".bim-mobile-roam-look-knob, .bim-mobile-roam-move-knob").forEach(o=>o.style.transform=""),this.firstPersonControls?.resetMovementState?.(),this.thirdPersonControls?.resetMovementState?.(),this.mobileRoamControlsEl.style.display="flex",this.updateMobileVerticalControlsVisibility();return}const e=document.createElement("div");e.className="bim-mobile-roam-controls",e.addEventListener("contextmenu",o=>o.preventDefault());const t=document.createElement("div");t.className="bim-mobile-roam-pad bim-mobile-roam-move-pad";const n=document.createElement("span");n.className="bim-mobile-roam-move-knob",t.appendChild(n),this.bindMovePad(t);const s=document.createElement("div");s.className="bim-mobile-roam-vertical-pad",s.appendChild(this.createMobileRoamButton("&#8593;","q","is-round")),s.appendChild(this.createMobileRoamButton("&#8595;","e","is-round")),e.appendChild(t),e.appendChild(s),this.engine.container.appendChild(e),this.mobileRoamControlsEl=e,this.updateMobileVerticalControlsVisibility()}removeMobileRoamControls(){this.mobileMovePointerId=null,this.releaseMobileMoveKeys(),this.mobileLookPointerId=null,this.mobileLookOffset={x:0,y:0},this.getActiveRoamControl()?.setExternalLookActive?.(!1),this.mobileRoamControlsEl&&(this.mobileRoamControlsEl.remove(),this.mobileRoamControlsEl=null),this.firstPersonControls?.resetMovementState?.(),this.thirdPersonControls?.resetMovementState?.()}update(){if(this.updateMobileMoveSpeed(),this.updateMobileLookRotation(),this.firstPersonControls.enabled&&this.firstPersonControls.update(),this.thirdPersonControls?.enabled&&this.thirdPersonControls.update(),this.orbitControls.enabled){const e=this.engine.controlModule.orbitControls.origin,n=this.engine.worldToScreen.worldToScreen(e);this.originDiv&&this.isDragging?(this.originDiv.style.left=n.x-15+this.engine.reactBoundingClientRect.left+"px",this.originDiv.style.top=n.y-15+this.engine.reactBoundingClientRect.top+"px",this.originDiv.style.display="block"):this.originDiv&&(this.originDiv.style.display="none")}}dispose(){this.isActive=!1,this.handelBehaved?.disActive?.(),this.orbitControls?.dispose?.(),this.firstPersonControls?.dispose?.(),this.thirdPersonControls?.dispose?.(),this.removeMobileRoamControls(),this.originDiv?.remove(),this.originDiv=null,this.orbitControls=null,this.firstPersonControls=null,this.thirdPersonControls=null,this.handelBehaved=null}}const xS={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`
5981
5981
 
5982
5982
  varying vec2 vUv;
5983
5983