iflow-engine-base 3.7.13 → 3.7.14

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.
@@ -5257,7 +5257,7 @@ void main() {
5257
5257
  #include <tonemapping_fragment>
5258
5258
  #include <colorspace_fragment>
5259
5259
 
5260
- }`};const Tx={turbidity:10,rayleigh:3,mieCoefficient:.005,mieDirectionalG:.7,elevation:2,azimuth:180,exposure:.5,orthoExposureScale:1.5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},xf="sunrise_clear",Dx=.2,bf=[{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}}],Bx=bf.reduce((n,e)=>(n[e.id]=e,n),{}),Px=2e6;class dD{engine;sky=null;sun=new w.Vector3;params={...Tx,...Bx[xf].params};currentPreset=xf;currentIntensity=Dx;currentEnvironmentTarget=null;skyScale=45e4;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=w.NoToneMapping;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){if(!this.engine?.scene)return;if(this.sky){this.sky.visible=!0,this._captureSceneState(),this._expandCameraFarForSky(),this._applyParamsToSky();return}const e=new Rc;e.scale.setScalar(this.skyScale),e.name=this.skyName,this.sky=e,this.engine.scene.add(e),this._captureSceneState(),this._expandCameraFarForSky(),this.engine.renderer&&(this.engine.renderer.toneMapping=w.ACESFilmicToneMapping,this.engine.scene.background=null),this._applyParamsToSky()}close(e=!0){this.sky&&(this._restoreCameraFar(),this._restoreSceneState(e),e?(this.engine?.scene?.remove(this.sky),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null):this.sky.visible=!1)}isActive(){return this.sky!=null&&this.engine?.scene?.children?.includes(this.sky)}getParams(){return{...this.params}}setParams(e){Object.assign(this.params,e),this._applyParamsToSky(),this.engine?.renderer&&(e.exposure!==void 0||e.orthoExposureScale!==void 0)&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}setPreset(e){const t=Bx[e];t&&(this.currentPreset=e,this.params={...Tx,...t.params},this._applyParamsToSky(),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()))}getCurrentPreset(){return this.currentPreset}getPresetNames(){return bf.map(e=>e.id)}getPresetList(){return bf.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){if(this.currentIntensity=Math.max(e,0),!(!this.sky?.visible||!this.engine?.scene)){if(!this.currentEnvironmentTarget){this._refreshEnvironmentMap();return}this.engine.scene.environmentIntensity=this.currentIntensity}}getIntensity(){return this.currentIntensity}update(e){if(!this.sky?.visible)return;const t=this.sky.material.uniforms;t&&"time"in t&&(t.time.value=e??performance.now()*.001),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}_isOrthographicCamera(){const e=this.engine?.camera;return e!=null&&e.type==="OrthographicCamera"}_getEffectiveExposure(){const e=this.params.exposure;return this._isOrthographicCamera()?e*this.params.orthoExposureScale:e}_expandCameraFarForSky(){const e=this.engine?.camera;if(!e||typeof e.far!="number")return;const t=e.far;t>=Px||(this.savedCameraFar==null&&(this.savedCameraFar=t),e.far=Px,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix())}_restoreCameraFar(){if(this.savedCameraFar==null||!this.engine?.camera)return;const e=this.engine.camera;typeof e.far=="number"&&(e.far=this.savedCameraFar,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;const e=this.sky.material.uniforms;this._setUniformValue(e,"turbidity",this.params.turbidity),this._setUniformValue(e,"rayleigh",this.params.rayleigh),this._setUniformValue(e,"mieCoefficient",this.params.mieCoefficient),this._setUniformValue(e,"mieDirectionalG",this.params.mieDirectionalG),this._setUniformValue(e,"cloudCoverage",this.params.cloudCoverage),this._setUniformValue(e,"cloudDensity",this.params.cloudDensity),this._setUniformValue(e,"cloudElevation",this.params.cloudElevation),this._setUniformValue(e,"showSunDisc",this.params.showSunDisc?1:0);const t=w.MathUtils.degToRad(90-this.params.elevation),i=w.MathUtils.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,t,i),this._setUniformValue(e,"sunPosition",this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=w.ACESFilmicToneMapping,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure(),this.sky.visible&&this._refreshEnvironmentMap())}_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??w.NoToneMapping,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(e){!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),e&&(this._disposeEnvironmentTarget(),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=w.NoToneMapping,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1))}_refreshEnvironmentMap(){if(!this.sky||!this.engine?.renderer||!this.engine?.scene)return;this._disposeEnvironmentTarget();const e=new w.Scene,t=this.sky.clone();t.material=this.sky.material.clone(),e.add(t);const i=new w.PMREMGenerator(this.engine.renderer);this.currentEnvironmentTarget=i.fromScene(e,0,.1,this.skyScale*2),i.dispose(),this.engine.scene.background=null,this.engine.scene.environment=this.currentEnvironmentTarget.texture,this.engine.scene.environmentIntensity=this.currentIntensity,t.material.dispose()}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_setUniformValue(e,t,i){const s=e[t];s&&(i instanceof w.Vector3&&typeof s.value?.copy=="function"?s.value.copy(i):s.value=i)}}class fD{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()||[],i=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(s=>this._toPresetItem(s)),hdr:t.map(s=>this._toPresetItem(s)),sky:i.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?.switchModel(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.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===w.NoToneMapping&&(t.toneMapping=w.ACESFilmicToneMapping),t.toneMappingExposure=2*e,t.toneMappingExposure==1?this.engine.renderer.toneMapping=0:this.engine.renderer.toneMapping=w.ACESFilmicToneMapping)}_syncSettingsFromModules(){this.settings=this._readCurrentSettingsFromModules()}_buildDefaultSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,t=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,s=this.engine.renderer?.toneMappingExposure,r=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??wn,a=this.engine.hdr?.getIntensity?.(),l=this.engine.skyManager?.getIntensity?.(),c=this.engine.skyManager?.getCurrentPreset?.()??xf,h=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()),contrast:this._uniformToPercent(t,sA),saturation:this._uniformToPercent(e,nA),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),Ec),lightIntensity:this._exposureToPercent(s,Vm),gtaoIntensity:this._unitToPercent(i,iA)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??Af,edgeOpacity:this._unitToPercent(r,Ix),showGrid:this.engine.grid?.getVisible?.()??gf,showLevel:this.engine.level?.getVisible?.()??Ex,showGround:this.engine.ground?.getVisible?.()??Cx,groundId:this.engine.ground?.getCurrentId?.()??wx,groundHeight:this.engine.ground?.getHeight?.()??Sx},environment:{type:h?"sky":o!==wn?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,Mx),skyPreset:c,skyParams:{},skyIntensity:this._unitToPercent(l,Dx)}}}_readCurrentSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,t=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,s=this.engine.renderer?.toneMappingExposure,r=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??this.settings.environment.hdrId,a=this.engine.hdr?.getIntensity?.(),l=this.engine.skyManager?.getIntensity?.(),c=this.engine.skyManager?.getCurrentPreset?.()??this.settings.environment.skyPreset,h=this.engine.skyManager?.getParams?.(),u=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()??this.settings.render.mode),contrast:this._uniformToPercent(t,this.settings.render.contrast/100+.5),saturation:this._uniformToPercent(e,this.settings.render.saturation/100+.5),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),this.settings.render.shadowIntensity/50),lightIntensity:this._exposureToPercent(s,this.settings.render.lightIntensity/50),gtaoIntensity:this._unitToPercent(i,this.settings.render.gtaoIntensity/100)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??this.settings.display.showEdge,edgeOpacity:this._unitToPercent(r,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:u?"sky":o!==wn?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,this.settings.environment.hdrIntensity/100),skyPreset:c,skyParams:h?this._clone(h):this._clone(this.settings.environment.skyParams),skyIntensity:this._unitToPercent(l,this.settings.environment.skyIntensity/100)}}}_toRenderMode(e){return e==="simple"||e==="balance"||e==="advanced"?e:ux}_uniformToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent((i-.5)*100)}_shadowToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*50)}_exposureToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*50)}_unitToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*100)}_clampPercent(e){return Math.min(100,Math.max(0,Math.round(e)))}_getDirectionalLightShadowIntensity(){const e=this.engine.scene?.children?.filter(i=>i instanceof w.DirectionalLight);return!e||e.length===0?Ec:(e.find(i=>i.castShadow)??e[0]).shadow?.intensity??Ec}_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(wn),t===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),t===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!==wn){if(await this.engine.hdr?.setHdr(e.hdrId),t!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setIntensity(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(i=>i instanceof w.DirectionalLight);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 sn(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var e=Math.random()*16|0,t=n=="x"?e:e&3|8;return t.toString(16)})}class Kn{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Rd(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 i=this.setting.unit,s=i;return t==1?i=="mm"?e=e*1e3:i=="cm"?e=e*100:i=="dm"?e=e*10:i=="m"?e=e*1:i=="km"&&(e=e*.001):t==2&&(i=="mm"?e=e*1e3*1e3:i=="cm"?e=e*100*100:i=="dm"?e=e*10*10:i=="m"?e=e*1*1:i=="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(i=>{i.highlight==!0&&(i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData,t=!0;for(let i in e)for(let s=e[i].length-1;s>=0;s--){let r=e[i][s];r.isSelect==!0&&(r.container.remove(),e[i].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 i=e[t].length-1;i>=0;i--){let s=e[t][i];s.highlight==!0&&(s.container.remove(),e[t].splice(i,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(i=>{i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;this.engine.measure.annotationData.normalAnnotation.forEach(p=>{d(p)}),this.engine.measure.annotationData.elevationAnnotation.forEach(p=>{f(p)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(p=>{u(p)}),this.engine.measure.annotationData.angleAnnotation.forEach(p=>{l(p)}),this.engine.measure.annotationData.areaAnnotation.forEach(p=>{c(p)}),this.engine.measure.annotationData.slopeAnnotation.forEach(p=>{h(p)});function l(p){if(p.container==null){let I=['<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">'+p.text+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="angle-annotation",p.container.id=p.id,p.container.style.pointerEvents="none",p.container.innerHTML=I,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point1),m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point2),A=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point3),x=e.engine.reactBoundingClientRect.left,b=e.engine.reactBoundingClientRect.top;g.x+=x,g.y+=b,m.x+=x,m.y+=b,A.x+=x,A.y+=b;let y=p.container;y.getElementsByTagName("circle")[0].setAttribute("cx",g.x),y.getElementsByTagName("circle")[0].setAttribute("cy",g.y),y.getElementsByTagName("circle")[1].setAttribute("cx",m.x),y.getElementsByTagName("circle")[1].setAttribute("cy",m.y),y.getElementsByTagName("circle")[2].setAttribute("cx",A.x),y.getElementsByTagName("circle")[2].setAttribute("cy",A.y),y.getElementsByTagName("polyline")[0].setAttribute("points",g.x+","+g.y+" "+m.x+","+m.y),y.getElementsByTagName("polyline")[1].setAttribute("points",m.x+","+m.y+" "+A.x+","+A.y);let _=m.x,E=m.y-30;y.getElementsByTagName("rect")[0].setAttribute("x",_-40),y.getElementsByTagName("rect")[0].setAttribute("y",E-12.5),y.getElementsByTagName("text")[0].setAttribute("x",_),y.getElementsByTagName("text")[0].setAttribute("y",E+4),y.getElementsByTagName("text")[0].innerHTML=p.text,y.style.top="0px",y.style.left="0px"}function c(p){if(p.container==null){let S=['<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(p.text,2)+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="area-annotation",p.container.id=p.id,p.container.innerHTML=S,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}if(!p.points||p.points.length<2)return;let g=e.engine.reactBoundingClientRect.left,m=e.engine.reactBoundingClientRect.top,A=[],x=0,b=0;for(let S=0;S<p.points.length;S++){let P=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.points[S]);P.x+=g,P.y+=m,A.push(P),x+=P.x,b+=P.y}x=x/A.length,b=b/A.length;let y=A.map(S=>S.x+","+S.y).join(" "),_=[...A];A.length>=3&&_.push(A[0]);let E=_.map(S=>S.x+","+S.y).join(" "),I=p.container;I.getElementsByTagName("polygon")[0].setAttribute("points",A.length>=3?y:""),I.getElementsByTagName("polyline")[0].setAttribute("points",E);let B=x,C=b;I.getElementsByTagName("rect")[0].setAttribute("x",B-40),I.getElementsByTagName("rect")[0].setAttribute("y",C-12.5),I.getElementsByTagName("text")[0].setAttribute("x",B+10),I.getElementsByTagName("text")[0].setAttribute("y",C+4),I.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(p.text,2),I.style.top="0px",I.style.left="0px"}function h(p){if(p.container==null){let E=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+p.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-'+p.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"> '+p.text+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="slope-annotation",p.container.id=p.id,p.container.innerHTML=E,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point1),m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point2),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;g.x+=A,g.y+=x,m.x+=A,m.y+=x;let b=p.container;b.getElementsByTagName("polyline")[0].setAttribute("points",g.x+","+g.y+" "+m.x+","+m.y);let y=(g.x+m.x)/2,_=(g.y+m.y)/2-30;b.getElementsByTagName("rect")[0].setAttribute("x",y-50),b.getElementsByTagName("rect")[0].setAttribute("y",_-12.5),b.getElementsByTagName("text")[0].setAttribute("x",y),b.getElementsByTagName("text")[0].setAttribute("y",_+4),b.getElementsByTagName("text")[0].innerHTML=p.text,b.style.top="0px",b.style.left="0px"}function u(p){if(p.container==null){let I=['<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(p.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(-p.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(p.textY,1)+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="coordinate-annotation",p.container.id=p.id,p.container.style.position="absolute",p.container.style.pointerEvents="none",p.container.innerHTML=I,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=p.container,m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;m.x+=A,m.y+=x,g.style.top="0px",g.style.left="0px";let b=g.getElementsByTagName("circle")[0];b&&(b.setAttribute("cx",m.x),b.setAttribute("cy",m.y));let y=g.getElementsByTagName("rect"),_=g.getElementsByTagName("text"),E=-55;y[0]&&(y[0].setAttribute("x",m.x+10),y[0].setAttribute("y",m.y+10+E)),_[0]&&(_[0].setAttribute("x",m.x+10+50),_[0].setAttribute("y",m.y+10+16+E)),y[1]&&(y[1].setAttribute("x",m.x+10),y[1].setAttribute("y",m.y+10+30+E)),_[1]&&(_[1].setAttribute("x",m.x+10+50),_[1].setAttribute("y",m.y+10+46+E)),y[2]&&(y[2].setAttribute("x",m.x+10),y[2].setAttribute("y",m.y+10+60+E)),_[2]&&(_[2].setAttribute("x",m.x+10+50),_[2].setAttribute("y",m.y+10+76+E)),_[0]&&(_[0].innerHTML="X: "+e.getMeasureText(p.textX,1)),_[1]&&(_[1].innerHTML="Y: "+e.getMeasureText(-p.textZ,1)),_[2]&&(_[2].innerHTML="Z: "+e.getMeasureText(p.textY,1))}function f(p){if(p.container==null){let b=['<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(p.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("");p.container=document.createElement("div"),p.container.className="elevation-annotation",p.container.id=p.id,p.container.style.position="absolute",p.container.style.pointerEvents="none",p.container.innerHTML=b,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=p.container,m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;g.style.top=m.y+x-48+"px",g.style.left=m.x+A-16+"px",g.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(p.text,1)}function d(p){if(p.container==null){let y=['<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(p.text,1)+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="normal-annotation",p.container.id=p.id,p.container.innerHTML=y,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=p.container;if(p.point1==null||p.point2==null){g.style.display="none";return}else g.style.display="block";let m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point1),A=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point2),x=e.engine.reactBoundingClientRect.left,b=e.engine.reactBoundingClientRect.top;m.x+=x,m.y+=b,A.x+=x,A.y+=b,g.getElementsByTagName("polyline")[0].setAttribute("points",m.x+","+m.y+" "+A.x+","+A.y),g.getElementsByTagName("circle")[0].setAttribute("cx",m.x),g.getElementsByTagName("circle")[0].setAttribute("cy",m.y),g.getElementsByTagName("circle")[1].setAttribute("cx",A.x),g.getElementsByTagName("circle")[1].setAttribute("cy",A.y),g.getElementsByTagName("rect")[0].setAttribute("x",m.x*.5+A.x*.5-40),g.getElementsByTagName("rect")[0].setAttribute("y",m.y*.5+A.y*.5-12.5),g.getElementsByTagName("text")[0].setAttribute("x",m.x*.5+A.x*.5+50-40),g.getElementsByTagName("text")[0].setAttribute("y",m.y*.5+A.y*.5+16-12.5),g.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(p.text,1),g.style.top="0px",g.style.left="0px"}}}class pD{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new Kn(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}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let s=0;s<e.length;s++){const r=e[s];if(!r)continue;typeof r.updateMatrixWorld=="function"&&r.updateMatrixWorld(!0);const o=new w.Box3().setFromObject(r);!Number.isFinite(o.min.y)||!Number.isFinite(o.max.y)||(o.min.y<t&&(t=o.min.y),o.max.y>i&&(i=o.max.y))}return!Number.isFinite(t)||!Number.isFinite(i)?null:{minY:t,maxY:i}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let r=this.engine.interactionModule.getCatchMeshs(e);var i=this.getMeshesMinMaxY(r);this.catchDir==0?t.set(t.x,i?.minY,t.z):t.set(t.x,i?.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(r=>r.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:sn(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=e.catch;if(this.type=="element"){let s=e.catch.point.clone();s.set(s.x,this.points[0].y,s.z);let r=new w.Raycaster(s.add(new w.Vector3(0,.01,0)),new w.Vector3(0,this.catchDir==0?-1:1,0));i.point=this.points[0];const o=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(r))??this.engine.octreeBox.rayInterationModel(r);if(o.length===0){t.point2=null;return}t.point1=s,t.point2=o[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(St.MeasureChanged,t)}else{let s=new w.Raycaster(e.catch.point.clone().add(new w.Vector3(0,.01,0)),new w.Vector3(0,this.catchDir==0?-1:1,0));const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(s))??this.engine.octreeBox.rayInterationModel(s);if(r.length===0){t.point2=null;return}t.point1=i.point,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(St.MeasureChanged,t)}}}class gD{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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 i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);if(i==null)return;i.point2=t.point,i.isSelect=!1,this.points=[],this.engine.events.trigger(St.MeasureChanged,i),this.behavior.clearLastPoint()}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);i==null&&(i={id:sn(),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(i)),i.point2=t.point,i.text=i.point1.clone().distanceTo(i.point2.clone())}}}class mD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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(i=>i.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(o=>o.isSelect==!0);t==null&&(t={text:null,id:sn(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=new w.Raycaster(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(i))??this.engine.octreeBox.rayInterationModel(i);if(s.length==0){t.point2=null;return}let r=e.catch;t.point1=r.point,t.point2=s[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(St.MeasureChanged,t)}}class AD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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(i=>i.isSelect==!0);t==null&&(t={id:sn(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t)),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(i=>i.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.text=e.catch.point.y,this.engine.events.trigger(St.MeasureChanged,t))}}class xD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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(i=>i.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(i=>i.isSelect==!0);if(t==null){t={id:sn(),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(St.MeasureChanged,t)}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(St.MeasureChanged,e))}}class bD{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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,i){const s=new w.Vector3().subVectors(e,t),r=new w.Vector3().subVectors(i,t),o=s.length(),a=r.length();if(o===0||a===0)return 0;const c=s.dot(r)/(o*a),h=Math.max(-1,Math.min(1,c));return Math.acos(h)*(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 i=this.engine.measure.annotationData.angleAnnotation.find(s=>s.isSelect==!0);if(i==null)return;i.point3=t.point.clone(),i.angle=this.calculateAngle(i.point1,i.point2,i.point3),i.text=i.angle.toFixed(2)+"°",i.isSelect=!1,i.type="angle",this.points=[],this.engine.events.trigger(St.MeasureChanged,i)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:sn(),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)}}}class yD{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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,i=new w.Vector3(0,0,0);for(let s=0;s<t;s++){const r=(s+1)%t;i.x+=(e[s].y-e[r].y)*(e[s].z+e[r].z),i.y+=(e[s].z-e[r].z)*(e[s].x+e[r].x),i.z+=(e[s].x-e[r].x)*(e[s].y+e[r].y)}return i.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 i=this.getCurrentDrawingMeasure();i==null?(i={id:sn(),points:this.points.map(s=>s.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(i)):i.points=this.points.map(s=>s.clone()),this.points.length>=3?(i.area=this.calculateArea(this.points),i.text=i.area):(i.area=0,i.text=0)}handleMouseMove(e){if(e.catch!=null&&this.points.length>=1){let t=this.getCurrentDrawingMeasure();t==null&&(t={id:sn(),points:[],area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t));const i=this.points.map(s=>s.clone());i.push(e.catch.point.clone()),t.points=i,i.length>=3?(t.area=this.calculateArea(i),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(St.MeasureChanged,e)):this.engine.measure.tools.handelKeyEscDown()}}class vD{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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 i=t.y-e.y,s=t.x-e.x,r=t.z-e.z,o=Math.sqrt(s*s+r*r);if(o===0)return{percentage:0,angle:0,heightDiff:i,horizontalDist:0,type:"slope"};const a=i/o*100,c=Math.atan(i/o)*(180/Math.PI);return{percentage:a,angle:c,heightDiff:i,horizontalDist:o,type:"slope"}}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){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);if(i==null)return;console.log("进来了"),i.point2=t.point.clone();const s=this.calculateSlope(i.point1,i.point2);i.slopePercentage=s.percentage,i.slopeAngle=s.angle,i.heightDiff=s.heightDiff,i.horizontalDist=s.horizontalDist,i.text=s.percentage.toFixed(2)+"%",i.isSelect=!1,this.points=[],this.engine.events.trigger(St.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);i==null&&(i={id:sn(),point1:this.points[0].clone(),point2:t.point.clone(),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00%",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(i)),i.point2=t.point.clone();const s=this.calculateSlope(i.point1,i.point2);i.slopePercentage=s.percentage,i.slopeAngle=s.angle,i.heightDiff=s.heightDiff,i.horizontalDist=s.horizontalDist,i.text=s.percentage.toFixed(2)+"%"}}}class _D{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 i=this.points[0].clone(),s=this.projectPointToFace(i,t);if(s==null)return;let r=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);r==null&&(r={id:sn(),type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(r)),r.point1=i,r.point2=s.footPoint,r.text=s.distance,r.facePoint=t.point.clone(),r.faceNormal=t.normal.clone(),r.isSelect=!1,this.points=[],this.behavior?.clearLastPoint?.(),this.engine.events.trigger(St.MeasureChanged,r)}handleMouseMove(e){if(e.catch==null||this.points.length!==1)return;const t=this.getFaceInfo(e.catch);if(t==null)return;const i=this.points[0].clone(),s=this.projectPointToFace(i,t);if(s==null)return;let r=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);r==null&&(r={id:sn(),point1:i.clone(),point2:s.footPoint.clone(),text:s.distance,type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(r)),r.point1=i,r.point2=s.footPoint,r.text=s.distance,r.facePoint=t.point.clone(),r.faceNormal=t.normal.clone()}getFaceInfo(e){if(e?.face==null||e?.point==null)return null;const t=e.point.clone?.(),i=this.getWorldFaceNormal(e);return!(t instanceof w.Vector3)||i==null?null:{point:t,normal:i}}getWorldFaceNormal(e){const t=e?.normal??e?.face?.normal;if(t==null)return null;const i=t.clone(),s=e?.matrix??e?.object?.matrixWorld;return s!=null&&i.transformDirection(s),i.lengthSq()<1e-10?null:i.normalize()}projectPointToFace(e,t){const i=new w.Vector3().subVectors(e,t.point).dot(t.normal),s=e.clone().sub(t.normal.clone().multiplyScalar(i));return{footPoint:s,distance:e.distanceTo(s)}}}class wD{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 pD(e),this.distanceMeasure=new gD(e),this.clearDistanceMeasure=new mD(e),this.elevationMeasure=new AD(e),this.pointMeasure=new xD(e),this.angleMeasure=new bD(e),this.areaMeasure=new yD(e),this.slopeMeasure=new vD(e),this.faceDistanceMeasure=new _D(e),this.tools=new Kn(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}active(){this.isActive=!0,this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){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.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 i=0;i<t.length;i++)t[i].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.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}}class SD{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;faceIdleOpacity=0;faceHoverOpacity=.05;transformControls=new Map;transformAnchors=new Map;transformHelpers=new Map;faceMetaMap=new Map;isSyncingTransform=!1;transformHandleSize=1.05;transformHandleColor=16777215;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};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 i=t[0];this.isDrag=!0,this.pickPoint=i.point.clone(),this.pickMesh=i.object;const s=this.pickMesh?.userData?.dragNormal?.clone?.(),r=i.face?.normal?.clone?.();if(this.pickNormal=(s??r??new w.Vector3(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 o=new w.Plane;o.setFromNormalAndCoplanarPoint(new w.Vector3(0,1,0),this.pickPoint),this.plane=o}else{const o=new w.Vector3(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),a=new w.Plane;a.setFromNormalAndCoplanarPoint(o.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,i){return new w.Vector3(Math.max(t.x,Math.min(i.x,e.x)),Math.max(t.y,Math.min(i.y,e.y)),Math.max(t.z,Math.min(i.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 i=new w.Vector3;if(e.raycaster.ray.intersectPlane(this.plane,i)){const s=i.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(!!this.pickMesh?.userData?.isMinFace){const o=this.box_.min.clone().add(this.pickNormal.clone().setLength(s));this.box.min=this.clampVector3(o,this.maxBox.min,this.box.max)}else{const o=this.box_.max.clone().add(this.pickNormal.clone().setLength(s));this.box.max=this.clampVector3(o,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,i=this.maxBox.max.z-this.maxBox.min.z,s=this.toPercent((this.box.min.x-this.maxBox.min.x)/e*100),r=this.toPercent((this.box.max.x-this.maxBox.min.x)/e*100),o=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),l=this.toPercent((this.box.min.z-this.maxBox.min.z)/i*100),c=this.toPercent((this.box.max.z-this.maxBox.min.z)/i*100),h={x:{min:s,max:r},y:{min:o,max:a},z:{min:l,max:c}};this.engine.events.trigger(St.SectionMove,h)}toPercent(e){return e<0?0:e>100?100:e}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const t=new w.Raycaster,i=new w.Vector2,s=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/s*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}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),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)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}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 w.Plane);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 i=e.getHelper(),s=[];i.traverse(r=>{if(r?.name!==t||!r.geometry)return;const o=r.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const l=a.getCenter(new w.Vector3);if(!(t==="X"&&l.x<0||t==="Y"&&l.y<0||t==="Z"&&l.z<0))return;const h=o.parameters,u=h&&h.radiusTop===0&&h.radiusBottom===.04&&h.height===.1,f=h&&h.radiusTop===.2&&h.radiusBottom===0&&h.height===.6;(u||f)&&s.push(r)}),s.forEach(r=>{r.parent?.remove(r)})}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,i=this.engine.camera;if(!t||!i)return;const s=new w.Object3D;s.name=`SectionBoxTransformAnchor_${e}`,s.visible=this.isActive,this.engine.scene.add(s);const r=new xx(i,t);r.name=`SectionBoxTransformControl_${e}`,r.setMode("translate"),r.setSpace("local"),r.showX=!0,r.showY=!1,r.showZ=!1,r.size=this.transformHandleSize,r.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),r.enabled=this.isActive,r.attach(s),this.keepSingleDirectionArrow(r,"X"),r.addEventListener("dragging-changed",a=>{this.engine.controls.enabled=!a.value,a.value===!0?this.clearClippingBoxFill():this.updateClippingBoxFill()}),r.addEventListener("objectChange",()=>{this.handleTransformObjectChange(e)});const o=r.getHelper();o.visible=this.isActive,this.engine.scene.add(o),this.transformAnchors.set(e,s),this.transformControls.set(e,r),this.transformHelpers.set(e,o)}updateFaceTransformControl(e,t,i,s){this.ensureFaceTransformControl(e);const r=this.transformAnchors.get(e),o=this.transformControls.get(e);if(!r||!o)return;const a=this.getFaceTransformOffset(),l=new w.Quaternion().setFromUnitVectors(new w.Vector3(1,0,0),t.clone().normalize()),c=i.clone().add(t.clone().setLength(a));this.faceMetaMap.set(e,{normal:t.clone().normalize(),isMinFace:s,center:i.clone()}),this.isSyncingTransform=!0,r.position.copy(c),r.quaternion.copy(l),r.visible=this.isActive,o.object!==r&&o.attach(r),o.enabled=this.isActive;const h=this.transformHelpers.get(e);h&&(h.visible=this.isActive),this.isSyncingTransform=!1}getDominantAxis(e){const t=Math.abs(e.x),i=Math.abs(e.y),s=Math.abs(e.z);return t>=i&&t>=s?"x":i>=t&&i>=s?"y":"z"}handleTransformObjectChange(e){if(this.isSyncingTransform)return;const t=this.transformAnchors.get(e),i=this.faceMetaMap.get(e);if(!t||!i||!this.box||!this.maxBox)return;const s=i.normal,r=this.getDominantAxis(s),o=this.getFaceTransformOffset(),a=s[r],l=t.position[r]-a*o;if(i.isMinFace){const c=this.maxBox.min[r],h=this.box.max[r];this.box.min[r]=Math.max(c,Math.min(h,l))}else{const c=this.box.min[r],h=this.maxBox.max[r];this.box.max[r]=Math.max(c,Math.min(h,l))}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 w.Group,t.name="ClippingBox",this.engine.scene.add(t)),[{name:"前",normal:new w.Vector3(0,0,-1),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.min.z)]},{name:"后",normal:new w.Vector3(0,0,1),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.max.z)]},{name:"右",normal:new w.Vector3(1,0,0),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)]},{name:"左",normal:new w.Vector3(-1,0,0),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z)]},{name:"顶",normal:new w.Vector3(0,1,0),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.min.z)]},{name:"底",normal:new w.Vector3(0,-1,0),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.min.y,e.max.z)]}].forEach(s=>{this.createFace(t,s.vertices,s.normal,s.name,s.isMinFace,s.planePoint)}),Bd(this.engine).forEach(s=>{s.material&&Array.isArray(s.material)?s.material.forEach(r=>{r.clippingPlanes=this.engine.sectionPlane}):s.material.clippingPlanes=this.engine.sectionPlane})}createFace(e,t,i,s,r,o){const a=new w.BufferGeometry,l=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]),c=[0,2,1,0,3,2];a.setAttribute("position",new w.BufferAttribute(l,3)),a.setIndex(c);let h=this.meshs.find(A=>A.name===s);if(h==null){const A=new w.MeshBasicMaterial({color:65280,transparent:!0,opacity:this.faceIdleOpacity,side:w.DoubleSide});A.polygonOffset=!0,A.polygonOffsetFactor=1,A.polygonOffsetUnits=4,h=new w.Mesh(a,A),h.name=s,e.add(h),this.meshs.push(h)}else h.geometry=a;h.userData={dragNormal:i.clone(),isMinFace:r,faceName:s};const u=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]),f=new w.LineBasicMaterial({color:255}),d=new w.BufferGeometry;d.setAttribute("position",new w.BufferAttribute(u,3));let p=this.meshs.find(A=>A.name===s+"Line");p==null?(p=new w.Line(d,f),p.name=s+"Line",e.add(p),this.meshs.push(p)):(p.geometry=d,p.material=f);const g=new w.Vector3;t.forEach(A=>g.add(A)),g.multiplyScalar(1/t.length),this.updateFaceTransformControl(s,i,g,r);const m=this.engine.sectionPlane.find(A=>A.name==s);m&&m.setFromNormalAndCoplanarPoint(i.clone().setLength(-1),o)}}class CD{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 w.Vector3(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;idleOpacity=.02;hoverOpacity=.05;transformControl=null;transformAnchor=null;transformHelper=null;isSyncingTransformControl=!1;moveEpsilon=1e-5;transformHandleSize=1.15;transformHandleColor=16777215;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};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.transformAnchor||!this.center)return;const e=this.normal.clone().normalize(),t=this.getDistanceRange(e),i=this.getTransformHandleOffset(),s=this.transformAnchor.position.clone().sub(this.center).dot(e)-i,r=Math.min(t.max,Math.max(t.min,s));Math.abs(r-Number(this.distance))>this.moveEpsilon?this.updata_face(r):Math.abs(s-r)>this.moveEpsilon&&this.updateTransformControl(e)};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){if(this.isActive==!0)return;this.isActive=!0,this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(i=>{i.name.includes("face")&&(i.visible=!0)})}),this.attachListeners(),this.ensureTransformControl(),this.setTransformControlVisible(!0);const e=this;Bd(e.engine).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name=="face"),t)}),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(i=>{i.name.includes("face")&&(i.visible=!1)})})}init(e){const t=this.engine.octreeBox.getBoundingBox();this.box=t,this.distance=0,this.center=new w.Vector3((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,i){this.angleX=e,this.angleY=t,this.angleZ=i,this.distance=0,this.normal=new w.Vector3(0,1,0).applyAxisAngle(new w.Vector3(1,0,0),e).applyAxisAngle(new w.Vector3(0,0,1),t).applyAxisAngle(new w.Vector3(0,1,0),i).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 i=this.engine.sectionPlane?.find(s=>s.name==="face");if(i){const s=this.center.clone().add(this.normal.clone().multiplyScalar(t));i.setFromNormalAndCoplanarPoint(this.normal.clone().multiplyScalar(this.direction),s)}this.updateClippingFaceFill()}activateClippingOnly(){if(this.isActive)return;this.isActive=!0;const e=this;Bd(e.engine).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name==="face"),t)})}reverse(){this.direction=this.direction*-1,this.updata_face(this.distance),this.updateClippingFaceFill()}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e){if(!this.box)return;this.distance=e;let t=this.engine.scene.children.find(b=>b.type=="Group"&&b.name=="ClippingBox");t==null&&(t=new w.Group,t.name="ClippingBox",this.engine.scene.add(t));const i=this.normal.clone().normalize(),s=this.center??new w.Vector3((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=s.clone();const{tangent:r,bitangent:o}=this.getPlaneBasis(i),a=this.getBoxCorners(this.box),l=this.box.min.distanceTo(this.box.max),c=Math.max(l*.02,.01);let h=1/0,u=-1/0,f=1/0,d=-1/0;a.forEach(b=>{const y=b.clone().sub(s),_=y.dot(r),E=y.dot(o);h=Math.min(h,_),u=Math.max(u,_),f=Math.min(f,E),d=Math.max(d,E)}),h-=c,u+=c,f-=c,d+=c;const p=i.clone().multiplyScalar(e),g=s.clone().add(r.clone().multiplyScalar(h)).add(o.clone().multiplyScalar(f)).add(p),m=s.clone().add(r.clone().multiplyScalar(u)).add(o.clone().multiplyScalar(f)).add(p),A=s.clone().add(r.clone().multiplyScalar(u)).add(o.clone().multiplyScalar(d)).add(p),x=s.clone().add(r.clone().multiplyScalar(h)).add(o.clone().multiplyScalar(d)).add(p);this.current_center=s.clone().add(p),this.createFace(t,[g,m,A,x],i,"face"),this.updateTransformControl(i)}createFace(e,t,i,s){const r=new w.BufferGeometry,o=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=[0,1,2,0,2,3];r.setAttribute("position",new w.BufferAttribute(o,3)),r.setIndex(a);let l=this.meshs.find(p=>p.name==s);if(l==null){const p=new w.MeshBasicMaterial({color:65280,transparent:!0,opacity:this.idleOpacity,side:w.DoubleSide});p.polygonOffset=!0,p.polygonOffsetFactor=1,p.polygonOffsetUnits=4,l=new w.Mesh(r,p),l.name=s,e.add(l),this.meshs.push(l)}else l.geometry=r;l.normal=i.clone();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 w.LineBasicMaterial({color:255}),u=new w.BufferGeometry;u.setAttribute("position",new w.BufferAttribute(c,3));let f=this.meshs.find(p=>p.name==s+"Line");f==null?(f=new w.Line(u,h),f.name=s+"Line",e.add(f),this.meshs.push(f)):(f.geometry=u,f.material=h);const d=this.engine.sectionPlane.find(p=>p.name==s);d&&this.current_center&&d.setFromNormalAndCoplanarPoint(i.clone().setLength(this.direction),this.current_center)}getPlaneBasis(e){const t=new w.Vector3(1,0,0),i=new w.Vector3(0,1,0),s=new w.Vector3(0,0,1),r=Math.abs(e.dot(t)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(s));let l=t;o<=r&&o<=a?l=i:a<=r&&a<=o&&(l=s),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new w.Vector3().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}getBoxCorners(e){return[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const t=this.center??new w.Vector3((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),i=this.getBoxCorners(this.box);let s=1/0,r=-1/0;return i.forEach(o=>{const a=o.clone().sub(t).dot(e);s=Math.min(s,a),r=Math.max(r,a)}),{min:s,max:r}}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)}keepSingleDirectionArrow(e,t="X"){const i=e.getHelper(),s=[];i.traverse(r=>{if(r?.name!==t||!r.geometry)return;const o=r.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const l=a.getCenter(new w.Vector3);if(!(t==="X"&&l.x<0||t==="Y"&&l.y<0||t==="Z"&&l.z<0))return;const h=o.parameters,u=h&&h.radiusTop===0&&h.radiusBottom===.04&&h.height===.1,f=h&&h.radiusTop===.2&&h.radiusBottom===0&&h.height===.6;(u||f)&&s.push(r)}),s.forEach(r=>{r.parent?.remove(r)})}ensureTransformControl(){if(this.transformControl&&this.transformAnchor)return;const e=this.engine.renderer?.domElement,t=this.engine.camera;if(!e||!t)return;const i=new w.Object3D;i.name="SectionFaceTransformAnchor",i.visible=this.isActive,this.engine.scene.add(i);const s=new xx(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(i),this.keepSingleDirectionArrow(s,"X"),s.addEventListener("dragging-changed",o=>{this.engine.controls.enabled=!o.value,o.value===!0?this.clearClippingFaceFill():this.updateClippingFaceFill()}),s.addEventListener("objectChange",this.handleTransformObjectChange);const r=s.getHelper();r.visible=this.isActive,this.engine.scene.add(r),this.transformAnchor=i,this.transformControl=s,this.transformHelper=r}setTransformControlVisible(e){this.ensureTransformControl(),this.transformControl&&(this.transformControl.enabled=e),this.transformHelper&&(this.transformHelper.visible=e),this.transformAnchor&&(this.transformAnchor.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(),i=this.current_center.clone().add(e.clone().setLength(t)),s=new w.Quaternion().setFromUnitVectors(new w.Vector3(1,0,0),e.clone().normalize().multiplyScalar(-1));this.isSyncingTransformControl=!0,this.transformAnchor.position.copy(i),this.transformAnchor.quaternion.copy(s),this.transformAnchor.visible=this.isActive,this.transformControl.object!==this.transformAnchor&&this.transformControl.attach(this.transformAnchor),this.transformControl.enabled=this.isActive,this.transformHelper&&(this.transformHelper.visible=this.isActive),this.isSyncingTransformControl=!1}createRaycasterFromMouseEvent(e){const t=new w.Raycaster,i=new w.Vector2,s=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/s*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}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),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)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}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 i=t[0],s=i.point.clone();this.isDrag=!0,this.pickPoint=s;const o=(i.face?.normal?.clone()??this.normal.clone()).clone();if(o.dot(this.normal)<0&&o.multiplyScalar(-1),o.normalize(),this.pickNormal=o,this.engine.controls.enabled=!1,this.dragStartDistance=Number(this.distance)||0,o.y==0){const a=new w.Plane;a.setFromNormalAndCoplanarPoint(new w.Vector3(0,1,0),s),this.plane=a}else{const a=new w.Vector3(this.engine.camera.position.x,s.y,this.engine.camera.position.z),l=new w.Plane;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.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 i=this.pickPoint,s=this.pickNormal,r=this.plane;if(i!=null&&s!=null&&r!=null){const o=new w.Vector3;if(e.raycaster.ray.intersectPlane(r,o)){const a=o.clone().sub(i.clone()).dot(s.clone()),l=this.getDistanceRange(this.normal.clone().normalize()),c=this.dragStartDistance+a;this.distance=Math.min(l.max,Math.max(l.min,c)),this.updata_face(this.distance)}}}}class MD{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})}}const Lx=0,ED=1,ID=2,Rx=2,yf=1.25,kx=1,li=32,Wt=li/4,Fx=65535,TD=Math.pow(2,-24),vf=Symbol("SKIP_GENERATION");function DD(n){return n.index?n.index.count:n.attributes.position.count}function fr(n){return DD(n)/3}function BD(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function PD(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=BD(t,i);n.setIndex(new v.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function Ox(n,e){const t=fr(n),i=e||n.drawRange,s=i.start/3,r=(i.start+i.count)/3,o=Math.max(0,s),a=Math.min(t,r)-o;return[{offset:Math.floor(o),count:Math.floor(a)}]}function Ux(n,e){if(!n.groups||!n.groups.length)return Ox(n,e);const t=[],i=e||n.drawRange,s=i.start/3,r=(i.start+i.count)/3,o=fr(n),a=[];for(const h of n.groups){const{start:u,count:f}=h,d=u/3,p=isFinite(f)?f:o*3-u,g=(u+p)/3;d<r&&g>s&&(a.push({pos:Math.max(s,d),isStart:!0}),a.push({pos:Math.min(r,g),isStart:!1}))}a.sort((h,u)=>h.pos!==u.pos?h.pos-u.pos:h.type==="end"?-1:1);let l=0,c=null;for(const h of a){const u=h.pos;l!==0&&u!==c&&t.push({offset:c,count:u-c}),l+=h.isStart?1:-1,c=u}return t}function _f(n,e,t,i,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,u=1/0,f=1/0,d=1/0,p=-1/0,g=-1/0,m=-1/0;const A=n.offset||0;for(let x=(e-A)*6,b=(e+t-A)*6;x<b;x+=6){const y=n[x+0],_=n[x+1],E=y-_,I=y+_;E<r&&(r=E),I>l&&(l=I),y<u&&(u=y),y>p&&(p=y);const B=n[x+2],C=n[x+3],S=B-C,P=B+C;S<o&&(o=S),P>c&&(c=P),B<f&&(f=B),B>g&&(g=B);const T=n[x+4],R=n[x+5],M=T-R,F=T+R;M<a&&(a=M),F>h&&(h=F),T<d&&(d=T),T>m&&(m=T)}i[0]=r,i[1]=o,i[2]=a,i[3]=l,i[4]=c,i[5]=h,s[0]=u,s[1]=f,s[2]=d,s[3]=p,s[4]=g,s[5]=m}function Nx(n,e,t=null,i=null,s=null){const r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(s===null)s=new Float32Array(t*6),s.offset=e;else if(e<0||t+e>s.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,c=r.offset||0;let h=3;r.isInterleavedBufferAttribute&&(h=r.data.stride);const u=["getX","getY","getZ"],f=s.offset;for(let d=e,p=e+t;d<p;d++){const m=(i?i[d]:d)*3,A=(d-f)*6;let x=m+0,b=m+1,y=m+2;o&&(x=o[x],b=o[b],y=o[y]),a||(x=x*h+c,b=b*h+c,y=y*h+c);for(let _=0;_<3;_++){let E,I,B;a?(E=r[u[_]](x),I=r[u[_]](b),B=r[u[_]](y)):(E=l[x+_],I=l[b+_],B=l[y+_]);let C=E;I<C&&(C=I),B<C&&(C=B);let S=E;I>S&&(S=I),B>S&&(S=B);const P=(S-C)/2,T=_*2;s[A+T+0]=C+P,s[A+T+1]=P+(Math.abs(C)+P)*TD}}return s}function It(n,e,t){return t.min.x=e[n],t.min.y=e[n+1],t.min.z=e[n+2],t.max.x=e[n+3],t.max.y=e[n+4],t.max.z=e[n+5],t}function zx(n){let e=-1,t=-1/0;for(let i=0;i<3;i++){const s=n[i+3]-n[i];s>t&&(t=s,e=i)}return e}function Gx(n,e){e.set(n)}function Vx(n,e,t){let i,s;for(let r=0;r<3;r++){const o=r+3;i=n[r],s=e[r],t[r]=i<s?i:s,i=n[o],s=e[o],t[o]=i>s?i:s}}function kc(n,e,t){for(let i=0;i<3;i++){const s=e[n+2*i],r=e[n+2*i+1],o=s-r,a=s+r;o<t[i]&&(t[i]=o),a>t[i+3]&&(t[i+3]=a)}}function Ma(n){const e=n[3]-n[0],t=n[4]-n[1],i=n[5]-n[2];return 2*(e*t+t*i+i*e)}const $n=32,LD=(n,e)=>n.candidate-e.candidate,Ms=new Array($n).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Fc=new Float32Array(6);function RD(n,e,t,i,s,r){let o=-1,a=0;if(r===Lx)o=zx(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===ED)o=zx(n),o!==-1&&(a=kD(t,i,s,o));else if(r===ID){const l=Ma(n);let c=yf*s;const h=t.offset||0,u=(i-h)*6,f=(i+s-h)*6;for(let d=0;d<3;d++){const p=e[d],A=(e[d+3]-p)/$n;if(s<$n/4){const x=[...Ms];x.length=s;let b=0;for(let _=u;_<f;_+=6,b++){const E=x[b];E.candidate=t[_+2*d],E.count=0;const{bounds:I,leftCacheBounds:B,rightCacheBounds:C}=E;for(let S=0;S<3;S++)C[S]=1/0,C[S+3]=-1/0,B[S]=1/0,B[S+3]=-1/0,I[S]=1/0,I[S+3]=-1/0;kc(_,t,I)}x.sort(LD);let y=s;for(let _=0;_<y;_++){const E=x[_];for(;_+1<y&&x[_+1].candidate===E.candidate;)x.splice(_+1,1),y--}for(let _=u;_<f;_+=6){const E=t[_+2*d];for(let I=0;I<y;I++){const B=x[I];E>=B.candidate?kc(_,t,B.rightCacheBounds):(kc(_,t,B.leftCacheBounds),B.count++)}}for(let _=0;_<y;_++){const E=x[_],I=E.count,B=s-E.count,C=E.leftCacheBounds,S=E.rightCacheBounds;let P=0;I!==0&&(P=Ma(C)/l);let T=0;B!==0&&(T=Ma(S)/l);const R=kx+yf*(P*I+T*B);R<c&&(o=d,c=R,a=E.candidate)}}else{for(let y=0;y<$n;y++){const _=Ms[y];_.count=0,_.candidate=p+A+y*A;const E=_.bounds;for(let I=0;I<3;I++)E[I]=1/0,E[I+3]=-1/0}for(let y=u;y<f;y+=6){let I=~~((t[y+2*d]-p)/A);I>=$n&&(I=$n-1);const B=Ms[I];B.count++,kc(y,t,B.bounds)}const x=Ms[$n-1];Gx(x.bounds,x.rightCacheBounds);for(let y=$n-2;y>=0;y--){const _=Ms[y],E=Ms[y+1];Vx(_.bounds,E.rightCacheBounds,_.rightCacheBounds)}let b=0;for(let y=0;y<$n-1;y++){const _=Ms[y],E=_.count,I=_.bounds,C=Ms[y+1].rightCacheBounds;E!==0&&(b===0?Gx(I,Fc):Vx(I,Fc,Fc)),b+=E;let S=0,P=0;b!==0&&(S=Ma(Fc)/l);const T=s-b;T!==0&&(P=Ma(C)/l);const R=kx+yf*(S*b+P*T);R<c&&(o=d,c=R,a=_.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}function kD(n,e,t,i){let s=0;const r=n.offset;for(let o=e,a=e+t;o<a;o++)s+=n[(o-r)*6+i*2];return s/t}class wf{constructor(){this.boundingData=new Float32Array(6)}}function FD(n,e,t,i,s,r){let o=i,a=i+s-1;const l=r.pos,c=r.axis*2,h=t.offset||0;for(;;){for(;o<=a&&t[(o-h)*6+c]<l;)o++;for(;o<=a&&t[(a-h)*6+c]>=l;)a--;if(o<a){for(let u=0;u<3;u++){let f=e[o*3+u];e[o*3+u]=e[a*3+u],e[a*3+u]=f}for(let u=0;u<6;u++){const f=o-h,d=a-h,p=t[f*6+u];t[f*6+u]=t[d*6+u],t[d*6+u]=p}o++,a--}else return o}}function OD(n,e,t,i,s,r){let o=i,a=i+s-1;const l=r.pos,c=r.axis*2,h=t.offset||0;for(;;){for(;o<=a&&t[(o-h)*6+c]<l;)o++;for(;o<=a&&t[(a-h)*6+c]>=l;)a--;if(o<a){let u=n[o];n[o]=n[a],n[a]=u;for(let f=0;f<6;f++){const d=o-h,p=a-h,g=t[d*6+f];t[d*6+f]=t[p*6+f],t[p*6+f]=g}o++,a--}else return o}}let Qx,Oc,Sf,jx;const UD=Math.pow(2,32);function Cf(n){return"count"in n?1:1+Cf(n.left)+Cf(n.right)}function ND(n,e,t){return Qx=new Float32Array(t),Oc=new Uint32Array(t),Sf=new Uint16Array(t),jx=new Uint8Array(t),Mf(n,e)}function Mf(n,e){const t=n/4,i=n/2,s="count"in e,r=e.boundingData;for(let o=0;o<6;o++)Qx[t+o]=r[o];if(s)return e.buffer?(jx.set(new Uint8Array(e.buffer),n),n+e.buffer.byteLength):(Oc[t+6]=e.offset,Sf[i+14]=e.count,Sf[i+15]=Fx,n+li);{const{left:o,right:a,splitAxis:l}=e,c=n+li;let h=Mf(c,o);const u=n/li,d=h/li-u;if(d>UD)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Oc[t+6]=d,Oc[t+7]=l,Mf(h,a)}}function zD(n,e,t){const s=(n.index?n.index.count:n.attributes.position.count)/3>2**16,r=t.reduce((h,u)=>h+u.count,0),o=s?4:2,a=e?new SharedArrayBuffer(r*o):new ArrayBuffer(r*o),l=s?new Uint32Array(a):new Uint16Array(a);let c=0;for(let h=0;h<t.length;h++){const{offset:u,count:f}=t[h];for(let d=0;d<f;d++)l[c+d]=u+d;c+=f}return l}function GD(n,e,t,i,s){const{maxDepth:r,verbose:o,maxLeafTris:a,strategy:l,onProgress:c,indirect:h}=s,u=n._indirectBuffer,f=n.geometry,d=f.index?f.index.array:null,p=h?OD:FD,g=fr(f),m=new Float32Array(6);let A=!1;const x=new wf;return _f(e,t,i,x.boundingData,m),y(x,t,i,m),x;function b(_){c&&c(_/g)}function y(_,E,I,B=null,C=0){if(!A&&C>=r&&(A=!0,o&&(console.warn(`MeshBVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`),console.warn(f))),I<=a||C>=r)return b(E+I),_.offset=E,_.count=I,_;const S=RD(_.boundingData,B,e,E,I,l);if(S.axis===-1)return b(E+I),_.offset=E,_.count=I,_;const P=p(u,d,e,E,I,S);if(P===E||P===E+I)b(E+I),_.offset=E,_.count=I;else{_.splitAxis=S.axis;const T=new wf,R=E,M=P-E;_.left=T,_f(e,R,M,T.boundingData,m),y(T,R,M,m,C+1);const F=new wf,N=P,j=I-M;_.right=F,_f(e,N,j,F.boundingData,m),y(F,N,j,m,C+1)}return _}}function VD(n,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=n.geometry;let s,r;if(e.indirect){const o=Ux(i,e.range),a=zD(i,e.useSharedArrayBuffer,o);n._indirectBuffer=a,s=Nx(i,0,a.length,a),r=[{offset:0,count:a.length}]}else{PD(i,e);const o=Ox(i,e.range)[0];s=Nx(i,o.offset,o.count),r=Ux(i,e.range)}n._roots=r.map(o=>{const a=GD(n,s,o.offset,o.count,e),l=Cf(a),c=new t(li*l);return ND(0,a,c),c})}class Jn{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,s=-1/0;for(let r=0,o=e.length;r<o;r++){const l=e[r][t];i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}setFromPoints(e,t){let i=1/0,s=-1/0;for(let r=0,o=t.length;r<o;r++){const a=t[r],l=e.dot(a);i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}Jn.prototype.setFromBox=(function(){const n=new v.Vector3;return function(t,i){const s=i.min,r=i.max;let o=1/0,a=-1/0;for(let l=0;l<=1;l++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){n.x=s.x*l+r.x*(1-l),n.y=s.y*c+r.y*(1-c),n.z=s.z*h+r.z*(1-h);const u=t.dot(n);o=Math.min(u,o),a=Math.max(u,a)}this.min=o,this.max=a}})();const QD=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Vector3;return function(s,r,o){const a=s.start,l=n,c=r.start,h=e;t.subVectors(a,c),n.subVectors(s.end,s.start),e.subVectors(r.end,r.start);const u=t.dot(h),f=h.dot(l),d=h.dot(h),p=t.dot(l),m=l.dot(l)*d-f*f;let A,x;m!==0?A=(u*f-p*d)/m:A=0,x=(u+A*f)/d,o.x=A,o.y=x}})(),Ef=(function(){const n=new v.Vector2,e=new v.Vector3,t=new v.Vector3;return function(s,r,o,a){QD(s,r,n);let l=n.x,c=n.y;if(l>=0&&l<=1&&c>=0&&c<=1){s.at(l,o),r.at(c,a);return}else if(l>=0&&l<=1){c<0?r.at(0,a):r.at(1,a),s.closestPointToPoint(a,!0,o);return}else if(c>=0&&c<=1){l<0?s.at(0,o):s.at(1,o),r.closestPointToPoint(o,!0,a);return}else{let h;l<0?h=s.start:h=s.end;let u;c<0?u=r.start:u=r.end;const f=e,d=t;if(s.closestPointToPoint(u,!0,e),r.closestPointToPoint(h,!0,t),f.distanceToSquared(u)<=d.distanceToSquared(h)){o.copy(f),a.copy(u);return}else{o.copy(h),a.copy(d);return}}}})(),jD=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Plane,i=new v.Line3;return function(r,o){const{radius:a,center:l}=r,{a:c,b:h,c:u}=o;if(i.start=c,i.end=h,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a||(i.start=c,i.end=u,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a)||(i.start=h,i.end=u,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a))return!0;const g=o.getPlane(t);if(Math.abs(g.distanceToPoint(l))<=a){const A=g.projectPoint(l,e);if(o.containsPoint(A))return!0}return!1}})(),WD=["x","y","z"],Zn=1e-15,Wx=Zn*Zn;function Gi(n){return Math.abs(n)<Zn}class Vi extends v.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new v.Vector3),this.satBounds=new Array(4).fill().map(()=>new Jn),this.points=[this.a,this.b,this.c],this.plane=new v.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new v.Line3,this.needsUpdate=!0}intersectsSphere(e){return jD(e,this)}update(){const e=this.a,t=this.b,i=this.c,s=this.points,r=this.satAxes,o=this.satBounds,a=r[0],l=o[0];this.getNormal(a),l.setFromPoints(a,s);const c=r[1],h=o[1];c.subVectors(e,t),h.setFromPoints(c,s);const u=r[2],f=o[2];u.subVectors(t,i),f.setFromPoints(u,s);const d=r[3],p=o[3];d.subVectors(i,e),p.setFromPoints(d,s);const g=c.length(),m=u.length(),A=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,g<Zn?m<Zn||A<Zn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):m<Zn?A<Zn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<Zn&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Vi.prototype.closestPointToSegment=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Line3;return function(s,r=null,o=null){const{start:a,end:l}=s,c=this.points;let h,u=1/0;for(let f=0;f<3;f++){const d=(f+1)%3;t.start.copy(c[f]),t.end.copy(c[d]),Ef(t,s,n,e),h=n.distanceToSquared(e),h<u&&(u=h,r&&r.copy(n),o&&o.copy(e))}return this.closestPointToPoint(a,n),h=a.distanceToSquared(n),h<u&&(u=h,r&&r.copy(n),o&&o.copy(a)),this.closestPointToPoint(l,n),h=l.distanceToSquared(n),h<u&&(u=h,r&&r.copy(n),o&&o.copy(l)),Math.sqrt(u)}})(),Vi.prototype.intersectsTriangle=(function(){const n=new Vi,e=new Jn,t=new Jn,i=new v.Vector3,s=new v.Vector3,r=new v.Vector3,o=new v.Vector3,a=new v.Line3,l=new v.Line3,c=new v.Vector3,h=new v.Vector2,u=new v.Vector2;function f(b,y,_,E){const I=i;!b.isDegenerateIntoPoint&&!b.isDegenerateIntoSegment?I.copy(b.plane.normal):I.copy(y.plane.normal);const B=b.satBounds,C=b.satAxes;for(let T=1;T<4;T++){const R=B[T],M=C[T];if(e.setFromPoints(M,y.points),R.isSeparated(e)||(o.copy(I).cross(M),e.setFromPoints(o,b.points),t.setFromPoints(o,y.points),e.isSeparated(t)))return!1}const S=y.satBounds,P=y.satAxes;for(let T=1;T<4;T++){const R=S[T],M=P[T];if(e.setFromPoints(M,b.points),R.isSeparated(e)||(o.crossVectors(I,M),e.setFromPoints(o,b.points),t.setFromPoints(o,y.points),e.isSeparated(t)))return!1}return _&&(E||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),_.start.set(0,0,0),_.end.set(0,0,0)),!0}function d(b,y,_,E,I,B,C,S,P,T,R){let M=C/(C-S);T.x=E+(I-E)*M,R.start.subVectors(y,b).multiplyScalar(M).add(b),M=C/(C-P),T.y=E+(B-E)*M,R.end.subVectors(_,b).multiplyScalar(M).add(b)}function p(b,y,_,E,I,B,C,S,P,T,R){if(I>0)d(b.c,b.a,b.b,E,y,_,P,C,S,T,R);else if(B>0)d(b.b,b.a,b.c,_,y,E,S,C,P,T,R);else if(S*P>0||C!=0)d(b.a,b.b,b.c,y,_,E,C,S,P,T,R);else if(S!=0)d(b.b,b.a,b.c,_,y,E,S,C,P,T,R);else if(P!=0)d(b.c,b.a,b.b,E,y,_,P,C,S,T,R);else return!0;return!1}function g(b,y,_,E){const I=y.degenerateSegment,B=b.plane.distanceToPoint(I.start),C=b.plane.distanceToPoint(I.end);return Gi(B)?Gi(C)?f(b,y,_,E):(_&&(_.start.copy(I.start),_.end.copy(I.start)),b.containsPoint(I.start)):Gi(C)?(_&&(_.start.copy(I.end),_.end.copy(I.end)),b.containsPoint(I.end)):b.plane.intersectLine(I,i)!=null?(_&&(_.start.copy(i),_.end.copy(i)),b.containsPoint(i)):!1}function m(b,y,_){const E=y.a;return Gi(b.plane.distanceToPoint(E))&&b.containsPoint(E)?(_&&(_.start.copy(E),_.end.copy(E)),!0):!1}function A(b,y,_){const E=b.degenerateSegment,I=y.a;return E.closestPointToPoint(I,!0,i),I.distanceToSquared(i)<Wx?(_&&(_.start.copy(I),_.end.copy(I)),!0):!1}function x(b,y,_,E){if(b.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const I=b.degenerateSegment,B=y.degenerateSegment,C=s,S=r;I.delta(C),B.delta(S);const P=i.subVectors(B.start,I.start),T=C.x*S.y-C.y*S.x;if(Gi(T))return!1;const R=(P.x*S.y-P.y*S.x)/T,M=-(C.x*P.y-C.y*P.x)/T;if(R<0||R>1||M<0||M>1)return!1;const F=I.start.z+C.z*R,N=B.start.z+S.z*M;return Gi(F-N)?(_&&(_.start.copy(I.start).addScaledVector(C,R),_.end.copy(I.start).addScaledVector(C,R)),!0):!1}else return y.isDegenerateIntoPoint?A(b,y,_):g(y,b,_,E);else{if(b.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(b.a)<Wx?(_&&(_.start.copy(b.a),_.end.copy(b.a)),!0):!1:y.isDegenerateIntoSegment?A(y,b,_):m(y,b,_);if(y.isDegenerateIntoPoint)return m(b,y,_);if(y.isDegenerateIntoSegment)return g(b,y,_,E)}}return function(y,_=null,E=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(n.copy(y),n.update(),y=n);const I=x(this,y,_,E);if(I!==void 0)return I;const B=this.plane,C=y.plane;let S=C.distanceToPoint(this.a),P=C.distanceToPoint(this.b),T=C.distanceToPoint(this.c);Gi(S)&&(S=0),Gi(P)&&(P=0),Gi(T)&&(T=0);const R=S*P,M=S*T;if(R>0&&M>0)return!1;let F=B.distanceToPoint(y.a),N=B.distanceToPoint(y.b),j=B.distanceToPoint(y.c);Gi(F)&&(F=0),Gi(N)&&(N=0),Gi(j)&&(j=0);const q=F*N,U=F*j;if(q>0&&U>0)return!1;s.copy(B.normal),r.copy(C.normal);const H=s.cross(r);let z=0,G=Math.abs(H.x);const re=Math.abs(H.y);re>G&&(G=re,z=1),Math.abs(H.z)>G&&(z=2);const ue=WD[z],se=this.a[ue],fe=this.b[ue],Ae=this.c[ue],_e=y.a[ue],Ce=y.b[ue],Oe=y.c[ue];if(p(this,se,fe,Ae,R,M,S,P,T,h,a))return f(this,y,_,E);if(p(y,_e,Ce,Oe,q,U,F,N,j,u,l))return f(this,y,_,E);if(h.y<h.x){const Ke=h.y;h.y=h.x,h.x=Ke,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(u.y<u.x){const Ke=u.y;u.y=u.x,u.x=Ke,c.copy(l.start),l.start.copy(l.end),l.end.copy(c)}return h.y<u.x||u.y<h.x?!1:(_&&(u.x>h.x?_.start.copy(l.start):_.start.copy(a.start),u.y<h.y?_.end.copy(l.end):_.end.copy(a.end)),!0)}})(),Vi.prototype.distanceToPoint=(function(){const n=new v.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})(),Vi.prototype.distanceToTriangle=(function(){const n=new v.Vector3,e=new v.Vector3,t=["a","b","c"],i=new v.Line3,s=new v.Line3;return function(o,a=null,l=null){const c=a||l?i:null;if(this.intersectsTriangle(o,c))return(a||l)&&(a&&c.getCenter(a),l&&c.getCenter(l)),0;let h=1/0;for(let u=0;u<3;u++){let f;const d=t[u],p=o[d];this.closestPointToPoint(p,n),f=p.distanceToSquared(n),f<h&&(h=f,a&&a.copy(n),l&&l.copy(p));const g=this[d];o.closestPointToPoint(g,n),f=g.distanceToSquared(n),f<h&&(h=f,a&&a.copy(g),l&&l.copy(n))}for(let u=0;u<3;u++){const f=t[u],d=t[(u+1)%3];i.set(this[f],this[d]);for(let p=0;p<3;p++){const g=t[p],m=t[(p+1)%3];s.set(o[g],o[m]),Ef(i,s,n,e);const A=n.distanceToSquared(e);A<h&&(h=A,a&&a.copy(n),l&&l.copy(e))}}return Math.sqrt(h)}})();class ci{constructor(e,t,i){this.isOrientedBox=!0,this.min=new v.Vector3,this.max=new v.Vector3,this.matrix=new v.Matrix4,this.invMatrix=new v.Matrix4,this.points=new Array(8).fill().map(()=>new v.Vector3),this.satAxes=new Array(3).fill().map(()=>new v.Vector3),this.satBounds=new Array(3).fill().map(()=>new Jn),this.alignedSatBounds=new Array(3).fill().map(()=>new Jn),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}ci.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,i=this.max,s=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const f=1*c|2*h|4*u,d=s[f];d.x=c?i.x:t.x,d.y=h?i.y:t.y,d.z=u?i.z:t.z,d.applyMatrix4(e)}const r=this.satBounds,o=this.satAxes,a=s[0];for(let c=0;c<3;c++){const h=o[c],u=r[c],f=1<<c,d=s[f];h.subVectors(a,d),u.setFromPoints(h,s)}const l=this.alignedSatBounds;l[0].setFromPointsField(s,"x"),l[1].setFromPointsField(s,"y"),l[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})(),ci.prototype.intersectsBox=(function(){const n=new Jn;return function(t){this.needsUpdate&&this.update();const i=t.min,s=t.max,r=this.satBounds,o=this.satAxes,a=this.alignedSatBounds;if(n.min=i.x,n.max=s.x,a[0].isSeparated(n)||(n.min=i.y,n.max=s.y,a[1].isSeparated(n))||(n.min=i.z,n.max=s.z,a[2].isSeparated(n)))return!1;for(let l=0;l<3;l++){const c=o[l],h=r[l];if(n.setFromBox(c,t),h.isSeparated(n))return!1}return!0}})(),ci.prototype.intersectsTriangle=(function(){const n=new Vi,e=new Array(3),t=new Jn,i=new Jn,s=new v.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(n.copy(o),n.update(),o=n);const a=this.satBounds,l=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let f=0;f<3;f++){const d=a[f],p=l[f];if(t.setFromPoints(p,e),d.isSeparated(t))return!1}const c=o.satBounds,h=o.satAxes,u=this.points;for(let f=0;f<3;f++){const d=c[f],p=h[f];if(t.setFromPoints(p,u),d.isSeparated(t))return!1}for(let f=0;f<3;f++){const d=l[f];for(let p=0;p<4;p++){const g=h[p];if(s.crossVectors(d,g),t.setFromPoints(s,e),i.setFromPoints(s,u),t.isSeparated(i))return!1}}return!0}})(),ci.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})(),ci.prototype.distanceToPoint=(function(){const n=new v.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})(),ci.prototype.distanceToBox=(function(){const n=["x","y","z"],e=new Array(12).fill().map(()=>new v.Line3),t=new Array(12).fill().map(()=>new v.Line3),i=new v.Vector3,s=new v.Vector3;return function(o,a=0,l=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(l||c)&&(o.getCenter(s),this.closestPointToPoint(s,i),o.closestPointToPoint(i,s),l&&l.copy(i),c&&c.copy(s)),0;const h=a*a,u=o.min,f=o.max,d=this.points;let p=1/0;for(let m=0;m<8;m++){const A=d[m];s.copy(A).clamp(u,f);const x=A.distanceToSquared(s);if(x<p&&(p=x,l&&l.copy(A),c&&c.copy(s),x<h))return Math.sqrt(x)}let g=0;for(let m=0;m<3;m++)for(let A=0;A<=1;A++)for(let x=0;x<=1;x++){const b=(m+1)%3,y=(m+2)%3,_=A<<b|x<<y,E=1<<m|A<<b|x<<y,I=d[_],B=d[E];e[g].set(I,B);const S=n[m],P=n[b],T=n[y],R=t[g],M=R.start,F=R.end;M[S]=u[S],M[P]=A?u[P]:f[P],M[T]=x?u[T]:f[P],F[S]=f[S],F[P]=A?u[P]:f[P],F[T]=x?u[T]:f[P],g++}for(let m=0;m<=1;m++)for(let A=0;A<=1;A++)for(let x=0;x<=1;x++){s.x=m?f.x:u.x,s.y=A?f.y:u.y,s.z=x?f.z:u.z,this.closestPointToPoint(s,i);const b=s.distanceToSquared(i);if(b<p&&(p=b,l&&l.copy(i),c&&c.copy(s),b<h))return Math.sqrt(b)}for(let m=0;m<12;m++){const A=e[m];for(let x=0;x<12;x++){const b=t[x];Ef(A,b,i,s);const y=i.distanceToSquared(s);if(y<p&&(p=y,l&&l.copy(i),c&&c.copy(s),y<h))return Math.sqrt(y)}}return Math.sqrt(p)}})();class If{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class HD extends If{constructor(){super(()=>new Vi)}}const Qi=new HD;function Ht(n,e){return e[n+15]===Fx}function Ii(n,e){return e[n+6]}function ji(n,e){return e[n+14]}function Xt(n){return n+Wt}function Yt(n,e){const t=e[n+6];return n+t*Wt}function Tf(n,e){return e[n+7]}function FF(n){return n}class qD{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const _t=new qD;let Es,bo;const yo=[],Uc=new If(()=>new v.Box3);function XD(n,e,t,i,s,r){Es=Uc.getPrimitive(),bo=Uc.getPrimitive(),yo.push(Es,bo),_t.setBuffer(n._roots[e]);const o=Df(0,n.geometry,t,i,s,r);_t.clearBuffer(),Uc.releasePrimitive(Es),Uc.releasePrimitive(bo),yo.pop(),yo.pop();const a=yo.length;return a>0&&(bo=yo[a-1],Es=yo[a-2]),o}function Df(n,e,t,i,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=_t;let h=n*2;if(Ht(h,l)){const f=Ii(n,c),d=ji(h,l);return It(n,a,Es),i(f,d,!1,o,r+n/Wt,Es)}else{let S=function(T){const{uint16Array:R,uint32Array:M}=_t;let F=T*2;for(;!Ht(F,R);)T=Xt(T),F=T*2;return Ii(T,M)},P=function(T){const{uint16Array:R,uint32Array:M}=_t;let F=T*2;for(;!Ht(F,R);)T=Yt(T,M),F=T*2;return Ii(T,M)+ji(F,R)};const f=Xt(n),d=Yt(n,c);let p=f,g=d,m,A,x,b;if(s&&(x=Es,b=bo,It(p,a,x),It(g,a,b),m=s(x),A=s(b),A<m)){p=d,g=f;const T=m;m=A,A=T,x=b}x||(x=Es,It(p,a,x));const y=Ht(p*2,l),_=t(x,y,m,o+1,r+p/Wt);let E;if(_===Rx){const T=S(p),M=P(p)-T;E=i(T,M,!0,o+1,r+p/Wt,x)}else E=_&&Df(p,e,t,i,s,r,o+1);if(E)return!0;b=bo,It(g,a,b);const I=Ht(g*2,l),B=t(b,I,A,o+1,r+g/Wt);let C;if(B===Rx){const T=S(g),M=P(g)-T;C=i(T,M,!0,o+1,r+g/Wt,b)}else C=B&&Df(g,e,t,i,s,r,o+1);return!!C}}const Ea=new v.Vector3,Bf=new v.Vector3;function YD(n,e,t={},i=0,s=1/0){const r=i*i,o=s*s;let a=1/0,l=null;if(n.shapecast({boundsTraverseOrder:h=>(Ea.copy(e).clamp(h.min,h.max),Ea.distanceToSquared(e)),intersectsBounds:(h,u,f)=>f<a&&f<o,intersectsTriangle:(h,u)=>{h.closestPointToPoint(e,Ea);const f=e.distanceToSquared(Ea);return f<a&&(Bf.copy(Ea),a=f,l=u),f<r}}),a===1/0)return null;const c=Math.sqrt(a);return t.point?t.point.copy(Bf):t.point=Bf.clone(),t.distance=c,t.faceIndex=l,t}const Nc=parseInt(v.REVISION)>=169,KD=parseInt(v.REVISION)<=161,pr=new v.Vector3,gr=new v.Vector3,mr=new v.Vector3,zc=new v.Vector2,Gc=new v.Vector2,Vc=new v.Vector2,Hx=new v.Vector3,qx=new v.Vector3,Xx=new v.Vector3,Ia=new v.Vector3;function $D(n,e,t,i,s,r,o,a){let l;if(r===v.BackSide?l=n.intersectTriangle(i,t,e,!0,s):l=n.intersectTriangle(e,t,i,r!==v.DoubleSide,s),l===null)return null;const c=n.origin.distanceTo(s);return c<o||c>a?null:{distance:c,point:s.clone()}}function Yx(n,e,t,i,s,r,o,a,l,c,h){pr.fromBufferAttribute(e,r),gr.fromBufferAttribute(e,o),mr.fromBufferAttribute(e,a);const u=$D(n,pr,gr,mr,Ia,l,c,h);if(u){if(i){zc.fromBufferAttribute(i,r),Gc.fromBufferAttribute(i,o),Vc.fromBufferAttribute(i,a),u.uv=new v.Vector2;const d=v.Triangle.getInterpolation(Ia,pr,gr,mr,zc,Gc,Vc,u.uv);Nc||(u.uv=d)}if(s){zc.fromBufferAttribute(s,r),Gc.fromBufferAttribute(s,o),Vc.fromBufferAttribute(s,a),u.uv1=new v.Vector2;const d=v.Triangle.getInterpolation(Ia,pr,gr,mr,zc,Gc,Vc,u.uv1);Nc||(u.uv1=d),KD&&(u.uv2=u.uv1)}if(t){Hx.fromBufferAttribute(t,r),qx.fromBufferAttribute(t,o),Xx.fromBufferAttribute(t,a),u.normal=new v.Vector3;const d=v.Triangle.getInterpolation(Ia,pr,gr,mr,Hx,qx,Xx,u.normal);u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1),Nc||(u.normal=d)}const f={a:r,b:o,c:a,normal:new v.Vector3,materialIndex:0};if(v.Triangle.getNormal(pr,gr,mr,f.normal),u.face=f,u.faceIndex=r,Nc){const d=new v.Vector3;v.Triangle.getBarycoord(Ia,pr,gr,mr,d),u.barycoord=d}}return u}function Kx(n){return n&&n.isMaterial?n.side:n}function Qc(n,e,t,i,s,r,o){const a=i*3;let l=a+0,c=a+1,h=a+2;const{index:u,groups:f}=n;n.index&&(l=u.getX(l),c=u.getX(c),h=u.getX(h));const{position:d,normal:p,uv:g,uv1:m}=n.attributes;if(Array.isArray(e)){const A=i*3;for(let x=0,b=f.length;x<b;x++){const{start:y,count:_,materialIndex:E}=f[x];if(A>=y&&A<y+_){const I=Kx(e[E]),B=Yx(t,d,p,g,m,l,c,h,I,r,o);if(B)if(B.faceIndex=i,B.face.materialIndex=E,s)s.push(B);else return B}}}else{const A=Kx(e),x=Yx(t,d,p,g,m,l,c,h,A,r,o);if(x)if(x.faceIndex=i,x.face.materialIndex=0,s)s.push(x);else return x}return null}function Ut(n,e,t,i){const s=n.a,r=n.b,o=n.c;let a=e,l=e+1,c=e+2;t&&(a=t.getX(a),l=t.getX(l),c=t.getX(c)),s.x=i.getX(a),s.y=i.getY(a),s.z=i.getZ(a),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l),o.x=i.getX(c),o.y=i.getY(c),o.z=i.getZ(c)}function JD(n,e,t,i,s,r,o,a){const{geometry:l,_indirectBuffer:c}=n;for(let h=i,u=i+s;h<u;h++)Qc(l,e,t,h,r,o,a)}function ZD(n,e,t,i,s,r,o){const{geometry:a,_indirectBuffer:l}=n;let c=1/0,h=null;for(let u=i,f=i+s;u<f;u++){let d;d=Qc(a,e,t,u,null,r,o),d&&d.distance<c&&(h=d,c=d.distance)}return h}function eB(n,e,t,i,s,r,o){const{geometry:a}=t,{index:l}=a,c=a.attributes.position;for(let h=n,u=e+n;h<u;h++){let f;if(f=h,Ut(o,f*3,l,c),o.needsUpdate=!0,i(o,f,s,r))return!0}return!1}function tB(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,l,c=0;const h=n._roots;for(let f=0,d=h.length;f<d;f++)r=h[f],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(f,d,p=!1){const g=f*2;if(Ht(g,a)){const m=o[f+6],A=a[g+14];let x=1/0,b=1/0,y=1/0,_=-1/0,E=-1/0,I=-1/0;for(let B=3*m,C=3*(m+A);B<C;B++){let S=i[B];const P=s.getX(S),T=s.getY(S),R=s.getZ(S);P<x&&(x=P),P>_&&(_=P),T<b&&(b=T),T>E&&(E=T),R<y&&(y=R),R>I&&(I=R)}return l[f+0]!==x||l[f+1]!==b||l[f+2]!==y||l[f+3]!==_||l[f+4]!==E||l[f+5]!==I?(l[f+0]=x,l[f+1]=b,l[f+2]=y,l[f+3]=_,l[f+4]=E,l[f+5]=I,!0):!1}else{const m=Xt(f),A=Yt(f,o);let x=p,b=!1,y=!1;if(e){if(!x){const S=m/Wt+d/li,P=A/Wt+d/li;b=e.has(S),y=e.has(P),x=!b&&!y}}else b=!0,y=!0;const _=x||b,E=x||y;let I=!1;_&&(I=u(m,d,x));let B=!1;E&&(B=u(A,d,x));const C=I||B;if(C)for(let S=0;S<3;S++){const P=m+S,T=A+S,R=l[P],M=l[P+3],F=l[T],N=l[T+3];l[f+S]=R<F?R:F,l[f+S+3]=M>N?M:N}return C}}}function Is(n,e,t,i,s){let r,o,a,l,c,h;const u=1/t.direction.x,f=1/t.direction.y,d=1/t.direction.z,p=t.origin.x,g=t.origin.y,m=t.origin.z;let A=e[n],x=e[n+3],b=e[n+1],y=e[n+3+1],_=e[n+2],E=e[n+3+2];return u>=0?(r=(A-p)*u,o=(x-p)*u):(r=(x-p)*u,o=(A-p)*u),f>=0?(a=(b-g)*f,l=(y-g)*f):(a=(y-g)*f,l=(b-g)*f),r>l||a>o||((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),d>=0?(c=(_-m)*d,h=(E-m)*d):(c=(E-m)*d,h=(_-m)*d),r>h||c>o)?!1:((c>r||r!==r)&&(r=c),(h<o||o!==o)&&(o=h),r<=s&&o>=i)}function iB(n,e,t,i,s,r,o,a){const{geometry:l,_indirectBuffer:c}=n;for(let h=i,u=i+s;h<u;h++){let f=c?c[h]:h;Qc(l,e,t,f,r,o,a)}}function nB(n,e,t,i,s,r,o){const{geometry:a,_indirectBuffer:l}=n;let c=1/0,h=null;for(let u=i,f=i+s;u<f;u++){let d;d=Qc(a,e,t,l?l[u]:u,null,r,o),d&&d.distance<c&&(h=d,c=d.distance)}return h}function sB(n,e,t,i,s,r,o){const{geometry:a}=t,{index:l}=a,c=a.attributes.position;for(let h=n,u=e+n;h<u;h++){let f;if(f=t.resolveTriangleIndex(h),Ut(o,f*3,l,c),o.needsUpdate=!0,i(o,f,s,r))return!0}return!1}function rB(n,e,t,i,s,r,o){_t.setBuffer(n._roots[e]),Pf(0,n,t,i,s,r,o),_t.clearBuffer()}function Pf(n,e,t,i,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=_t,h=n*2;if(Ht(h,l)){const f=Ii(n,c),d=ji(h,l);JD(e,t,i,f,d,s,r,o)}else{const f=Xt(n);Is(f,a,i,r,o)&&Pf(f,e,t,i,s,r,o);const d=Yt(n,c);Is(d,a,i,r,o)&&Pf(d,e,t,i,s,r,o)}}const oB=["x","y","z"];function aB(n,e,t,i,s,r){_t.setBuffer(n._roots[e]);const o=Lf(0,n,t,i,s,r);return _t.clearBuffer(),o}function Lf(n,e,t,i,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=_t;let c=n*2;if(Ht(c,a)){const u=Ii(n,l),f=ji(c,a);return ZD(e,t,i,u,f,s,r)}else{const u=Tf(n,l),f=oB[u],p=i.direction[f]>=0;let g,m;p?(g=Xt(n),m=Yt(n,l)):(g=Yt(n,l),m=Xt(n));const x=Is(g,o,i,s,r)?Lf(g,e,t,i,s,r):null;if(x){const _=x.point[f];if(p?_<=o[m+u]:_>=o[m+u+3])return x}const y=Is(m,o,i,s,r)?Lf(m,e,t,i,s,r):null;return x&&y?x.distance<=y.distance?x:y:x||y||null}}const jc=new v.Box3,vo=new Vi,_o=new Vi,Ta=new v.Matrix4,$x=new ci,Wc=new ci;function lB(n,e,t,i){_t.setBuffer(n._roots[e]);const s=Rf(0,n,t,i);return _t.clearBuffer(),s}function Rf(n,e,t,i,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_t;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),$x.set(t.boundingBox.min,t.boundingBox.max,i),s=$x),Ht(l,o)){const h=e.geometry,u=h.index,f=h.attributes.position,d=t.index,p=t.attributes.position,g=Ii(n,a),m=ji(l,o);if(Ta.copy(i).invert(),t.boundsTree)return It(n,r,Wc),Wc.matrix.copy(Ta),Wc.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>Wc.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(i),x.b.applyMatrix4(i),x.c.applyMatrix4(i),x.needsUpdate=!0;for(let b=g*3,y=(m+g)*3;b<y;b+=3)if(Ut(_o,b,u,f),_o.needsUpdate=!0,x.intersectsTriangle(_o))return!0;return!1}});{const A=fr(t);for(let x=g*3,b=(m+g)*3;x<b;x+=3){Ut(vo,x,u,f),vo.a.applyMatrix4(Ta),vo.b.applyMatrix4(Ta),vo.c.applyMatrix4(Ta),vo.needsUpdate=!0;for(let y=0,_=A*3;y<_;y+=3)if(Ut(_o,y,d,p),_o.needsUpdate=!0,vo.intersectsTriangle(_o))return!0}}}else{const h=Xt(n),u=Yt(n,a);return It(h,r,jc),!!(s.intersectsBox(jc)&&Rf(h,e,t,i,s)||(It(u,r,jc),s.intersectsBox(jc)&&Rf(u,e,t,i,s)))}}const Hc=new v.Matrix4,kf=new ci,Da=new ci,cB=new v.Vector3,hB=new v.Vector3,uB=new v.Vector3,dB=new v.Vector3;function fB(n,e,t,i={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),kf.set(e.boundingBox.min,e.boundingBox.max,t),kf.needsUpdate=!0;const a=n.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,f=Qi.getPrimitive(),d=Qi.getPrimitive();let p=cB,g=hB,m=null,A=null;s&&(m=uB,A=dB);let x=1/0,b=null,y=null;return Hc.copy(t).invert(),Da.matrix.copy(Hc),n.shapecast({boundsTraverseOrder:_=>kf.distanceToBox(_),intersectsBounds:(_,E,I)=>I<x&&I<o?(E&&(Da.min.copy(_.min),Da.max.copy(_.max),Da.needsUpdate=!0),!0):!1,intersectsRange:(_,E)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:B=>Da.distanceToBox(B),intersectsBounds:(B,C,S)=>S<x&&S<o,intersectsRange:(B,C)=>{for(let S=B,P=B+C;S<P;S++){Ut(d,3*S,u,h),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let T=_,R=_+E;T<R;T++){Ut(f,3*T,c,l),f.needsUpdate=!0;const M=f.distanceToTriangle(d,p,m);if(M<x&&(g.copy(p),A&&A.copy(m),x=M,b=T,y=S),M<r)return!0}}}});{const I=fr(e);for(let B=0,C=I;B<C;B++){Ut(d,3*B,u,h),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let S=_,P=_+E;S<P;S++){Ut(f,3*S,c,l),f.needsUpdate=!0;const T=f.distanceToTriangle(d,p,m);if(T<x&&(g.copy(p),A&&A.copy(m),x=T,b=S,y=B),T<r)return!0}}}}}),Qi.releasePrimitive(f),Qi.releasePrimitive(d),x===1/0?null:(i.point?i.point.copy(g):i.point=g.clone(),i.distance=x,i.faceIndex=b,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Hc),g.applyMatrix4(Hc),s.distance=g.sub(s.point).length(),s.faceIndex=y),i)}function pB(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,l,c=0;const h=n._roots;for(let f=0,d=h.length;f<d;f++)r=h[f],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(f,d,p=!1){const g=f*2;if(Ht(g,a)){const m=o[f+6],A=a[g+14];let x=1/0,b=1/0,y=1/0,_=-1/0,E=-1/0,I=-1/0;for(let B=m,C=m+A;B<C;B++){const S=3*n.resolveTriangleIndex(B);for(let P=0;P<3;P++){let T=S+P;T=i?i[T]:T;const R=s.getX(T),M=s.getY(T),F=s.getZ(T);R<x&&(x=R),R>_&&(_=R),M<b&&(b=M),M>E&&(E=M),F<y&&(y=F),F>I&&(I=F)}}return l[f+0]!==x||l[f+1]!==b||l[f+2]!==y||l[f+3]!==_||l[f+4]!==E||l[f+5]!==I?(l[f+0]=x,l[f+1]=b,l[f+2]=y,l[f+3]=_,l[f+4]=E,l[f+5]=I,!0):!1}else{const m=Xt(f),A=Yt(f,o);let x=p,b=!1,y=!1;if(e){if(!x){const S=m/Wt+d/li,P=A/Wt+d/li;b=e.has(S),y=e.has(P),x=!b&&!y}}else b=!0,y=!0;const _=x||b,E=x||y;let I=!1;_&&(I=u(m,d,x));let B=!1;E&&(B=u(A,d,x));const C=I||B;if(C)for(let S=0;S<3;S++){const P=m+S,T=A+S,R=l[P],M=l[P+3],F=l[T],N=l[T+3];l[f+S]=R<F?R:F,l[f+S+3]=M>N?M:N}return C}}}function gB(n,e,t,i,s,r,o){_t.setBuffer(n._roots[e]),Ff(0,n,t,i,s,r,o),_t.clearBuffer()}function Ff(n,e,t,i,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=_t,h=n*2;if(Ht(h,l)){const f=Ii(n,c),d=ji(h,l);iB(e,t,i,f,d,s,r,o)}else{const f=Xt(n);Is(f,a,i,r,o)&&Ff(f,e,t,i,s,r,o);const d=Yt(n,c);Is(d,a,i,r,o)&&Ff(d,e,t,i,s,r,o)}}const mB=["x","y","z"];function AB(n,e,t,i,s,r){_t.setBuffer(n._roots[e]);const o=Of(0,n,t,i,s,r);return _t.clearBuffer(),o}function Of(n,e,t,i,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=_t;let c=n*2;if(Ht(c,a)){const u=Ii(n,l),f=ji(c,a);return nB(e,t,i,u,f,s,r)}else{const u=Tf(n,l),f=mB[u],p=i.direction[f]>=0;let g,m;p?(g=Xt(n),m=Yt(n,l)):(g=Yt(n,l),m=Xt(n));const x=Is(g,o,i,s,r)?Of(g,e,t,i,s,r):null;if(x){const _=x.point[f];if(p?_<=o[m+u]:_>=o[m+u+3])return x}const y=Is(m,o,i,s,r)?Of(m,e,t,i,s,r):null;return x&&y?x.distance<=y.distance?x:y:x||y||null}}const qc=new v.Box3,wo=new Vi,So=new Vi,Ba=new v.Matrix4,Jx=new ci,Xc=new ci;function xB(n,e,t,i){_t.setBuffer(n._roots[e]);const s=Uf(0,n,t,i);return _t.clearBuffer(),s}function Uf(n,e,t,i,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_t;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Jx.set(t.boundingBox.min,t.boundingBox.max,i),s=Jx),Ht(l,o)){const h=e.geometry,u=h.index,f=h.attributes.position,d=t.index,p=t.attributes.position,g=Ii(n,a),m=ji(l,o);if(Ba.copy(i).invert(),t.boundsTree)return It(n,r,Xc),Xc.matrix.copy(Ba),Xc.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>Xc.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(i),x.b.applyMatrix4(i),x.c.applyMatrix4(i),x.needsUpdate=!0;for(let b=g,y=m+g;b<y;b++)if(Ut(So,3*e.resolveTriangleIndex(b),u,f),So.needsUpdate=!0,x.intersectsTriangle(So))return!0;return!1}});{const A=fr(t);for(let x=g,b=m+g;x<b;x++){const y=e.resolveTriangleIndex(x);Ut(wo,3*y,u,f),wo.a.applyMatrix4(Ba),wo.b.applyMatrix4(Ba),wo.c.applyMatrix4(Ba),wo.needsUpdate=!0;for(let _=0,E=A*3;_<E;_+=3)if(Ut(So,_,d,p),So.needsUpdate=!0,wo.intersectsTriangle(So))return!0}}}else{const h=Xt(n),u=Yt(n,a);return It(h,r,qc),!!(s.intersectsBox(qc)&&Uf(h,e,t,i,s)||(It(u,r,qc),s.intersectsBox(qc)&&Uf(u,e,t,i,s)))}}const Yc=new v.Matrix4,Nf=new ci,Pa=new ci,bB=new v.Vector3,yB=new v.Vector3,vB=new v.Vector3,_B=new v.Vector3;function wB(n,e,t,i={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Nf.set(e.boundingBox.min,e.boundingBox.max,t),Nf.needsUpdate=!0;const a=n.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,f=Qi.getPrimitive(),d=Qi.getPrimitive();let p=bB,g=yB,m=null,A=null;s&&(m=vB,A=_B);let x=1/0,b=null,y=null;return Yc.copy(t).invert(),Pa.matrix.copy(Yc),n.shapecast({boundsTraverseOrder:_=>Nf.distanceToBox(_),intersectsBounds:(_,E,I)=>I<x&&I<o?(E&&(Pa.min.copy(_.min),Pa.max.copy(_.max),Pa.needsUpdate=!0),!0):!1,intersectsRange:(_,E)=>{if(e.boundsTree){const I=e.boundsTree;return I.shapecast({boundsTraverseOrder:B=>Pa.distanceToBox(B),intersectsBounds:(B,C,S)=>S<x&&S<o,intersectsRange:(B,C)=>{for(let S=B,P=B+C;S<P;S++){const T=I.resolveTriangleIndex(S);Ut(d,3*T,u,h),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let R=_,M=_+E;R<M;R++){const F=n.resolveTriangleIndex(R);Ut(f,3*F,c,l),f.needsUpdate=!0;const N=f.distanceToTriangle(d,p,m);if(N<x&&(g.copy(p),A&&A.copy(m),x=N,b=R,y=S),N<r)return!0}}}})}else{const I=fr(e);for(let B=0,C=I;B<C;B++){Ut(d,3*B,u,h),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let S=_,P=_+E;S<P;S++){const T=n.resolveTriangleIndex(S);Ut(f,3*T,c,l),f.needsUpdate=!0;const R=f.distanceToTriangle(d,p,m);if(R<x&&(g.copy(p),A&&A.copy(m),x=R,b=S,y=B),R<r)return!0}}}}}),Qi.releasePrimitive(f),Qi.releasePrimitive(d),x===1/0?null:(i.point?i.point.copy(g):i.point=g.clone(),i.distance=x,i.faceIndex=b,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Yc),g.applyMatrix4(Yc),s.distance=g.sub(s.point).length(),s.faceIndex=y),i)}function SB(){return typeof SharedArrayBuffer<"u"}const La=new _t.constructor,Kc=new _t.constructor,Ts=new If(()=>new v.Box3),Co=new v.Box3,Mo=new v.Box3,zf=new v.Box3,Gf=new v.Box3;let Vf=!1;function CB(n,e,t,i){if(Vf)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Vf=!0;const s=n._roots,r=e._roots;let o,a=0,l=0;const c=new v.Matrix4().copy(t).invert();for(let h=0,u=s.length;h<u;h++){La.setBuffer(s[h]),l=0;const f=Ts.getPrimitive();It(0,La.float32Array,f),f.applyMatrix4(c);for(let d=0,p=r.length;d<p&&(Kc.setBuffer(r[d]),o=rn(0,0,t,c,i,a,l,0,0,f),Kc.clearBuffer(),l+=r[d].byteLength/li,!o);d++);if(Ts.releasePrimitive(f),La.clearBuffer(),a+=s[h].byteLength/li,o)break}return Vf=!1,o}function rn(n,e,t,i,s,r=0,o=0,a=0,l=0,c=null,h=!1){let u,f;h?(u=Kc,f=La):(u=La,f=Kc);const d=u.float32Array,p=u.uint32Array,g=u.uint16Array,m=f.float32Array,A=f.uint32Array,x=f.uint16Array,b=n*2,y=e*2,_=Ht(b,g),E=Ht(y,x);let I=!1;if(E&&_)h?I=s(Ii(e,A),ji(e*2,x),Ii(n,p),ji(n*2,g),l,o+e/Wt,a,r+n/Wt):I=s(Ii(n,p),ji(n*2,g),Ii(e,A),ji(e*2,x),a,r+n/Wt,l,o+e/Wt);else if(E){const B=Ts.getPrimitive();It(e,m,B),B.applyMatrix4(t);const C=Xt(n),S=Yt(n,p);It(C,d,Co),It(S,d,Mo);const P=B.intersectsBox(Co),T=B.intersectsBox(Mo);I=P&&rn(e,C,i,t,s,o,r,l,a+1,B,!h)||T&&rn(e,S,i,t,s,o,r,l,a+1,B,!h),Ts.releasePrimitive(B)}else{const B=Xt(e),C=Yt(e,A);It(B,m,zf),It(C,m,Gf);const S=c.intersectsBox(zf),P=c.intersectsBox(Gf);if(S&&P)I=rn(n,B,t,i,s,r,o,a,l+1,c,h)||rn(n,C,t,i,s,r,o,a,l+1,c,h);else if(S)if(_)I=rn(n,B,t,i,s,r,o,a,l+1,c,h);else{const T=Ts.getPrimitive();T.copy(zf).applyMatrix4(t);const R=Xt(n),M=Yt(n,p);It(R,d,Co),It(M,d,Mo);const F=T.intersectsBox(Co),N=T.intersectsBox(Mo);I=F&&rn(B,R,i,t,s,o,r,l,a+1,T,!h)||N&&rn(B,M,i,t,s,o,r,l,a+1,T,!h),Ts.releasePrimitive(T)}else if(P)if(_)I=rn(n,C,t,i,s,r,o,a,l+1,c,h);else{const T=Ts.getPrimitive();T.copy(Gf).applyMatrix4(t);const R=Xt(n),M=Yt(n,p);It(R,d,Co),It(M,d,Mo);const F=T.intersectsBox(Co),N=T.intersectsBox(Mo);I=F&&rn(C,R,i,t,s,o,r,l,a+1,T,!h)||N&&rn(C,M,i,t,s,o,r,l,a+1,T,!h),Ts.releasePrimitive(T)}}return I}const $c=new ci,Zx=new v.Box3,MB={strategy:Lx,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class Qf{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,s=e._roots,r=e._indirectBuffer,o=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(l=>l.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=s,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:s,roots:r,indirectBuffer:o}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),l(r));const a=new Qf(t,{...i,[vf]:!0});if(a._roots=r,a._indirectBuffer=o||null,i.setIndex){const c=t.getIndex();if(c===null){const h=new v.BufferAttribute(e.index,1,!1);t.setIndex(h)}else c.array!==s&&(c.array.set(s),c.needsUpdate=!0)}return a;function l(c){for(let h=0;h<c.length;h++){const u=c[h],f=new Uint32Array(u),d=new Uint16Array(u);for(let p=0,g=u.byteLength/li;p<g;p++){const m=Wt*p,A=2*m;Ht(A,d)||(f[m+6]=f[m+6]/Wt-p)}}}}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...MB,[vf]:!1},t),t.useSharedArrayBuffer&&!SB())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[vf]||(VD(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new v.Box3))),this.resolveTriangleIndex=t.indirect?i=>this._indirectBuffer[i]:i=>i}shiftTriangleOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,s=t.length;i<s;i++)t[i]+=e;else{const i=this._roots;for(let s=0;s<i.length;s++){const r=i[s],o=new Uint32Array(r),a=new Uint16Array(r),l=r.byteLength/li;for(let c=0;c<l;c++){const h=Wt*c,u=2*h;Ht(u,a)&&(o[h+6]+=e)}}}}refit(e=null){return(this.indirect?pB:tB)(this,e)}traverse(e,t=0){const i=this._roots[t],s=new Uint32Array(i),r=new Uint16Array(i);o(0);function o(a,l=0){const c=a*2,h=Ht(c,r);if(h){const u=s[a+6],f=r[c+14];e(l,h,new Float32Array(i,a*4,6),u,f)}else{const u=Xt(a),f=Yt(a,s),d=Tf(a,s);e(l,h,new Float32Array(i,a*4,6),d)||(o(u,l+1),o(f,l+1))}}}raycast(e,t=v.FrontSide,i=0,s=1/0){const r=this._roots,o=[],a=this.indirect?gB:rB;for(let l=0,c=r.length;l<c;l++)a(this,l,t,e,o,i,s);return o}raycastFirst(e,t=v.FrontSide,i=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?AB:aB;for(let l=0,c=r.length;l<c;l++){const h=a(this,l,t,e,i,s);h!=null&&(o==null||h.distance<o.distance)&&(o=h)}return o}intersectsGeometry(e,t){let i=!1;const s=this._roots,r=this.indirect?xB:lB;for(let o=0,a=s.length;o<a&&(i=r(this,o,e,t),!i);o++);return i}shapecast(e){const t=Qi.getPrimitive(),i=this.indirect?sB:eB;let{boundsTraverseOrder:s,intersectsBounds:r,intersectsRange:o,intersectsTriangle:a}=e;if(o&&a){const u=o;o=(f,d,p,g,m)=>u(f,d,p,g,m)?!0:i(f,d,this,a,p,g,t)}else o||(a?o=(u,f,d,p)=>i(u,f,this,a,d,p,t):o=(u,f,d)=>d);let l=!1,c=0;const h=this._roots;for(let u=0,f=h.length;u<f;u++){const d=h[u];if(l=XD(this,u,r,o,s,c),l)break;c+=d.byteLength/li}return Qi.releasePrimitive(t),l}bvhcast(e,t,i){let{intersectsRanges:s,intersectsTriangles:r}=i;const o=Qi.getPrimitive(),a=this.geometry.index,l=this.geometry.attributes.position,c=this.indirect?p=>{const g=this.resolveTriangleIndex(p);Ut(o,g*3,a,l)}:p=>{Ut(o,p*3,a,l)},h=Qi.getPrimitive(),u=e.geometry.index,f=e.geometry.attributes.position,d=e.indirect?p=>{const g=e.resolveTriangleIndex(p);Ut(h,g*3,u,f)}:p=>{Ut(h,p*3,u,f)};if(r){const p=(g,m,A,x,b,y,_,E)=>{for(let I=A,B=A+x;I<B;I++){d(I),h.a.applyMatrix4(t),h.b.applyMatrix4(t),h.c.applyMatrix4(t),h.needsUpdate=!0;for(let C=g,S=g+m;C<S;C++)if(c(C),o.needsUpdate=!0,r(o,h,C,I,b,y,_,E))return!0}return!1};if(s){const g=s;s=function(m,A,x,b,y,_,E,I){return g(m,A,x,b,y,_,E,I)?!0:p(m,A,x,b,y,_,E,I)}}else s=p}return CB(this,e,t,s)}intersectsBox(e,t){return $c.set(e.min,e.max,t),$c.needsUpdate=!0,this.shapecast({intersectsBounds:i=>$c.intersectsBox(i),intersectsTriangle:i=>$c.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},s={},r=0,o=1/0){return(this.indirect?wB:fB)(this,e,t,i,s,r,o)}closestPointToPoint(e,t={},i=0,s=1/0){return YD(this,e,t,i,s)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(i=>{It(0,new Float32Array(i),Zx),e.union(Zx)}),e}}const eb=1e-6,EB=eb*.5,tb=Math.pow(10,-Math.log10(eb)),IB=EB*tb;function Sn(n){return~~(n*tb+IB)}function TB(n){return`${Sn(n.x)},${Sn(n.y)}`}function ib(n){return`${Sn(n.x)},${Sn(n.y)},${Sn(n.z)}`}function DB(n){return`${Sn(n.x)},${Sn(n.y)},${Sn(n.z)},${Sn(n.w)}`}function BB(n,e,t){t.direction.subVectors(e,n).normalize();const i=n.dot(t.direction);return t.origin.copy(n).addScaledVector(t.direction,-i),t}function nb(){return typeof SharedArrayBuffer<"u"}function PB(n){if(n.buffer instanceof SharedArrayBuffer)return n;const e=n.constructor,t=n.buffer,i=new SharedArrayBuffer(t.byteLength),s=new Uint8Array(t);return new Uint8Array(i).set(s,0),new e(i)}function LB(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function RB(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=LB(t,i);n.setIndex(new v.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function kB(n){return n.index?n.index.count:n.attributes.position.count}function jf(n){return kB(n)/3}const FB=1e-8,OB=new v.Vector3;function UB(n){return~~(n/3)}function NB(n){return n%3}function sb(n,e){return n.start-e.start}function rb(n,e){return OB.subVectors(e,n.origin).dot(n.direction)}function zB(n,e,t,i=FB){n.sort(sb),e.sort(sb);for(let a=0;a<n.length;a++){const l=n[a];for(let c=0;c<e.length;c++){const h=e[c];if(!(h.start>l.end)){if(l.end<h.start||h.end<l.start)continue;if(l.start<=h.start&&l.end>=h.end)r(h.end,l.end)||n.splice(a+1,0,{start:h.end,end:l.end,index:l.index}),l.end=h.start,h.start=0,h.end=0;else if(l.start>=h.start&&l.end<=h.end)r(l.end,h.end)||e.splice(c+1,0,{start:l.end,end:h.end,index:h.index}),h.end=l.start,l.start=0,l.end=0;else if(l.start<=h.start&&l.end<=h.end){const u=l.end;l.end=h.start,h.start=u}else if(l.start>=h.start&&l.end>=h.end){const u=h.end;h.end=l.start,l.start=u}else throw new Error}if(t.has(l.index)||t.set(l.index,[]),t.has(h.index)||t.set(h.index,[]),t.get(l.index).push(h.index),t.get(h.index).push(l.index),o(h)&&(e.splice(c,1),c--),o(l)){n.splice(a,1),a--;break}}}s(n),s(e);function s(a){for(let l=0;l<a.length;l++)o(a[l])&&(a.splice(l,1),l--)}function r(a,l){return Math.abs(l-a)<i}function o(a){return Math.abs(a.end-a.start)<i}}const ob=1e-5,ab=1e-4;class GB{constructor(){this._rays=[]}addRay(e){this._rays.push(e)}findClosestRay(e){const t=this._rays,i=e.clone();i.direction.multiplyScalar(-1);let s=1/0,r=null;for(let l=0,c=t.length;l<c;l++){const h=t[l];if(o(h,e)&&o(h,i))continue;const u=a(h,e),f=a(h,i),d=Math.min(u,f);d<s&&(s=d,r=h)}return r;function o(l,c){const h=l.origin.distanceTo(c.origin)>ob;return l.direction.angleTo(c.direction)>ab||h}function a(l,c){const h=l.origin.distanceTo(c.origin),u=l.direction.angleTo(c.direction);return h/ob+u/ab}}}const Wf=new v.Vector3,Hf=new v.Vector3,Jc=new v.Ray;function VB(n,e,t){const i=n.attributes,s=n.index,r=i.position,o=new Map,a=new Map,l=Array.from(e),c=new GB;for(let h=0,u=l.length;h<u;h++){const f=l[h],d=UB(f),p=NB(f);let g=3*d+p,m=3*d+(p+1)%3;s&&(g=s.getX(g),m=s.getX(m)),Wf.fromBufferAttribute(r,g),Hf.fromBufferAttribute(r,m),BB(Wf,Hf,Jc);let A,x=c.findClosestRay(Jc);x===null&&(x=Jc.clone(),c.addRay(x)),a.has(x)||a.set(x,{forward:[],reverse:[],ray:x}),A=a.get(x);let b=rb(x,Wf),y=rb(x,Hf);b>y&&([b,y]=[y,b]),Jc.direction.dot(x.direction)<0?A.reverse.push({start:b,end:y,index:f}):A.forward.push({start:b,end:y,index:f})}return a.forEach(({forward:h,reverse:u},f)=>{zB(h,u,o,t),h.length===0&&u.length===0&&a.delete(f)}),{disjointConnectivityMap:o,fragmentMap:a}}const QB=new v.Vector2,qf=new v.Vector3,jB=new v.Vector4,Xf=["","",""];class WB{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:~~(i/3)}getSiblingEdgeIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:i%3}getDisjointSiblingTriangleIndices(e,t){const i=e*3+t,s=this.disjointConnections.get(i);return s?s.map(r=>~~(r/3)):[]}getDisjointSiblingEdgeIndices(e,t){const i=e*3+t,s=this.disjointConnections.get(i);return s?s.map(r=>r%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:t,useDrawRange:i,matchDisjointEdges:s,degenerateEpsilon:r}=this,o=t?b:x,a=new Map,{attributes:l}=e,c=t?Object.keys(l):null,h=e.index,u=l.position;let f=jf(e);const d=f;let p=0;i&&(p=e.drawRange.start,e.drawRange.count!==1/0&&(f=~~(e.drawRange.count/3)));let g=this.data;(!g||g.length<3*d)&&(g=new Int32Array(3*d)),g.fill(-1);let m=0,A=new Set;for(let y=p,_=f*3+p;y<_;y+=3){const E=y;for(let I=0;I<3;I++){let B=E+I;h&&(B=h.getX(B)),Xf[I]=o(B)}for(let I=0;I<3;I++){const B=(I+1)%3,C=Xf[I],S=Xf[B],P=`${S}_${C}`;if(a.has(P)){const T=E+I,R=a.get(P);g[T]=R,g[R]=T,a.delete(P),m+=2,A.delete(R)}else{const T=`${C}_${S}`,R=E+I;a.set(T,R),A.add(R)}}}if(s){const{fragmentMap:y,disjointConnectivityMap:_}=VB(e,A,r);A.clear(),y.forEach(({forward:E,reverse:I})=>{E.forEach(({index:B})=>A.add(B)),I.forEach(({index:B})=>A.add(B))}),this.unmatchedDisjointEdges=y,this.disjointConnections=_,m=f*3-A.size}this.matchedEdges=m,this.unmatchedEdges=A.size,this.data=g;function x(y){return qf.fromBufferAttribute(u,y),ib(qf)}function b(y){let _="";for(let E=0,I=c.length;E<I;E++){const B=l[c[E]];let C;switch(B.itemSize){case 1:C=Sn(B.getX(y));break;case 2:C=TB(QB.fromBufferAttribute(B,y));break;case 3:C=ib(qf.fromBufferAttribute(B,y));break;case 4:C=DB(jB.fromBufferAttribute(B,y));break}_!==""&&(_+="|"),_+=C}return _}}}class Zc extends v.Mesh{constructor(...e){super(...e),this.isBrush=!0,this._previousMatrix=new v.Matrix4,this._previousMatrix.elements.fill(0)}markUpdated(){this._previousMatrix.copy(this.matrix)}isDirty(){const{matrix:e,_previousMatrix:t}=this,i=e.elements,s=t.elements;for(let r=0;r<16;r++)if(i[r]!==s[r])return!0;return!1}prepareGeometry(){const e=this.geometry,t=e.attributes,i=nb();if(i)for(const s in t){const r=t[s];if(r.isInterleavedBufferAttribute)throw new Error("Brush: InterleavedBufferAttributes are not supported.");r.array=PB(r.array)}if(e.boundsTree||(RB(e,{useSharedArrayBuffer:i}),e.boundsTree=new Qf(e,{maxLeafTris:3,indirect:!0,useSharedArrayBuffer:i})),e.halfEdges||(e.halfEdges=new WB(e)),!e.groupIndices){const s=jf(e),r=new Uint16Array(s),o=e.groups;for(let a=0,l=o.length;a<l;a++){const{start:c,count:h}=o[a];for(let u=c/3,f=(c+h)/3;u<f;u++)r[u]=a}e.groupIndices=r}}disposeCacheData(){const{geometry:e}=this;e.halfEdges=null,e.boundsTree=null,e.groupIndices=null}}const HB=1e-14,Yf=new v.Vector3,lb=new v.Vector3,cb=new v.Vector3;function Ds(n,e=HB){Yf.subVectors(n.b,n.a),lb.subVectors(n.c,n.a),cb.subVectors(n.b,n.c);const t=Yf.angleTo(lb),i=Yf.angleTo(cb),s=Math.PI-t-i;return Math.abs(t)<e||Math.abs(i)<e||Math.abs(s)<e||n.a.distanceToSquared(n.b)<e||n.a.distanceToSquared(n.c)<e||n.b.distanceToSquared(n.c)<e}const Kf=1e-10,Ra=1e-10,qB=1e-10,es=new v.Line3,Ft=new v.Line3,ts=new v.Vector3,$f=new v.Vector3,hb=new v.Vector3,eh=new v.Plane,Jf=new Vi;class XB{constructor(){this._pool=[],this._index=0}getTriangle(){return this._index>=this._pool.length&&this._pool.push(new v.Triangle),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class YB{constructor(){this.trianglePool=new XB,this.triangles=[],this.normal=new v.Vector3,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:t,trianglePool:i,normal:s}=this;if(Array.isArray(e))for(let r=0,o=e.length;r<o;r++){const a=e[r];if(r===0)a.getNormal(s);else if(Math.abs(1-a.getNormal(ts).dot(s))>Kf)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const l=i.getTriangle();l.copy(a),t.push(l)}else{e.getNormal(s);const r=i.getTriangle();r.copy(e),t.push(r)}}splitByTriangle(e){const{normal:t,triangles:i}=this;if(e.getNormal($f).normalize(),Math.abs(1-Math.abs($f.dot(t)))<qB){this.coplanarTriangleUsed=!0;for(let r=0,o=i.length;r<o;r++){const a=i[r];a.coplanarCount=0}const s=[e.a,e.b,e.c];for(let r=0;r<3;r++){const o=(r+1)%3,a=s[r],l=s[o];ts.subVectors(l,a).normalize(),hb.crossVectors($f,ts),eh.setFromNormalAndCoplanarPoint(hb,a),this.splitByPlane(eh,e)}}else e.getPlane(eh),this.splitByPlane(eh,e)}splitByPlane(e,t){const{triangles:i,trianglePool:s}=this;Jf.copy(t),Jf.needsUpdate=!0;for(let r=0,o=i.length;r<o;r++){const a=i[r];if(!Jf.intersectsTriangle(a,es,!0))continue;const{a:l,b:c,c:h}=a;let u=0,f=-1,d=!1,p=[],g=[];const m=[l,c,h];for(let A=0;A<3;A++){const x=(A+1)%3;es.start.copy(m[A]),es.end.copy(m[x]);const b=e.distanceToPoint(es.start),y=e.distanceToPoint(es.end);if(Math.abs(b)<Ra&&Math.abs(y)<Ra){d=!0;break}if(b>0?p.push(A):g.push(A),Math.abs(b)<Ra)continue;let _=!!e.intersectLine(es,ts);!_&&Math.abs(y)<Ra&&(ts.copy(es.end),_=!0),_&&!(ts.distanceTo(es.start)<Kf)&&(ts.distanceTo(es.end)<Kf&&(f=A),u===0?Ft.start.copy(ts):Ft.end.copy(ts),u++)}if(!d&&u===2&&Ft.distance()>Ra)if(f!==-1){f=(f+1)%3;let A=0;A===f&&(A=(A+1)%3);let x=A+1;x===f&&(x=(x+1)%3);const b=s.getTriangle();b.a.copy(m[x]),b.b.copy(Ft.end),b.c.copy(Ft.start),Ds(b)||i.push(b),a.a.copy(m[A]),a.b.copy(Ft.start),a.c.copy(Ft.end),Ds(a)&&(i.splice(r,1),r--,o--)}else{const A=p.length>=2?g[0]:p[0];if(A===0){let E=Ft.start;Ft.start=Ft.end,Ft.end=E}const x=(A+1)%3,b=(A+2)%3,y=s.getTriangle(),_=s.getTriangle();m[x].distanceToSquared(Ft.start)<m[b].distanceToSquared(Ft.end)?(y.a.copy(m[x]),y.b.copy(Ft.start),y.c.copy(Ft.end),_.a.copy(m[x]),_.b.copy(m[b]),_.c.copy(Ft.start)):(y.a.copy(m[b]),y.b.copy(Ft.start),y.c.copy(Ft.end),_.a.copy(m[x]),_.b.copy(m[b]),_.c.copy(Ft.end)),a.a.copy(m[A]),a.b.copy(Ft.end),a.c.copy(Ft.start),Ds(y)||i.push(y),Ds(_)||i.push(_),Ds(a)&&(i.splice(r,1),r--,o--)}else u===3&&console.warn("TriangleClipper: Coplanar clip not handled")}}reset(){this.triangles.length=0,this.trianglePool.clear(),this.coplanarTriangleUsed=!1}}function KB(n){return n=~~n,n+4-n%4}class ub{constructor(e,t=500){this.expansionFactor=1.5,this.type=e,this.length=0,this.array=null,this.setSize(t)}setType(e){if(this.length!==0)throw new Error("TypeBackedArray: Cannot change the type while there is used data in the buffer.");const t=this.array.buffer;this.array=new e(t),this.type=e}setSize(e){if(this.array&&e===this.array.length)return;const t=this.type,i=nb()?SharedArrayBuffer:ArrayBuffer,s=new t(new i(KB(e*t.BYTES_PER_ELEMENT)));this.array&&s.set(this.array,0),this.array=s}expand(){const{array:e,expansionFactor:t}=this;this.setSize(e.length*t)}push(...e){let{array:t,length:i}=this;i+e.length>t.length&&(this.expand(),t=this.array);for(let s=0,r=e.length;s<r;s++)t[i+s]=e[s];this.length+=e.length}clear(){this.length=0}}class $B{constructor(){this.groupAttributes=[{}],this.groupCount=0}getType(e){return this.groupAttributes[0][e].type}getItemSize(e){return this.groupAttributes[0][e].itemSize}getNormalized(e){return this.groupAttributes[0][e].normalized}getCount(e){if(this.groupCount<=e)return 0;const t=this.getGroupAttrArray("position",e);return t.length/t.itemSize}getTotalLength(e){const{groupCount:t,groupAttributes:i}=this;let s=0;for(let r=0;r<t;r++){const o=i[r];s+=o[e].length}return s}getGroupAttrSet(e=0){const{groupAttributes:t}=this;if(t[e])return this.groupCount=Math.max(this.groupCount,e+1),t[e];const i=t[0];for(this.groupCount=Math.max(this.groupCount,e+1);e>=t.length;){const s={};t.push(s);for(const r in i){const o=i[r],a=new ub(o.type);a.itemSize=o.itemSize,a.normalized=o.normalized,s[r]=a}}return t[e]}getGroupAttrArray(e,t=0){const{groupAttributes:i}=this;if(!i[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(t)[e]}initializeArray(e,t,i,s){const{groupAttributes:r}=this,a=r[0][e];if(a){if(a.type!==t)for(let l=0,c=r.length;l<c;l++){const h=r[l][e];h.setType(t),h.itemSize=i,h.normalized=s}}else for(let l=0,c=r.length;l<c;l++){const h=new ub(t);h.itemSize=i,h.normalized=s,r[l][e]=h}}clear(){this.groupCount=0;const{groupAttributes:e}=this;e.forEach(t=>{for(const i in t)t[i].clear()})}delete(e){this.groupAttributes.forEach(t=>{delete t[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class db{constructor(){this.intersectionSet={},this.ids=[]}add(e,t){const{intersectionSet:i,ids:s}=this;i[e]||(i[e]=[],s.push(e)),i[e].push(t)}}const JB=0,ZB=1,eP=2,fb=3,tP=4,pb=5,gb=6,Wi=new v.Ray,mb=new v.Matrix4,hi=new v.Triangle,is=new v.Vector3,Ab=new v.Vector4,xb=new v.Vector4,bb=new v.Vector4,Zf=new v.Vector4,th=new v.Vector4,ih=new v.Vector4,yb=new v.Line3,ep=new v.Vector3,tp=1e-8,iP=1e-15,Ar=-1,xr=1,nh=-2,sh=2,ka=0,br=1,ip=2,nP=1e-14;let rh=null;function vb(n){rh=n}function _b(n,e){n.getMidpoint(Wi.origin),n.getNormal(Wi.direction);const t=e.raycastFirst(Wi,v.DoubleSide);return!!(t&&Wi.direction.dot(t.face.normal)>0)?Ar:xr}function sP(n,e){function t(){return Math.random()-.5}n.getNormal(ep),Wi.direction.copy(ep),n.getMidpoint(Wi.origin);const i=3;let s=0,r=1/0;for(let o=0;o<i;o++){Wi.direction.x+=t()*tp,Wi.direction.y+=t()*tp,Wi.direction.z+=t()*tp,Wi.direction.multiplyScalar(-1);const a=e.raycastFirst(Wi,v.DoubleSide);if(!!(a&&Wi.direction.dot(a.face.normal)>0)&&s++,a!==null&&(r=Math.min(r,a.distance)),r<=iP)return a.face.normal.dot(ep)>0?sh:nh;if(s/i>.5||(o-s+1)/i>.5)break}return s/i>.5?Ar:xr}function rP(n,e){const t=new db,i=new db;return mb.copy(n.matrixWorld).invert().multiply(e.matrixWorld),n.geometry.boundsTree.bvhcast(e.geometry.boundsTree,mb,{intersectsTriangles(s,r,o,a){if(!Ds(s)&&!Ds(r)){let l=s.intersectsTriangle(r,yb,!0);if(!l){const c=s.plane,h=r.plane,u=c.normal,f=h.normal;u.dot(f)===1&&Math.abs(c.constant-h.constant)<nP&&(l=!0)}if(l){let c=n.geometry.boundsTree.resolveTriangleIndex(o),h=e.geometry.boundsTree.resolveTriangleIndex(a);t.add(c,h),i.add(h,c),rh&&(rh.addEdge(yb),rh.addIntersectingTriangles(o,s,a,r))}}return!1}}),{aIntersections:t,bIntersections:i}}function oP(n,e,t,i,s,r,o=!1){const a=t.attributes,l=t.index,c=n*3,h=l.getX(c+0),u=l.getX(c+1),f=l.getX(c+2);for(const d in r){const p=a[d],g=r[d];if(!(d in a))throw new Error(`CSG Operations: Attribute ${d} not available on geometry.`);const m=p.itemSize;d==="position"?(hi.a.fromBufferAttribute(p,h).applyMatrix4(i),hi.b.fromBufferAttribute(p,u).applyMatrix4(i),hi.c.fromBufferAttribute(p,f).applyMatrix4(i),np(hi.a,hi.b,hi.c,e,3,g,o)):d==="normal"?(hi.a.fromBufferAttribute(p,h).applyNormalMatrix(s),hi.b.fromBufferAttribute(p,u).applyNormalMatrix(s),hi.c.fromBufferAttribute(p,f).applyNormalMatrix(s),o&&(hi.a.multiplyScalar(-1),hi.b.multiplyScalar(-1),hi.c.multiplyScalar(-1)),np(hi.a,hi.b,hi.c,e,3,g,o,!0)):(Ab.fromBufferAttribute(p,h),xb.fromBufferAttribute(p,u),bb.fromBufferAttribute(p,f),np(Ab,xb,bb,e,m,g,o))}}function aP(n,e,t,i,s,r,o,a=!1){sp(n,i,s,r,o,a),sp(a?t:e,i,s,r,o,a),sp(a?e:t,i,s,r,o,a)}function wb(n,e,t=!1){switch(n){case JB:if(e===xr||e===sh&&!t)return br;break;case ZB:if(t){if(e===Ar)return ka}else if(e===xr||e===nh)return br;break;case eP:if(t){if(e===xr||e===nh)return br}else if(e===Ar)return ka;break;case tP:if(e===Ar)return ka;if(e===xr)return br;break;case fb:if(e===Ar||e===sh&&!t)return br;break;case pb:if(!t&&(e===xr||e===nh))return br;break;case gb:if(!t&&(e===Ar||e===sh))return br;break;default:throw new Error(`Unrecognized CSG operation enum "${n}".`)}return ip}function np(n,e,t,i,s,r,o=!1,a=!1){const l=c=>{r.push(c.x),s>1&&r.push(c.y),s>2&&r.push(c.z),s>3&&r.push(c.w)};Zf.set(0,0,0,0).addScaledVector(n,i.a.x).addScaledVector(e,i.a.y).addScaledVector(t,i.a.z),th.set(0,0,0,0).addScaledVector(n,i.b.x).addScaledVector(e,i.b.y).addScaledVector(t,i.b.z),ih.set(0,0,0,0).addScaledVector(n,i.c.x).addScaledVector(e,i.c.y).addScaledVector(t,i.c.z),a&&(Zf.normalize(),th.normalize(),ih.normalize()),l(Zf),o?(l(ih),l(th)):(l(th),l(ih))}function sp(n,e,t,i,s,r=!1){for(const o in s){const a=e[o],l=s[o];if(!(o in e))throw new Error(`CSG Operations: Attribute ${o} no available on geometry.`);const c=a.itemSize;o==="position"?(is.fromBufferAttribute(a,n).applyMatrix4(t),l.push(is.x,is.y,is.z)):o==="normal"?(is.fromBufferAttribute(a,n).applyNormalMatrix(i),r&&is.multiplyScalar(-1),l.push(is.x,is.y,is.z)):(l.push(a.getX(n)),c>1&&l.push(a.getY(n)),c>2&&l.push(a.getZ(n)),c>3&&l.push(a.getW(n)))}}class lP{constructor(e){this.triangle=new v.Triangle().copy(e),this.intersects={}}addTriangle(e,t){this.intersects[e]=new v.Triangle().copy(t)}getIntersectArray(){const e=[],{intersects:t}=this;for(const i in t)e.push(t[i]);return e}}class Sb{constructor(){this.data={}}addTriangleIntersection(e,t,i,s){const{data:r}=this;r[e]||(r[e]=new lP(t)),r[e].addTriangle(i,s)}getTrianglesAsArray(e=null){const{data:t}=this,i=[];if(e!==null)e in t&&i.push(t[e].triangle);else for(const s in t)i.push(t[s].triangle);return i}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:t}=this;return t[e]?Object.keys(t[e].intersects).map(i=>parseInt(i)):[]}getIntersectionsAsArray(e=null,t=null){const{data:i}=this,s=new Set,r=[],o=a=>{if(i[a])if(t!==null)i[a].intersects[t]&&r.push(i[a].intersects[t]);else{const l=i[a].intersects;for(const c in l)s.has(c)||(s.add(c),r.push(l[c]))}};if(e!==null)o(e);else for(const a in i)o(a);return r}reset(){this.data={}}}class cP{constructor(){this.enabled=!1,this.triangleIntersectsA=new Sb,this.triangleIntersectsB=new Sb,this.intersectionEdges=[]}addIntersectingTriangles(e,t,i,s){const{triangleIntersectsA:r,triangleIntersectsB:o}=this;r.addTriangleIntersection(e,t,i,s),o.addTriangleIntersection(i,s,e,t)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),vb(this))}complete(){this.enabled&&vb(null)}}const Bs=new v.Matrix4,oh=new v.Matrix3,yr=new v.Triangle,ah=new v.Triangle,Ps=new v.Triangle,lh=new v.Triangle,on=[],vr=[];function hP(n){for(const e of n)return e}function uP(n,e,t,i,s,r={}){const{useGroups:o=!0}=r,{aIntersections:a,bIntersections:l}=rP(n,e),c=[];let h=null,u;return u=o?0:-1,Cb(n,e,a,t,!1,i,s,u),Mb(n,e,a,t,!1,s,u),t.findIndex(d=>d!==gb&&d!==pb)!==-1&&(u=o?n.geometry.groups.length||1:-1,Cb(e,n,l,t,!0,i,s,u),Mb(e,n,l,t,!0,s,u)),on.length=0,vr.length=0,{groups:c,materials:h}}function Cb(n,e,t,i,s,r,o,a=0){const l=n.matrixWorld.determinant()<0;Bs.copy(e.matrixWorld).invert().multiply(n.matrixWorld),oh.getNormalMatrix(n.matrixWorld).multiplyScalar(l?-1:1);const c=n.geometry.groupIndices,h=n.geometry.index,u=n.geometry.attributes.position,f=e.geometry.boundsTree,d=e.geometry.index,p=e.geometry.attributes.position,g=t.ids,m=t.intersectionSet;for(let A=0,x=g.length;A<x;A++){const b=g[A],y=a===-1?0:c[b]+a,_=3*b,E=h.getX(_+0),I=h.getX(_+1),B=h.getX(_+2);yr.a.fromBufferAttribute(u,E).applyMatrix4(Bs),yr.b.fromBufferAttribute(u,I).applyMatrix4(Bs),yr.c.fromBufferAttribute(u,B).applyMatrix4(Bs),r.reset(),r.initialize(yr);const C=m[b];for(let P=0,T=C.length;P<T;P++){const R=3*C[P],M=d.getX(R+0),F=d.getX(R+1),N=d.getX(R+2);ah.a.fromBufferAttribute(p,M),ah.b.fromBufferAttribute(p,F),ah.c.fromBufferAttribute(p,N),r.splitByTriangle(ah)}const S=r.triangles;for(let P=0,T=S.length;P<T;P++){const R=S[P],M=r.coplanarTriangleUsed?sP(R,f):_b(R,f);on.length=0,vr.length=0;for(let F=0,N=i.length;F<N;F++){const j=wb(i[F],M,s);j!==ip&&(vr.push(j),on.push(o[F].getGroupAttrSet(y)))}if(on.length!==0){yr.getBarycoord(R.a,lh.a),yr.getBarycoord(R.b,lh.b),yr.getBarycoord(R.c,lh.c);for(let F=0,N=on.length;F<N;F++){const j=on[F],U=vr[F]===ka;oP(b,lh,n.geometry,n.matrixWorld,oh,j,l!==U)}}}}return g.length}function Mb(n,e,t,i,s,r,o=0){const a=n.matrixWorld.determinant()<0;Bs.copy(e.matrixWorld).invert().multiply(n.matrixWorld),oh.getNormalMatrix(n.matrixWorld).multiplyScalar(a?-1:1);const l=e.geometry.boundsTree,c=n.geometry.groupIndices,h=n.geometry.index,u=n.geometry.attributes,f=u.position,d=[],p=n.geometry.halfEdges,g=new Set,m=jf(n.geometry);for(let A=0,x=m;A<x;A++)A in t.intersectionSet||g.add(A);for(;g.size>0;){const A=hP(g);g.delete(A),d.push(A);const x=3*A,b=h.getX(x+0),y=h.getX(x+1),_=h.getX(x+2);Ps.a.fromBufferAttribute(f,b).applyMatrix4(Bs),Ps.b.fromBufferAttribute(f,y).applyMatrix4(Bs),Ps.c.fromBufferAttribute(f,_).applyMatrix4(Bs);const E=_b(Ps,l);vr.length=0,on.length=0;for(let I=0,B=i.length;I<B;I++){const C=wb(i[I],E,s);C!==ip&&(vr.push(C),on.push(r[I]))}for(;d.length>0;){const I=d.pop();for(let B=0;B<3;B++){const C=p.getSiblingTriangleIndex(I,B);C!==-1&&g.has(C)&&(d.push(C),g.delete(C))}if(on.length!==0){const B=3*I,C=h.getX(B+0),S=h.getX(B+1),P=h.getX(B+2),T=o===-1?0:c[I]+o;if(Ps.a.fromBufferAttribute(f,C),Ps.b.fromBufferAttribute(f,S),Ps.c.fromBufferAttribute(f,P),!Ds(Ps))for(let R=0,M=on.length;R<M;R++){const F=vr[R],N=on[R].getGroupAttrSet(T),j=F===ka;aP(C,S,P,u,n.matrixWorld,oh,N,j!==a)}}}}}function dP(n){for(let e=0;e<n.length-1;e++){const t=n[e],i=n[e+1];if(t.materialIndex===i.materialIndex){const s=t.start,r=i.start+i.count;i.start=s,i.count=r-s,n.splice(e,1),e--}}}function fP(n,e,t,i){t.clear();const s=n.attributes;for(let r=0,o=i.length;r<o;r++){const a=i[r],l=s[a];t.initializeArray(a,l.array.constructor,l.itemSize,l.normalized)}for(const r in t.attributes)i.includes(r)||t.delete(r);for(const r in e.attributes)i.includes(r)||(e.deleteAttribute(r),e.dispose())}function pP(n,e,t){let i=!1,s=-1;const r=n.attributes,o=e.groupAttributes[0];for(const l in o){const c=e.getTotalLength(l),h=e.getType(l),u=e.getItemSize(l),f=e.getNormalized(l);let d=r[l];(!d||d.array.length<c)&&(d=new v.BufferAttribute(new h(c),u,f),n.setAttribute(l,d),i=!0);let p=0;for(let g=0,m=Math.min(t.length,e.groupCount);g<m;g++){const A=t[g].index,{array:x,type:b,length:y}=e.groupAttributes[A][l],_=new b(x.buffer,0,y);d.array.set(_,p),p+=_.length}d.needsUpdate=!0,s=c/d.itemSize}if(n.index){const l=n.index.array;if(l.length<s)n.index=null,i=!0;else for(let c=0,h=l.length;c<h;c++)l[c]=c}let a=0;n.clearGroups();for(let l=0,c=Math.min(t.length,e.groupCount);l<c;l++){const{index:h,materialIndex:u}=t[l],f=e.getCount(h);f!==0&&(n.addGroup(a,f,u),a+=f)}n.setDrawRange(0,s),n.boundsTree=null,i&&n.dispose()}function Eb(n,e){let t=e;return Array.isArray(e)||(t=[],n.forEach(i=>{t[i.materialIndex]=e})),t}class gP{constructor(){this.triangleSplitter=new YB,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new cP}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(t=>({...t}))}evaluate(e,t,i,s=new Zc){let r=!0;if(Array.isArray(i)||(i=[i]),Array.isArray(s)||(s=[s],r=!1),s.length!==i.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),t.prepareGeometry();const{triangleSplitter:o,attributeData:a,attributes:l,useGroups:c,consolidateGroups:h,debug:u}=this;for(;a.length<s.length;)a.push(new $B);s.forEach((A,x)=>{fP(e.geometry,A.geometry,a[x],l)}),u.init(),uP(e,t,i,o,a,{useGroups:c}),u.complete();const f=this.getGroupRanges(e.geometry),d=Eb(f,e.material),p=this.getGroupRanges(t.geometry),g=Eb(p,t.material);p.forEach(A=>A.materialIndex+=d.length);let m=[...f,...p].map((A,x)=>({...A,index:x}));if(c){const A=[...d,...g];h&&(m=m.map(b=>{const y=A[b.materialIndex];return b.materialIndex=A.indexOf(y),b}).sort((b,y)=>b.materialIndex-y.materialIndex));const x=[];for(let b=0,y=A.length;b<y;b++){let _=!1;for(let E=0,I=m.length;E<I;E++){const B=m[E];B.materialIndex===b&&(_=!0,B.materialIndex=x.length)}_&&x.push(A[b])}s.forEach(b=>{b.material=x})}else m=[{start:0,count:1/0,index:0,materialIndex:0}],s.forEach(A=>{A.material=d[0]});return s.forEach((A,x)=>{const b=A.geometry;pP(b,a[x],m),h&&dP(b.groups)}),r?s:s[0]}evaluateHierarchy(e,t=new Zc){e.updateMatrixWorld(!0);const i=(r,o)=>{const a=r.children;for(let l=0,c=a.length;l<c;l++){const h=a[l];h.isOperationGroup?i(h,o):o(h)}},s=r=>{const o=r.children;let a=!1;for(let c=0,h=o.length;c<h;c++){const u=o[c];a=s(u)||a}const l=r.isDirty();if(l&&r.markUpdated(),a&&!r.isOperationGroup){let c;return i(r,h=>{c?c=this.evaluate(c,h,h.operation):c=this.evaluate(r,h,h.operation)}),r._cachedGeometry=c.geometry,r._cachedMaterials=c.material,!0}else return a||l};return s(e),t.geometry=e._cachedGeometry,t.material=e._cachedMaterials,t}reset(){this.triangleSplitter.reset()}}class mP{engine;evaluator;fillMeshName="ClippingFaceFillMesh";fillMeshes=new Map;maxCandidates=22e5;maxTriangleCountPerMesh=12e4;fillMaterial;fillTextureRepeat=60;fillTextureRotation=0;constructor(e){this.engine=e,this.evaluator=new gP;const t=new URL("/texture/fill.png",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,i=new w.TextureLoader().load(t);i.wrapS=w.RepeatWrapping,i.wrapT=w.RepeatWrapping,i.center.set(.5,.5),i.rotation=this.fillTextureRotation,this.fillMaterial=new w.MeshStandardMaterial({color:14079687,map:i,side:w.DoubleSide,toneMapped:!1}),this.fillMaterial.clipShadows=!0,this.fillMaterial.clippingPlanes=e.sectionPlane}clear(){this.fillMeshes.forEach(e=>{e.parent?.remove(e),e.geometry?.dispose?.();const t=e.material;Array.isArray(t)?t.forEach(i=>i.dispose?.()):t&&t!==this.fillMaterial&&t.dispose?.()}),this.fillMeshes.clear()}updataFace(e){this.clear(),e instanceof w.Plane&&this.engine.clipping.fillCutFace&&this.buildSinglePlaneFill(e,"face")}updataFaces(e){this.clear(),!(!Array.isArray(e)||e.length===0)&&this.engine.clipping.fillCutFace&&e.forEach((t,i)=>{if(!(t instanceof w.Plane))return;const s=`plane-${i}-${String(t.name??i)}`;this.buildSinglePlaneFill(t,s)})}buildSinglePlaneFill(e,t){const i=this.engine?.octreeBox?.getBoundingBox?.();if(i==null||i.min==null||i.max==null)return;const s=this.collectCandidateMeshesFromOctree(e);if(s.length===0)return;const r=this.filterMeshesByBoxAndComplexity(e,s);if(r.length===0)return;const o=i.min.distanceTo(i.max),a=o*5,l=.1,c=this.createPlaneBrush(e,a,l),h=[];for(const g of r.slice(0,this.maxCandidates)){const m=this.createWorldBrushFromMesh(g);if(m!=null)try{const x=this.evaluator.evaluate(m,c,fb)?.geometry;if(!x)continue;const b=this.extractPlaneCapGeometry(x,e,l);b&&h.push(b),x.dispose()}catch{}finally{m.geometry.dispose()}}if(c.geometry.dispose(),h.length===0)return;const u=Xn(h,!1);if(h.forEach(g=>g.dispose()),!u)return;this.applyPlanarUv(u,e);const f=this.getFaceOffsetDistance(o),d=this.getFaceOffsetSign();u.translate(e.normal.x*f*d,e.normal.y*f*d,e.normal.z*f*d);const p=new w.Mesh(u,this.fillMaterial);p.name=`${this.fillMeshName}_${t}`,p.frustumCulled=!1,p.renderOrder=20,p.castShadow=!1,p.receiveShadow=!1,this.engine.scene.add(p),this.fillMeshes.set(t,p)}getFaceOffsetDistance(e){return-.001}getFaceOffsetSign(){const e=this.engine?.engineStatus?.clippingFaceOffsetSign;return e===1||e===-1?e:-1}collectCandidateMeshesFromOctree(e){const t=[],i=new Set,s=Array.isArray(this.engine?.engineStatus?.models)?this.engine.engineStatus.models:[];for(const r of s){const o=this.engine.models?.find?.(c=>c.url===r.url);if(!o?.nodesMap)continue;const a=this.getIgnoredIds(r.url),l=Array.isArray(r?.info?.lods)?r.info.lods:[];for(const c of l){const h=c?.octreeBox;if(!h)continue;const u=this.collectIntersectElementIds(h,e);for(const f of u){if(a.has(f))continue;const d=o.nodesMap.get(f);if(!(d?.instance===!0||!Array.isArray(d?.infos)))for(const p of d.infos){const g=p?.mesh;g instanceof w.Mesh&&(i.has(g.uuid)||(i.add(g.uuid),t.push(g)))}}}}return t}getIgnoredIds(e){const t=new Set,i=Array.isArray(this.engine?.engineStatus?.hideModels)?this.engine.engineStatus.hideModels:[],s=Array.isArray(this.engine?.engineStatus?.translucentModels)?this.engine.engineStatus.translucentModels:[],r=i.find(a=>a.url===e)?.ids;Array.isArray(r)&&r.forEach(a=>t.add(a));const o=s.find(a=>a.url===e)?.ids;return Array.isArray(o)&&o.forEach(a=>t.add(a)),t}collectIntersectElementIds(e,t){const i=new Set,s=[e];for(;s.length>0;){const r=s.pop();if(!r)continue;const o=this.octreeNodeToBox3(r);!o||!t.intersectsBox(o)||(Array.isArray(r.elements)&&r.elements.forEach(a=>i.add(a)),Array.isArray(r.children)&&r.children.forEach(a=>s.push(a)))}return i}octreeNodeToBox3(e){if(!e?.min||!e?.max)return null;const t=new w.Vector3(e.min.X*.3048,e.min.Z*.3048,-e.min.Y*.3048),i=new w.Vector3(e.max.X*.3048,e.max.Z*.3048,-e.max.Y*.3048),s=new w.Vector3(Math.min(t.x,i.x),Math.min(t.y,i.y),Math.min(t.z,i.z)),r=new w.Vector3(Math.max(t.x,i.x),Math.max(t.y,i.y),Math.max(t.z,i.z));return new w.Box3(s,r)}filterMeshesByBoxAndComplexity(e,t){const i=[],s=new w.Box3;for(const r of t){const o=r.geometry,a=o?.attributes?.position;!o||!a||a.count===0||(o.index?Math.floor(o.index.count/3):Math.floor(a.count/3))>this.maxTriangleCountPerMesh||(o.boundingBox||o.computeBoundingBox(),o.boundingBox&&(s.copy(o.boundingBox),r.updateWorldMatrix(!0,!1),s.applyMatrix4(r.matrixWorld),e.intersectsBox(s)&&(r.geometry.attributes.position.count>500||i.push(r))))}return i}createPlaneBrush(e,t,i){const s=new w.BoxGeometry(t,t,i),r=e.coplanarPoint(new w.Vector3),o=new w.Quaternion().setFromUnitVectors(new w.Vector3(0,0,1),e.normal.clone().normalize()),a=new w.Matrix4().compose(r,o,new w.Vector3(1,1,1));s.applyMatrix4(a);const l=this.toCsgReadyGeometry(s);return s.dispose(),new Zc(l)}createWorldBrushFromMesh(e){const t=e.geometry;if(!t||!t.attributes?.position)return null;e.updateWorldMatrix(!0,!1);const i=t.clone();i.applyMatrix4(e.matrixWorld);const s=this.toCsgReadyGeometry(i);return i.dispose(),new Zc(s)}toCsgReadyGeometry(e){const t=e.index?e.toNonIndexed():e.clone();t.getAttribute("normal")||t.computeVertexNormals();const i=t.getAttribute("position");if(i&&!t.getAttribute("uv")){const r=new Float32Array(i.count*2);t.setAttribute("uv",new w.Float32BufferAttribute(r,2))}const s=new Set(["position","normal","uv"]);return Object.keys(t.attributes).forEach(r=>{s.has(r)||t.deleteAttribute(r)}),t}extractPlaneCapGeometry(e,t,i){const s=e.index?e.toNonIndexed():e.clone(),r=s.getAttribute("position");if(!r||r.count<3)return s.dispose(),null;const o=t.normal.clone().normalize(),a=new w.Vector3,l=new w.Vector3,c=new w.Vector3,h=new w.Vector3,u=new w.Vector3,f=new w.Vector3,d=new w.Vector3,p=new w.Vector3,g=new w.Vector3,m=Math.max(i*.35,1e-4),A=Math.max(i*.7,1e-4),x=[];for(let y=0;y<r.count;y+=3){if(h.fromBufferAttribute(r,y),u.fromBufferAttribute(r,y+1),f.fromBufferAttribute(r,y+2),l.subVectors(u,h),c.subVectors(f,h),a.crossVectors(l,c),a.lengthSq()<1e-14||(a.normalize(),Math.abs(a.dot(o))<.9))continue;const _=t.distanceToPoint(h),E=t.distanceToPoint(u),I=t.distanceToPoint(f),B=Math.min(_,E,I);if(Math.max(_,E,I)-B>m)continue;const S=(_+E+I)/3;Math.abs(S)>A||S<0||(d.copy(h).addScaledVector(o,-_),p.copy(u).addScaledVector(o,-E),g.copy(f).addScaledVector(o,-I),a.dot(o)<=0?(x.push(d.x,d.y,d.z),x.push(p.x,p.y,p.z),x.push(g.x,g.y,g.z)):(x.push(d.x,d.y,d.z),x.push(g.x,g.y,g.z),x.push(p.x,p.y,p.z)))}if(s.dispose(),x.length<9)return null;const b=new w.BufferGeometry;return b.setAttribute("position",new w.Float32BufferAttribute(x,3)),b.computeVertexNormals(),b}applyPlanarUv(e,t){const i=e.getAttribute("position");if(!i||i.count===0)return;const{tangent:s,bitangent:r}=this.getPlaneBasis(t.normal.clone().normalize()),o=new w.Vector3,a=new Float32Array(i.count*2);let l=1/0,c=-1/0,h=1/0,u=-1/0;for(let p=0;p<i.count;p++){o.fromBufferAttribute(i,p);const g=o.dot(s),m=o.dot(r),A=p*2;a[A]=g,a[A+1]=m,l=Math.min(l,g),c=Math.max(c,g),h=Math.min(h,m),u=Math.max(u,m)}const f=Math.max(c-l,1e-6),d=Math.max(u-h,1e-6);for(let p=0;p<a.length;p+=2)a[p]=(a[p]-l)/f*this.fillTextureRepeat,a[p+1]=(a[p+1]-h)/d*this.fillTextureRepeat;e.setAttribute("uv",new w.BufferAttribute(a,2))}getPlaneBasis(e){const t=new w.Vector3(1,0,0),i=new w.Vector3(0,1,0),s=new w.Vector3(0,0,1),r=Math.abs(e.dot(t)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(s));let l=t;o<=r&&o<=a?l=i:a<=r&&a<=o&&(l=s),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new w.Vector3().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}}class AP{engine;clippingTolerance=1e-4;sectionBox;sectionFace;clippingStencil;clippingCSGSimple=null;currentClippingMode="";sectionCatchFace;fillCutFace=!0;constructor(e){this.engine=e,this.sectionCatchFace=new MD(this.engine);let t=new w.Plane(new w.Vector3(0,0,1),1e5);t.name="前";let i=new w.Plane(new w.Vector3(0,0,1),1e5);i.name="左";let s=new w.Plane(new w.Vector3(0,0,1),1e5);s.name="后";let r=new w.Plane(new w.Vector3(0,0,1),1e5);r.name="右";let o=new w.Plane(new w.Vector3(0,0,1),1e5);o.name="顶";let a=new w.Plane(new w.Vector3(0,0,1),1e5);a.name="底";let l=new w.Plane(new w.Vector3(0,0,1),1e5);l.name="face",this.engine.sectionPlane=[t,i,s,r,o,a,l]}init(){this.sectionBox=new SD(this.engine),this.sectionFace=new CD(this.engine),this.clippingCSGSimple=new mP(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}setFillCutFace(e){this.fillCutFace=e}getFillCutFace(){return this.fillCutFace}clippingModel(e){let t=[];e.forEach(r=>{let o=this.engine.models.find(a=>a.url===r.url);r.ids.forEach(a=>{o.nodesMap.get(a).infos.forEach(l=>{t.push(l.box)})})}),this.active("box");let i=s(t);this.sectionBox.setBox(i);function s(r){let o=new w.Vector3(1e8,1e9,1e10),a=new w.Vector3(-1e8,-1e9,-1e10);return r.forEach(l=>{l.min.x<o.x&&(o.x=l.min.x),l.min.y<o.y&&(o.y=l.min.y),l.min.z<o.z&&(o.z=l.min.z),l.max.x>a.x&&(a.x=l.max.x),l.max.y>a.y&&(a.y=l.max.y),l.max.z>a.z&&(a.z=l.max.z)}),new w.Box3(o,a)}}updateClippingValue(e){let t=this.sectionBox.maxBox,i=t.min.x+(t.max.x-t.min.x)*e.x.min*.01,s=t.min.y+(t.max.y-t.min.y)*e.y.min*.01,r=t.min.z+(t.max.z-t.min.z)*e.z.min*.01,o=t.min.x+(t.max.x-t.min.x)*e.x.max*.01,a=t.min.y+(t.max.y-t.min.y)*e.y.max*.01,l=t.min.z+(t.max.z-t.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:i,minY:s,minZ:r,maxX:o,maxY:a,maxZ:l})}active(e){this.engine.engineStatus.isForceFree=!0,this.sectionFace.disActive(),this.sectionBox.disActive(),this.sectionCatchFace.cancel(),this.currentClippingMode=e,e=="x"?(this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(-1,0,0))):e=="y"?(this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(0,0,-1))):e=="z"?(this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(0,-1,0))):e=="box"?(this.sectionBox.init(),this.sectionBox.active()):e=="face"&&(this.sectionCatchFace.init(),this.sectionCatchFace.catch_face(t=>{this.sectionFace.init(),this.sectionFace.active();let i=this.engine.octreeBox.getBoundingBox(),s=i.min.clone().add(i.max.clone()).multiplyScalar(.5),r=t.position.clone().sub(s),o=new w.Vector3(t.dir.x,t.dir.y,t.dir.z),a=r.dot(o);this.sectionFace.setFaceNormal(t.dir,a)}))}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.sectionFace.disabled(),this.engine.engineStatus.isForceFree=!1}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.sectionFace.recover()}reverse(){this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.clippingCSGSimple?.clear(),this.sectionCatchFace.cancel(),this.currentClippingMode="",this.engine.engineStatus.isForceFree=!1}isPointInClippingRange(e,t=this.clippingTolerance){if(!this.isVector3Like(e))return!1;const i=this.getEffectiveClippingPlanes();return i.length===0?!0:i.every(s=>s.distanceToPoint(e)>=-t)}filterIntersectionsByClipping(e,t=this.clippingTolerance){return!Array.isArray(e)||e.length===0?[]:e.filter(i=>this.isPointInClippingRange(i?.point,t))}getEffectiveClippingPlanes(){const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];if(this.currentClippingMode==="box")return e.slice(0,6).filter(t=>t instanceof w.Plane);if(this.currentClippingMode==="x"||this.currentClippingMode==="y"||this.currentClippingMode==="z"||this.currentClippingMode==="face"){const t=e[6];return t instanceof w.Plane?[t]:[]}return[]}isVector3Like(e){return e!=null&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}setSectionByView(e,t){this.sectionFace.disActive(),this.sectionBox.disActive(),this.scaleBox(),this.sectionFace.init(!0);const i=this.engine.octreeBox.getBoundingBox(),s=new w.Vector3((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2,(i.min.z+i.max.z)/2),o=new w.Vector3(t.x,t.y,t.z).normalize().clone().negate(),l=new w.Vector3(e.x,e.y,e.z).clone().sub(s).dot(o);this.sectionFace.setFaceNormalPlaneOnly(o,l),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face"}}class xP{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeLevel,name:t.info.baseInfo.name,url:t.url})}),e}getTypeTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeType,name:t.info.baseInfo.name,url:t.url})}),e}getMajorTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeMajor,name:t.info.baseInfo.name,url:t.url})}),e}}class bP{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,i=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(s=>{if(s instanceof w.Mesh){const r=s.geometry;if(r&&r.attributes){const o=r.attributes.position;if(o){const a=o.count;e+=a;let l=0;r.index?l=r.index.count/3:l=a/3,t+=l}}}}),this.engine.engineStatus.models.forEach(s=>{i=i+(Array.isArray(s?.info?.modelEdge)?s.info.modelEdge.length:0)}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:i})}}class yP{engine;extended‌=new Map;constructor(e){this.engine=e}init(){}updateExtended(e,t){let i=this.extended‌.get(e);i==null?this.extended‌.set(e,t):t.forEach((s,r)=>{i.set(r,s)})}getModelPropertiesWithName(e,t,i,s){let r=this.extended‌.get(e),o=this.engine.engineStatus.models.find(l=>l.url===e);o.properties==null?pa(e+"/property",l=>{let c=JSON.parse(l);o.properties=c,setTimeout(()=>{a(c,i,t,s)},100)},()=>{},o?.key):a(o.properties,i,t,s);function a(l,c,h,u){let f={};l.models[h.toString()||""].forEach(p=>{i.includes(l.names[p[1]])&&(f[l.names[p[1]]]=l.values[p[2]])}),r!=null&&r.has(h)&&f.push(r.get(h)),u?.({id:h,properties:f})}}getModelProperties(e,t,i){let s=this.extended‌.get(e),r=this.engine.engineStatus.models.find(a=>a.url===e);r.properties==null&&pa(e+"/property",a=>{let l=JSON.parse(a);r.properties=l,setTimeout(()=>{o(l,t,i)},100)},()=>{},r?.key),o(r.properties,t,i);function o(a,l,c){let h=[],u=a.models[l.toString()||""],f=u.map(d=>d[0]);f=f.filter((d,p)=>f.indexOf(d)===p),f.forEach(d=>{let p={name:a.categorys[d],children:[]};h.push(p),u.filter(g=>g[0]===d).forEach(g=>{p.children.push({name:a.names[g[1]],value:a.values[g[2]]})})}),s!=null&&s.has(l)&&h.push(s.get(l)),c?.({properties:h,materials:h})}}}class vP{engine;constructor(e){this.engine=e}getModelTypes(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.typeName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelMajors(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.majorName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelLevels(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.levelName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelMappers(e){}getModelMapper(e,t){let i=this.engine.engineStatus.models.find(o=>o.url==e);return i?i.info.modelMapper.find(o=>o.id==t):null}getModelsWithLevelType(e,t,i=null){let s=[];return this.engine.engineStatus.models.forEach(r=>{let o={url:r.url,ids:[]};s.push(o),r.info.modelMapper.filter(l=>l.levelName===e&&l.typeName===t).forEach(l=>{o.ids.push(Number(l.id))})}),i&&i(s),s}getModelsWithType(e,t=null){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.typeName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithLevel(e,t){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.levelName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithMajor(e,t){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.majorName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}}class _P{config;constructor(e){this.config={temperature:.7,maxTokens:2e4,timeout:3e5,...e}}async chat(e){const t=new AbortController,i=setTimeout(()=>t.abort(),this.config.timeout);try{const s=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!1}),signal:t.signal});if(clearTimeout(i),!s.ok){const o=await s.json().catch(()=>({}));throw new Error(`API请求失败 (${s.status}): ${o.error?.message||o.message||s.statusText}`)}return(await s.json()).choices?.[0]?.message?.content||""}catch(s){throw clearTimeout(i),s.name==="AbortError"?new Error("请求超时,请重试"):s.message.includes("Failed to fetch")?new Error(`网络请求失败,请检查:
5260
+ }`};const Tx={turbidity:10,rayleigh:3,mieCoefficient:.005,mieDirectionalG:.7,elevation:2,azimuth:180,exposure:.5,orthoExposureScale:1.5,cloudCoverage:.4,cloudDensity:.4,cloudElevation:.5,showSunDisc:!0},xf="sunrise_clear",Dx=.2,bf=[{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}}],Bx=bf.reduce((n,e)=>(n[e.id]=e,n),{}),Px=2e6;class dD{engine;sky=null;sun=new w.Vector3;params={...Tx,...Bx[xf].params};currentPreset=xf;currentIntensity=Dx;currentEnvironmentTarget=null;skyScale=45e4;skyName="bim_engine_sky";savedCameraFar=null;previousBackground=null;previousEnvironment=null;previousBackgroundIntensity=1;previousEnvironmentIntensity=1;previousToneMapping=w.NoToneMapping;previousToneMappingExposure=1;hasCapturedSceneState=!1;constructor(e){this.engine=e}activate(){if(!this.engine?.scene)return;if(this.sky){this.sky.visible=!0,this._captureSceneState(),this._expandCameraFarForSky(),this._applyParamsToSky();return}const e=new Rc;e.scale.setScalar(this.skyScale),e.name=this.skyName,this.sky=e,this.engine.scene.add(e),this._captureSceneState(),this._expandCameraFarForSky(),this.engine.renderer&&(this.engine.renderer.toneMapping=w.ACESFilmicToneMapping,this.engine.scene.background=null),this._applyParamsToSky()}close(e=!0){this.sky&&(this._restoreCameraFar(),this._restoreSceneState(e),e?(this.engine?.scene?.remove(this.sky),this.sky.material.dispose(),this.sky.geometry.dispose(),this.sky=null):this.sky.visible=!1)}isActive(){return this.sky!=null&&this.engine?.scene?.children?.includes(this.sky)}getParams(){return{...this.params}}setParams(e){Object.assign(this.params,e),this._applyParamsToSky(),this.engine?.renderer&&(e.exposure!==void 0||e.orthoExposureScale!==void 0)&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}setPreset(e){const t=Bx[e];t&&(this.currentPreset=e,this.params={...Tx,...t.params},this._applyParamsToSky(),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure()))}getCurrentPreset(){return this.currentPreset}getPresetNames(){return bf.map(e=>e.id)}getPresetList(){return bf.map(e=>({id:e.id,names:[...e.names],params:{...e.params}}))}setIntensity(e){if(this.currentIntensity=Math.max(e,0),!(!this.sky?.visible||!this.engine?.scene)){if(!this.currentEnvironmentTarget){this._refreshEnvironmentMap();return}this.engine.scene.environmentIntensity=this.currentIntensity}}getIntensity(){return this.currentIntensity}update(e){if(!this.sky?.visible)return;const t=this.sky.material.uniforms;t&&"time"in t&&(t.time.value=e??performance.now()*.001),this.engine?.renderer&&(this.engine.renderer.toneMappingExposure=this._getEffectiveExposure())}_isOrthographicCamera(){const e=this.engine?.camera;return e!=null&&e.type==="OrthographicCamera"}_getEffectiveExposure(){const e=this.params.exposure;return this._isOrthographicCamera()?e*this.params.orthoExposureScale:e}_expandCameraFarForSky(){const e=this.engine?.camera;if(!e||typeof e.far!="number")return;const t=e.far;t>=Px||(this.savedCameraFar==null&&(this.savedCameraFar=t),e.far=Px,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix())}_restoreCameraFar(){if(this.savedCameraFar==null||!this.engine?.camera)return;const e=this.engine.camera;typeof e.far=="number"&&(e.far=this.savedCameraFar,typeof e.updateProjectionMatrix=="function"&&e.updateProjectionMatrix(),this.savedCameraFar=null)}_applyParamsToSky(){if(!this.sky)return;const e=this.sky.material.uniforms;this._setUniformValue(e,"turbidity",this.params.turbidity),this._setUniformValue(e,"rayleigh",this.params.rayleigh),this._setUniformValue(e,"mieCoefficient",this.params.mieCoefficient),this._setUniformValue(e,"mieDirectionalG",this.params.mieDirectionalG),this._setUniformValue(e,"cloudCoverage",this.params.cloudCoverage),this._setUniformValue(e,"cloudDensity",this.params.cloudDensity),this._setUniformValue(e,"cloudElevation",this.params.cloudElevation),this._setUniformValue(e,"showSunDisc",this.params.showSunDisc?1:0);const t=w.MathUtils.degToRad(90-this.params.elevation),i=w.MathUtils.degToRad(this.params.azimuth);this.sun.setFromSphericalCoords(1,t,i),this._setUniformValue(e,"sunPosition",this.sun),this.engine?.renderer&&(this.engine.renderer.toneMapping=w.ACESFilmicToneMapping,this.engine.renderer.toneMappingExposure=this._getEffectiveExposure(),this.sky.visible&&this._refreshEnvironmentMap())}_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??w.NoToneMapping,this.previousToneMappingExposure=this.engine.renderer?.toneMappingExposure??1,this.hasCapturedSceneState=!0)}_restoreSceneState(e){!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),e&&(this._disposeEnvironmentTarget(),this.previousBackground=null,this.previousEnvironment=null,this.previousBackgroundIntensity=1,this.previousEnvironmentIntensity=1,this.previousToneMapping=w.NoToneMapping,this.previousToneMappingExposure=1,this.hasCapturedSceneState=!1))}_refreshEnvironmentMap(){if(!this.sky||!this.engine?.renderer||!this.engine?.scene)return;this._disposeEnvironmentTarget();const e=new w.Scene,t=this.sky.clone();t.material=this.sky.material.clone(),e.add(t);const i=new w.PMREMGenerator(this.engine.renderer);this.currentEnvironmentTarget=i.fromScene(e,0,.1,this.skyScale*2),i.dispose(),this.engine.scene.background=null,this.engine.scene.environment=this.currentEnvironmentTarget.texture,this.engine.scene.environmentIntensity=this.currentIntensity,t.material.dispose()}_disposeEnvironmentTarget(){this.currentEnvironmentTarget?.dispose(),this.currentEnvironmentTarget=null}_setUniformValue(e,t,i){const s=e[t];s&&(i instanceof w.Vector3&&typeof s.value?.copy=="function"?s.value.copy(i):s.value=i)}}class fD{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()||[],i=this.engine.skyManager?.getPresetList()||[];return{ground:e.map(s=>this._toPresetItem(s)),hdr:t.map(s=>this._toPresetItem(s)),sky:i.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?.switchModel(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.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===w.NoToneMapping&&(t.toneMapping=w.ACESFilmicToneMapping),t.toneMappingExposure=2*e,t.toneMappingExposure==1?this.engine.renderer.toneMapping=0:this.engine.renderer.toneMapping=w.ACESFilmicToneMapping)}_syncSettingsFromModules(){this.settings=this._readCurrentSettingsFromModules()}_buildDefaultSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,t=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,s=this.engine.renderer?.toneMappingExposure,r=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??wn,a=this.engine.hdr?.getIntensity?.(),l=this.engine.skyManager?.getIntensity?.(),c=this.engine.skyManager?.getCurrentPreset?.()??xf,h=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()),contrast:this._uniformToPercent(t,sA),saturation:this._uniformToPercent(e,nA),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),Ec),lightIntensity:this._exposureToPercent(s,Vm),gtaoIntensity:this._unitToPercent(i,iA)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??Af,edgeOpacity:this._unitToPercent(r,Ix),showGrid:this.engine.grid?.getVisible?.()??gf,showLevel:this.engine.level?.getVisible?.()??Ex,showGround:this.engine.ground?.getVisible?.()??Cx,groundId:this.engine.ground?.getCurrentId?.()??wx,groundHeight:this.engine.ground?.getHeight?.()??Sx},environment:{type:h?"sky":o!==wn?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,Mx),skyPreset:c,skyParams:{},skyIntensity:this._unitToPercent(l,Dx)}}}_readCurrentSettingsFromModules(){const e=this.engine.composerModule?.saturationPass?.uniforms?.saturation?.value,t=this.engine.composerModule?.saturationPass?.uniforms?.contrast?.value,i=this.engine.composerModule?.gtaoPass?.blendIntensity,s=this.engine.renderer?.toneMappingExposure,r=this.engine.modelEdge?.getOpacity?.(),o=this.engine.hdr?.getCurrentHdrId?.()??this.settings.environment.hdrId,a=this.engine.hdr?.getIntensity?.(),l=this.engine.skyManager?.getIntensity?.(),c=this.engine.skyManager?.getCurrentPreset?.()??this.settings.environment.skyPreset,h=this.engine.skyManager?.getParams?.(),u=this.engine.skyManager?.isActive?.()===!0;return{render:{mode:this._toRenderMode(this.engine.engineModelModule?.getCurrentMode?.()??this.settings.render.mode),contrast:this._uniformToPercent(t,this.settings.render.contrast/100+.5),saturation:this._uniformToPercent(e,this.settings.render.saturation/100+.5),shadowIntensity:this._shadowToPercent(this._getDirectionalLightShadowIntensity(),this.settings.render.shadowIntensity/50),lightIntensity:this._exposureToPercent(s,this.settings.render.lightIntensity/50),gtaoIntensity:this._unitToPercent(i,this.settings.render.gtaoIntensity/100)},display:{showEdge:this.engine.modelEdge?.isEnabled?.()??this.settings.display.showEdge,edgeOpacity:this._unitToPercent(r,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:u?"sky":o!==wn?"hdr":"none",hdrId:o,hdrIntensity:this._unitToPercent(a,this.settings.environment.hdrIntensity/100),skyPreset:c,skyParams:h?this._clone(h):this._clone(this.settings.environment.skyParams),skyIntensity:this._unitToPercent(l,this.settings.environment.skyIntensity/100)}}}_toRenderMode(e){return e==="simple"||e==="balance"||e==="advanced"?e:ux}_uniformToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent((i-.5)*100)}_shadowToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*50)}_exposureToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*50)}_unitToPercent(e,t){const i=typeof e=="number"?e:t;return this._clampPercent(i*100)}_clampPercent(e){return Math.min(100,Math.max(0,Math.round(e)))}_getDirectionalLightShadowIntensity(){const e=this.engine.scene?.children?.filter(i=>i instanceof w.DirectionalLight);return!e||e.length===0?Ec:(e.find(i=>i.castShadow)??e[0]).shadow?.intensity??Ec}_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(wn),t===this.environmentApplyVersion&&(this.engine.skyManager?.close(!0),t===this.environmentApplyVersion))switch(e.type){case"none":break;case"hdr":if(e.hdrId!==wn){if(await this.engine.hdr?.setHdr(e.hdrId),t!==this.environmentApplyVersion){this._applyEnvironmentSettings(this._clone(this.settings.environment));return}this.engine.hdr?.setIntensity(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(i=>i instanceof w.DirectionalLight);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 sn(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){var e=Math.random()*16|0,t=n=="x"?e:e&3|8;return t.toString(16)})}class Kn{engine;handelBehaved;setting;constructor(e){this.engine=e,this.handelBehaved=Rd(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 i=this.setting.unit,s=i;return t==1?i=="mm"?e=e*1e3:i=="cm"?e=e*100:i=="dm"?e=e*10:i=="m"?e=e*1:i=="km"&&(e=e*.001):t==2&&(i=="mm"?e=e*1e3*1e3:i=="cm"?e=e*100*100:i=="dm"?e=e*10*10:i=="m"?e=e*1*1:i=="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(i=>{i.highlight==!0&&(i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight"))})}handelKeyEscDown(){this.cancelCurrentSelectedAnnotation();let e=this.engine.measure.annotationData,t=!0;for(let i in e)for(let s=e[i].length-1;s>=0;s--){let r=e[i][s];r.isSelect==!0&&(r.container.remove(),e[i].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 i=e[t].length-1;i>=0;i--){let s=e[t][i];s.highlight==!0&&(s.container.remove(),e[t].splice(i,1))}}clearHighlight(){let e=this.engine.measure.annotationData;for(let t in e)e[t].forEach(i=>{i.highlight=!1,i.container.classList.remove("Hight"),i.container.getElementsByTagName("svg")[0].classList.remove("Hight")})}drawNormalAnnotation(){let e=this;this.engine.measure.annotationData.normalAnnotation.forEach(p=>{d(p)}),this.engine.measure.annotationData.elevationAnnotation.forEach(p=>{f(p)}),this.engine.measure.annotationData.coordinateAnnotation.forEach(p=>{u(p)}),this.engine.measure.annotationData.angleAnnotation.forEach(p=>{l(p)}),this.engine.measure.annotationData.areaAnnotation.forEach(p=>{c(p)}),this.engine.measure.annotationData.slopeAnnotation.forEach(p=>{h(p)});function l(p){if(p.container==null){let I=['<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">'+p.text+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="angle-annotation",p.container.id=p.id,p.container.style.pointerEvents="none",p.container.innerHTML=I,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point1),m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point2),A=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point3),x=e.engine.reactBoundingClientRect.left,b=e.engine.reactBoundingClientRect.top;g.x+=x,g.y+=b,m.x+=x,m.y+=b,A.x+=x,A.y+=b;let y=p.container;y.getElementsByTagName("circle")[0].setAttribute("cx",g.x),y.getElementsByTagName("circle")[0].setAttribute("cy",g.y),y.getElementsByTagName("circle")[1].setAttribute("cx",m.x),y.getElementsByTagName("circle")[1].setAttribute("cy",m.y),y.getElementsByTagName("circle")[2].setAttribute("cx",A.x),y.getElementsByTagName("circle")[2].setAttribute("cy",A.y),y.getElementsByTagName("polyline")[0].setAttribute("points",g.x+","+g.y+" "+m.x+","+m.y),y.getElementsByTagName("polyline")[1].setAttribute("points",m.x+","+m.y+" "+A.x+","+A.y);let _=m.x,E=m.y-30;y.getElementsByTagName("rect")[0].setAttribute("x",_-40),y.getElementsByTagName("rect")[0].setAttribute("y",E-12.5),y.getElementsByTagName("text")[0].setAttribute("x",_),y.getElementsByTagName("text")[0].setAttribute("y",E+4),y.getElementsByTagName("text")[0].innerHTML=p.text,y.style.top="0px",y.style.left="0px"}function c(p){if(p.container==null){let S=['<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(p.text,2)+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="area-annotation",p.container.id=p.id,p.container.innerHTML=S,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}if(!p.points||p.points.length<2)return;let g=e.engine.reactBoundingClientRect.left,m=e.engine.reactBoundingClientRect.top,A=[],x=0,b=0;for(let S=0;S<p.points.length;S++){let P=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.points[S]);P.x+=g,P.y+=m,A.push(P),x+=P.x,b+=P.y}x=x/A.length,b=b/A.length;let y=A.map(S=>S.x+","+S.y).join(" "),_=[...A];A.length>=3&&_.push(A[0]);let E=_.map(S=>S.x+","+S.y).join(" "),I=p.container;I.getElementsByTagName("polygon")[0].setAttribute("points",A.length>=3?y:""),I.getElementsByTagName("polyline")[0].setAttribute("points",E);let B=x,C=b;I.getElementsByTagName("rect")[0].setAttribute("x",B-40),I.getElementsByTagName("rect")[0].setAttribute("y",C-12.5),I.getElementsByTagName("text")[0].setAttribute("x",B+10),I.getElementsByTagName("text")[0].setAttribute("y",C+4),I.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(p.text,2),I.style.top="0px",I.style.left="0px"}function h(p){if(p.container==null){let E=['<svg class="measureSvg">',"<defs>",'<marker id="slope-arrow-'+p.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-'+p.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"> '+p.text+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="slope-annotation",p.container.id=p.id,p.container.innerHTML=E,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point1),m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point2),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;g.x+=A,g.y+=x,m.x+=A,m.y+=x;let b=p.container;b.getElementsByTagName("polyline")[0].setAttribute("points",g.x+","+g.y+" "+m.x+","+m.y);let y=(g.x+m.x)/2,_=(g.y+m.y)/2-30;b.getElementsByTagName("rect")[0].setAttribute("x",y-50),b.getElementsByTagName("rect")[0].setAttribute("y",_-12.5),b.getElementsByTagName("text")[0].setAttribute("x",y),b.getElementsByTagName("text")[0].setAttribute("y",_+4),b.getElementsByTagName("text")[0].innerHTML=p.text,b.style.top="0px",b.style.left="0px"}function u(p){if(p.container==null){let I=['<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(p.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(-p.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(p.textY,1)+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="coordinate-annotation",p.container.id=p.id,p.container.style.position="absolute",p.container.style.pointerEvents="none",p.container.innerHTML=I,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=p.container,m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;m.x+=A,m.y+=x,g.style.top="0px",g.style.left="0px";let b=g.getElementsByTagName("circle")[0];b&&(b.setAttribute("cx",m.x),b.setAttribute("cy",m.y));let y=g.getElementsByTagName("rect"),_=g.getElementsByTagName("text"),E=-55;y[0]&&(y[0].setAttribute("x",m.x+10),y[0].setAttribute("y",m.y+10+E)),_[0]&&(_[0].setAttribute("x",m.x+10+50),_[0].setAttribute("y",m.y+10+16+E)),y[1]&&(y[1].setAttribute("x",m.x+10),y[1].setAttribute("y",m.y+10+30+E)),_[1]&&(_[1].setAttribute("x",m.x+10+50),_[1].setAttribute("y",m.y+10+46+E)),y[2]&&(y[2].setAttribute("x",m.x+10),y[2].setAttribute("y",m.y+10+60+E)),_[2]&&(_[2].setAttribute("x",m.x+10+50),_[2].setAttribute("y",m.y+10+76+E)),_[0]&&(_[0].innerHTML="X: "+e.getMeasureText(p.textX,1)),_[1]&&(_[1].innerHTML="Y: "+e.getMeasureText(-p.textZ,1)),_[2]&&(_[2].innerHTML="Z: "+e.getMeasureText(p.textY,1))}function f(p){if(p.container==null){let b=['<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(p.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("");p.container=document.createElement("div"),p.container.className="elevation-annotation",p.container.id=p.id,p.container.style.position="absolute",p.container.style.pointerEvents="none",p.container.innerHTML=b,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=p.container,m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point),A=e.engine.reactBoundingClientRect.left,x=e.engine.reactBoundingClientRect.top;g.style.top=m.y+x-48+"px",g.style.left=m.x+A-16+"px",g.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(p.text,1)}function d(p){if(p.container==null){let y=['<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(p.text,1)+"</text>","</svg>"].join("");p.container=document.createElement("div"),p.container.className="normal-annotation",p.container.id=p.id,p.container.innerHTML=y,e.engine.measure.annotationContainer.appendChild(p.container),p.container.getElementsByTagName("svg")[0].addEventListener("click",function(){e.clearHighlight(),p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0,e.engine.events.trigger(St.MeasureClick,p)}),p.isSelect&&(p.container.getElementsByTagName("svg")[0].classList.add("Hight"),p.highlight=!0)}let g=p.container;if(p.point1==null||p.point2==null){g.style.display="none";return}else g.style.display="block";let m=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point1),A=new rt(e.engine.camera,e.engine.renderer,e.engine.scene).worldToScreen(p.point2),x=e.engine.reactBoundingClientRect.left,b=e.engine.reactBoundingClientRect.top;m.x+=x,m.y+=b,A.x+=x,A.y+=b,g.getElementsByTagName("polyline")[0].setAttribute("points",m.x+","+m.y+" "+A.x+","+A.y),g.getElementsByTagName("circle")[0].setAttribute("cx",m.x),g.getElementsByTagName("circle")[0].setAttribute("cy",m.y),g.getElementsByTagName("circle")[1].setAttribute("cx",A.x),g.getElementsByTagName("circle")[1].setAttribute("cy",A.y),g.getElementsByTagName("rect")[0].setAttribute("x",m.x*.5+A.x*.5-40),g.getElementsByTagName("rect")[0].setAttribute("y",m.y*.5+A.y*.5-12.5),g.getElementsByTagName("text")[0].setAttribute("x",m.x*.5+A.x*.5+50-40),g.getElementsByTagName("text")[0].setAttribute("y",m.y*.5+A.y*.5+16-12.5),g.getElementsByTagName("text")[0].innerHTML=e.getMeasureText(p.text,1),g.style.top="0px",g.style.left="0px"}}}class pD{engine;isActive=!1;tools;points=[];behavior;catchDir=0;type="point";constructor(e){this.engine=e,this.tools=new Kn(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}setSelectType(e){this.type=e}getMeshesMinMaxY(e){if(!Array.isArray(e)||e.length===0)return null;let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let s=0;s<e.length;s++){const r=e[s];if(!r)continue;typeof r.updateMatrixWorld=="function"&&r.updateMatrixWorld(!0);const o=new w.Box3().setFromObject(r);!Number.isFinite(o.min.y)||!Number.isFinite(o.max.y)||(o.min.y<t&&(t=o.min.y),o.max.y>i&&(i=o.max.y))}return!Number.isFinite(t)||!Number.isFinite(i)?null:{minY:t,maxY:i}}handleMouseClick(e){if(e.catch==null)return;let t=e.catch.point;if(this.type=="element"){let r=this.engine.interactionModule.getCatchMeshs(e);var i=this.getMeshesMinMaxY(r);this.catchDir==0?t.set(t.x,i?.minY,t.z):t.set(t.x,i?.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(r=>r.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:sn(),isSelect:!0,type:"clear-height"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=e.catch;if(this.type=="element"){let s=e.catch.point.clone();s.set(s.x,this.points[0].y,s.z);let r=new w.Raycaster(s.add(new w.Vector3(0,.01,0)),new w.Vector3(0,this.catchDir==0?-1:1,0));i.point=this.points[0];const o=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(r))??this.engine.octreeBox.rayInterationModel(r);if(o.length===0){t.point2=null;return}t.point1=s,t.point2=o[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(St.MeasureChanged,t)}else{let s=new w.Raycaster(e.catch.point.clone().add(new w.Vector3(0,.01,0)),new w.Vector3(0,this.catchDir==0?-1:1,0));const r=this.engine.clipping?.filterIntersectionsByClipping(this.engine.octreeBox.rayInterationModel(s))??this.engine.octreeBox.rayInterationModel(s);if(r.length===0){t.point2=null;return}t.point1=i.point,t.point2=r[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(St.MeasureChanged,t)}}}class gD{engine;tools;isActive=!1;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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 i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);if(i==null)return;i.point2=t.point,i.isSelect=!1,this.points=[],this.engine.events.trigger(St.MeasureChanged,i),this.behavior.clearLastPoint()}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.normalAnnotation.find(s=>s.isSelect==!0);i==null&&(i={id:sn(),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(i)),i.point2=t.point,i.text=i.point1.clone().distanceTo(i.point2.clone())}}}class mD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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(i=>i.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(o=>o.isSelect==!0);t==null&&(t={text:null,id:sn(),isSelect:!0,type:"clear-distance"},this.engine.measure.annotationData.normalAnnotation.push(t));let i=new w.Raycaster(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(i))??this.engine.octreeBox.rayInterationModel(i);if(s.length==0){t.point2=null;return}let r=e.catch;t.point1=r.point,t.point2=s[0].point,t.text=t.point1.clone().distanceTo(t.point2.clone()),this.engine.events.trigger(St.MeasureChanged,t)}}class AD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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(i=>i.isSelect==!0);t==null&&(t={id:sn(),point:e.catch.point.clone(),text:e.catch.point.y,isSelect:!0,type:"elevation"},this.engine.measure.annotationData.elevationAnnotation.push(t)),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(i=>i.isSelect==!0);t!=null&&(t.isSelect=!1,t.point=e.catch.point.clone(),t.text=e.catch.point.y,this.engine.events.trigger(St.MeasureChanged,t))}}class xD{engine;isActive=!1;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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(i=>i.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(i=>i.isSelect==!0);if(t==null){t={id:sn(),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(St.MeasureChanged,t)}createMeasure(){let e=this.engine.measure.annotationData.coordinateAnnotation.find(t=>t.isSelect==!0);e!=null&&(e.isSelect=!1,this.engine.events.trigger(St.MeasureChanged,e))}}class bD{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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,i){const s=new w.Vector3().subVectors(e,t),r=new w.Vector3().subVectors(i,t),o=s.length(),a=r.length();if(o===0||a===0)return 0;const c=s.dot(r)/(o*a),h=Math.max(-1,Math.min(1,c));return Math.acos(h)*(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 i=this.engine.measure.annotationData.angleAnnotation.find(s=>s.isSelect==!0);if(i==null)return;i.point3=t.point.clone(),i.angle=this.calculateAngle(i.point1,i.point2,i.point3),i.text=i.angle.toFixed(2)+"°",i.isSelect=!1,i.type="angle",this.points=[],this.engine.events.trigger(St.MeasureChanged,i)}}handleMouseMove(e){if(e.catch!=null&&this.points.length!=1&&this.points.length==2){let t=this.engine.measure.annotationData.angleAnnotation.find(i=>i.isSelect==!0);t==null&&(t={id:sn(),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)}}}class yD{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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,i=new w.Vector3(0,0,0);for(let s=0;s<t;s++){const r=(s+1)%t;i.x+=(e[s].y-e[r].y)*(e[s].z+e[r].z),i.y+=(e[s].z-e[r].z)*(e[s].x+e[r].x),i.z+=(e[s].x-e[r].x)*(e[s].y+e[r].y)}return i.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 i=this.getCurrentDrawingMeasure();i==null?(i={id:sn(),points:this.points.map(s=>s.clone()),area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(i)):i.points=this.points.map(s=>s.clone()),this.points.length>=3?(i.area=this.calculateArea(this.points),i.text=i.area):(i.area=0,i.text=0)}handleMouseMove(e){if(e.catch!=null&&this.points.length>=1){let t=this.getCurrentDrawingMeasure();t==null&&(t={id:sn(),points:[],area:0,text:0,isSelect:!0,type:"area"},this.engine.measure.annotationData.areaAnnotation.push(t));const i=this.points.map(s=>s.clone());i.push(e.catch.point.clone()),t.points=i,i.length>=3?(t.area=this.calculateArea(i),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(St.MeasureChanged,e)):this.engine.measure.tools.handelKeyEscDown()}}class vD{engine;tools;points=[];behavior;constructor(e){this.engine=e,this.tools=new Kn(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 i=t.y-e.y,s=t.x-e.x,r=t.z-e.z,o=Math.sqrt(s*s+r*r);if(o===0)return{percentage:0,angle:0,heightDiff:i,horizontalDist:0,type:"slope"};const a=i/o*100,c=Math.atan(i/o)*(180/Math.PI);return{percentage:a,angle:c,heightDiff:i,horizontalDist:o,type:"slope"}}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){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);if(i==null)return;console.log("进来了"),i.point2=t.point.clone();const s=this.calculateSlope(i.point1,i.point2);i.slopePercentage=s.percentage,i.slopeAngle=s.angle,i.heightDiff=s.heightDiff,i.horizontalDist=s.horizontalDist,i.text=s.percentage.toFixed(2)+"%",i.isSelect=!1,this.points=[],this.engine.events.trigger(St.MeasureChanged,i)}}handleMouseMove(e){if(e.catch==null)return;let t=e.catch;if(t!=null&&this.points.length==1){let i=this.engine.measure.annotationData.slopeAnnotation.find(r=>r.isSelect==!0);i==null&&(i={id:sn(),point1:this.points[0].clone(),point2:t.point.clone(),slopePercentage:0,slopeAngle:0,heightDiff:0,horizontalDist:0,text:"0.00%",isSelect:!0,type:"slope"},this.engine.measure.annotationData.slopeAnnotation.push(i)),i.point2=t.point.clone();const s=this.calculateSlope(i.point1,i.point2);i.slopePercentage=s.percentage,i.slopeAngle=s.angle,i.heightDiff=s.heightDiff,i.horizontalDist=s.horizontalDist,i.text=s.percentage.toFixed(2)+"%"}}}class _D{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 i=this.points[0].clone(),s=this.projectPointToFace(i,t);if(s==null)return;let r=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);r==null&&(r={id:sn(),type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(r)),r.point1=i,r.point2=s.footPoint,r.text=s.distance,r.facePoint=t.point.clone(),r.faceNormal=t.normal.clone(),r.isSelect=!1,this.points=[],this.behavior?.clearLastPoint?.(),this.engine.events.trigger(St.MeasureChanged,r)}handleMouseMove(e){if(e.catch==null||this.points.length!==1)return;const t=this.getFaceInfo(e.catch);if(t==null)return;const i=this.points[0].clone(),s=this.projectPointToFace(i,t);if(s==null)return;let r=this.engine.measure.annotationData.normalAnnotation.find(o=>o.isSelect==!0);r==null&&(r={id:sn(),point1:i.clone(),point2:s.footPoint.clone(),text:s.distance,type:"clear-distance",isSelect:!0},this.engine.measure.annotationData.normalAnnotation.push(r)),r.point1=i,r.point2=s.footPoint,r.text=s.distance,r.facePoint=t.point.clone(),r.faceNormal=t.normal.clone()}getFaceInfo(e){if(e?.face==null||e?.point==null)return null;const t=e.point.clone?.(),i=this.getWorldFaceNormal(e);return!(t instanceof w.Vector3)||i==null?null:{point:t,normal:i}}getWorldFaceNormal(e){const t=e?.normal??e?.face?.normal;if(t==null)return null;const i=t.clone(),s=e?.matrix??e?.object?.matrixWorld;return s!=null&&i.transformDirection(s),i.lengthSq()<1e-10?null:i.normalize()}projectPointToFace(e,t){const i=new w.Vector3().subVectors(e,t.point).dot(t.normal),s=e.clone().sub(t.normal.clone().multiplyScalar(i));return{footPoint:s,distance:e.distanceTo(s)}}}class wD{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 pD(e),this.distanceMeasure=new gD(e),this.clearDistanceMeasure=new mD(e),this.elevationMeasure=new AD(e),this.pointMeasure=new xD(e),this.angleMeasure=new bD(e),this.areaMeasure=new yD(e),this.slopeMeasure=new vD(e),this.faceDistanceMeasure=new _D(e),this.tools=new Kn(e),this.annotationContainer=document.createElement("div"),this.annotationContainer.className="annotation-container",e.container.appendChild(this.annotationContainer)}active(){this.isActive=!0,this.engine.modelEdge.loadModelEdge(),this.tools.active()}disActive(){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.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 i=0;i<t.length;i++)t[i].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.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}}class SD{engine;isActive=!1;isCtrlDown=!1;listenersAttached=!1;box;pickPoint;pickNormal;pickMesh;box_;plane;meshs;isDrag=!1;maxBox;faceIdleOpacity=0;faceHoverOpacity=.05;transformControls=new Map;transformAnchors=new Map;transformHelpers=new Map;faceMetaMap=new Map;isSyncingTransform=!1;transformHandleSize=1.05;transformHandleColor=16777215;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};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 i=t[0];this.isDrag=!0,this.pickPoint=i.point.clone(),this.pickMesh=i.object;const s=this.pickMesh?.userData?.dragNormal?.clone?.(),r=i.face?.normal?.clone?.();if(this.pickNormal=(s??r??new w.Vector3(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 o=new w.Plane;o.setFromNormalAndCoplanarPoint(new w.Vector3(0,1,0),this.pickPoint),this.plane=o}else{const o=new w.Vector3(this.engine.camera.position.x,this.pickPoint.y,this.engine.camera.position.z),a=new w.Plane;a.setFromNormalAndCoplanarPoint(o.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,i){return new w.Vector3(Math.max(t.x,Math.min(i.x,e.x)),Math.max(t.y,Math.min(i.y,e.y)),Math.max(t.z,Math.min(i.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 i=new w.Vector3;if(e.raycaster.ray.intersectPlane(this.plane,i)){const s=i.clone().sub(this.pickPoint.clone()).dot(this.pickNormal.clone());if(!!this.pickMesh?.userData?.isMinFace){const o=this.box_.min.clone().add(this.pickNormal.clone().setLength(s));this.box.min=this.clampVector3(o,this.maxBox.min,this.box.max)}else{const o=this.box_.max.clone().add(this.pickNormal.clone().setLength(s));this.box.max=this.clampVector3(o,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,i=this.maxBox.max.z-this.maxBox.min.z,s=this.toPercent((this.box.min.x-this.maxBox.min.x)/e*100),r=this.toPercent((this.box.max.x-this.maxBox.min.x)/e*100),o=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),l=this.toPercent((this.box.min.z-this.maxBox.min.z)/i*100),c=this.toPercent((this.box.max.z-this.maxBox.min.z)/i*100),h={x:{min:s,max:r},y:{min:o,max:a},z:{min:l,max:c}};this.engine.events.trigger(St.SectionMove,h)}toPercent(e){return e<0?0:e>100?100:e}getInteractiveMeshes(){return this.meshs.filter(e=>e.type==="Mesh")}createRaycasterFromMouseEvent(e){const t=new w.Raycaster,i=new w.Vector2,s=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/s*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}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),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)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}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 w.Plane);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 i=e.getHelper(),s=[];i.traverse(r=>{if(r?.name!==t||!r.geometry)return;const o=r.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const l=a.getCenter(new w.Vector3);if(!(t==="X"&&l.x<0||t==="Y"&&l.y<0||t==="Z"&&l.z<0))return;const h=o.parameters,u=h&&h.radiusTop===0&&h.radiusBottom===.04&&h.height===.1,f=h&&h.radiusTop===.2&&h.radiusBottom===0&&h.height===.6;(u||f)&&s.push(r)}),s.forEach(r=>{r.parent?.remove(r)})}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,i=this.engine.camera;if(!t||!i)return;const s=new w.Object3D;s.name=`SectionBoxTransformAnchor_${e}`,s.visible=this.isActive,this.engine.scene.add(s);const r=new xx(i,t);r.name=`SectionBoxTransformControl_${e}`,r.setMode("translate"),r.setSpace("local"),r.showX=!0,r.showY=!1,r.showZ=!1,r.size=this.transformHandleSize,r.setColors(this.transformHandleColor,this.transformHandleColor,this.transformHandleColor,this.transformHandleHoverColor),r.enabled=this.isActive,r.attach(s),this.keepSingleDirectionArrow(r,"X"),r.addEventListener("dragging-changed",a=>{this.engine.controls.enabled=!a.value,a.value===!0?this.clearClippingBoxFill():this.updateClippingBoxFill()}),r.addEventListener("objectChange",()=>{this.handleTransformObjectChange(e)});const o=r.getHelper();o.visible=this.isActive,this.engine.scene.add(o),this.transformAnchors.set(e,s),this.transformControls.set(e,r),this.transformHelpers.set(e,o)}updateFaceTransformControl(e,t,i,s){this.ensureFaceTransformControl(e);const r=this.transformAnchors.get(e),o=this.transformControls.get(e);if(!r||!o)return;const a=this.getFaceTransformOffset(),l=new w.Quaternion().setFromUnitVectors(new w.Vector3(1,0,0),t.clone().normalize()),c=i.clone().add(t.clone().setLength(a));this.faceMetaMap.set(e,{normal:t.clone().normalize(),isMinFace:s,center:i.clone()}),this.isSyncingTransform=!0,r.position.copy(c),r.quaternion.copy(l),r.visible=this.isActive,o.object!==r&&o.attach(r),o.enabled=this.isActive;const h=this.transformHelpers.get(e);h&&(h.visible=this.isActive),this.isSyncingTransform=!1}getDominantAxis(e){const t=Math.abs(e.x),i=Math.abs(e.y),s=Math.abs(e.z);return t>=i&&t>=s?"x":i>=t&&i>=s?"y":"z"}handleTransformObjectChange(e){if(this.isSyncingTransform)return;const t=this.transformAnchors.get(e),i=this.faceMetaMap.get(e);if(!t||!i||!this.box||!this.maxBox)return;const s=i.normal,r=this.getDominantAxis(s),o=this.getFaceTransformOffset(),a=s[r],l=t.position[r]-a*o;if(i.isMinFace){const c=this.maxBox.min[r],h=this.box.max[r];this.box.min[r]=Math.max(c,Math.min(h,l))}else{const c=this.box.min[r],h=this.maxBox.max[r];this.box.max[r]=Math.max(c,Math.min(h,l))}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 w.Group,t.name="ClippingBox",this.engine.scene.add(t)),[{name:"前",normal:new w.Vector3(0,0,-1),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.min.z)]},{name:"后",normal:new w.Vector3(0,0,1),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.max.z)]},{name:"右",normal:new w.Vector3(1,0,0),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)]},{name:"左",normal:new w.Vector3(-1,0,0),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z)]},{name:"顶",normal:new w.Vector3(0,1,0),isMinFace:!1,planePoint:e.max,vertices:[new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.min.z)]},{name:"底",normal:new w.Vector3(0,-1,0),isMinFace:!0,planePoint:e.min,vertices:[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.min.y,e.max.z)]}].forEach(s=>{this.createFace(t,s.vertices,s.normal,s.name,s.isMinFace,s.planePoint)}),Bd(this.engine).forEach(s=>{s.material&&Array.isArray(s.material)?s.material.forEach(r=>{r.clippingPlanes=this.engine.sectionPlane}):s.material.clippingPlanes=this.engine.sectionPlane})}createFace(e,t,i,s,r,o){const a=new w.BufferGeometry,l=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]),c=[0,2,1,0,3,2];a.setAttribute("position",new w.BufferAttribute(l,3)),a.setIndex(c);let h=this.meshs.find(A=>A.name===s);if(h==null){const A=new w.MeshBasicMaterial({color:65280,transparent:!0,opacity:this.faceIdleOpacity,side:w.DoubleSide});A.polygonOffset=!0,A.polygonOffsetFactor=1,A.polygonOffsetUnits=4,h=new w.Mesh(a,A),h.name=s,e.add(h),this.meshs.push(h)}else h.geometry=a;h.userData={dragNormal:i.clone(),isMinFace:r,faceName:s};const u=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]),f=new w.LineBasicMaterial({color:255}),d=new w.BufferGeometry;d.setAttribute("position",new w.BufferAttribute(u,3));let p=this.meshs.find(A=>A.name===s+"Line");p==null?(p=new w.Line(d,f),p.name=s+"Line",e.add(p),this.meshs.push(p)):(p.geometry=d,p.material=f);const g=new w.Vector3;t.forEach(A=>g.add(A)),g.multiplyScalar(1/t.length),this.updateFaceTransformControl(s,i,g,r);const m=this.engine.sectionPlane.find(A=>A.name==s);m&&m.setFromNormalAndCoplanarPoint(i.clone().setLength(-1),o)}}class CD{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 w.Vector3(0,0,1);distance=0;center=null;current_center=null;dragStartDistance=0;idleOpacity=.02;hoverOpacity=.05;transformControl=null;transformAnchor=null;transformHelper=null;isSyncingTransformControl=!1;moveEpsilon=1e-5;transformHandleSize=1.15;transformHandleColor=16777215;transformHandleHoverColor=16776960;handleNativeMouseDown=e=>{if(e.button!==0||!(this.isCtrlDown||e.ctrlKey))return;const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);i.length!==0&&(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseDown({button:e.button,raycaster:t,intersects:i}))};handleNativeMouseMove=e=>{if(!this.isDrag&&!(this.isCtrlDown||e.ctrlKey)){this.resetMeshOpacity();return}const t=this.createRaycasterFromMouseEvent(e),i=t.intersectObjects(this.getInteractiveMeshes(),!1);this.isDrag&&(e.preventDefault(),e.stopImmediatePropagation()),this.handleMouseMove({raycaster:t,intersects:i})};handleNativeMouseUp=e=>{e.button!==0||!this.isDrag||(e.preventDefault(),e.stopImmediatePropagation(),this.handleMouseUp({button:e.button}))};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.transformAnchor||!this.center)return;const e=this.normal.clone().normalize(),t=this.getDistanceRange(e),i=this.getTransformHandleOffset(),s=this.transformAnchor.position.clone().sub(this.center).dot(e)-i,r=Math.min(t.max,Math.max(t.min,s));Math.abs(r-Number(this.distance))>this.moveEpsilon?this.updata_face(r):Math.abs(s-r)>this.moveEpsilon&&this.updateTransformControl(e)};constructor(e){this.engine=e,this.meshs=[],this.box=null}active(){if(this.isActive==!0)return;this.isActive=!0,this.engine.scene.children.filter(t=>t.type=="Group"&&t.name=="ClippingBox").forEach(t=>{t.children.forEach(i=>{i.name.includes("face")&&(i.visible=!0)})}),this.attachListeners(),this.ensureTransformControl(),this.setTransformControlVisible(!0);const e=this;Bd(e.engine).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name=="face"),t)}),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(i=>{i.name.includes("face")&&(i.visible=!1)})})}init(e){const t=this.engine.octreeBox.getBoundingBox();this.box=t,this.distance=0,this.center=new w.Vector3((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,i){this.angleX=e,this.angleY=t,this.angleZ=i,this.distance=0,this.normal=new w.Vector3(0,1,0).applyAxisAngle(new w.Vector3(1,0,0),e).applyAxisAngle(new w.Vector3(0,0,1),t).applyAxisAngle(new w.Vector3(0,1,0),i).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 i=this.engine.sectionPlane?.find(s=>s.name==="face");if(i){const s=this.center.clone().add(this.normal.clone().multiplyScalar(t));i.setFromNormalAndCoplanarPoint(this.normal.clone().multiplyScalar(this.direction),s)}this.updateClippingFaceFill()}activateClippingOnly(){if(this.isActive)return;this.isActive=!0;const e=this;Bd(e.engine).forEach(t=>{t.material&&Array.isArray(t.material)?t.material.forEach(i=>{i.clippingPlanes=e.engine.sectionPlane}):t.material.clippingPlanes=e.engine.sectionPlane,e.engine.clipping.clippingStencil?.addMesh(e.engine.sectionPlane.find(i=>i.name==="face"),t)})}reverse(){this.direction=this.direction*-1,this.updata_face(this.distance),this.updateClippingFaceFill()}getFaceAngle(){return{angleX:this.angleX,angleY:this.angleY,angleZ:this.angleZ,direction:this.direction}}updata_face(e){if(!this.box)return;this.distance=e;let t=this.engine.scene.children.find(b=>b.type=="Group"&&b.name=="ClippingBox");t==null&&(t=new w.Group,t.name="ClippingBox",this.engine.scene.add(t));const i=this.normal.clone().normalize(),s=this.center??new w.Vector3((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=s.clone();const{tangent:r,bitangent:o}=this.getPlaneBasis(i),a=this.getBoxCorners(this.box),l=this.box.min.distanceTo(this.box.max),c=Math.max(l*.02,.01);let h=1/0,u=-1/0,f=1/0,d=-1/0;a.forEach(b=>{const y=b.clone().sub(s),_=y.dot(r),E=y.dot(o);h=Math.min(h,_),u=Math.max(u,_),f=Math.min(f,E),d=Math.max(d,E)}),h-=c,u+=c,f-=c,d+=c;const p=i.clone().multiplyScalar(e),g=s.clone().add(r.clone().multiplyScalar(h)).add(o.clone().multiplyScalar(f)).add(p),m=s.clone().add(r.clone().multiplyScalar(u)).add(o.clone().multiplyScalar(f)).add(p),A=s.clone().add(r.clone().multiplyScalar(u)).add(o.clone().multiplyScalar(d)).add(p),x=s.clone().add(r.clone().multiplyScalar(h)).add(o.clone().multiplyScalar(d)).add(p);this.current_center=s.clone().add(p),this.createFace(t,[g,m,A,x],i,"face"),this.updateTransformControl(i)}createFace(e,t,i,s){const r=new w.BufferGeometry,o=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=[0,1,2,0,2,3];r.setAttribute("position",new w.BufferAttribute(o,3)),r.setIndex(a);let l=this.meshs.find(p=>p.name==s);if(l==null){const p=new w.MeshBasicMaterial({color:65280,transparent:!0,opacity:this.idleOpacity,side:w.DoubleSide});p.polygonOffset=!0,p.polygonOffsetFactor=1,p.polygonOffsetUnits=4,l=new w.Mesh(r,p),l.name=s,e.add(l),this.meshs.push(l)}else l.geometry=r;l.normal=i.clone();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 w.LineBasicMaterial({color:255}),u=new w.BufferGeometry;u.setAttribute("position",new w.BufferAttribute(c,3));let f=this.meshs.find(p=>p.name==s+"Line");f==null?(f=new w.Line(u,h),f.name=s+"Line",e.add(f),this.meshs.push(f)):(f.geometry=u,f.material=h);const d=this.engine.sectionPlane.find(p=>p.name==s);d&&this.current_center&&d.setFromNormalAndCoplanarPoint(i.clone().setLength(this.direction),this.current_center)}getPlaneBasis(e){const t=new w.Vector3(1,0,0),i=new w.Vector3(0,1,0),s=new w.Vector3(0,0,1),r=Math.abs(e.dot(t)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(s));let l=t;o<=r&&o<=a?l=i:a<=r&&a<=o&&(l=s),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new w.Vector3().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}getBoxCorners(e){return[new w.Vector3(e.min.x,e.min.y,e.min.z),new w.Vector3(e.min.x,e.min.y,e.max.z),new w.Vector3(e.min.x,e.max.y,e.min.z),new w.Vector3(e.min.x,e.max.y,e.max.z),new w.Vector3(e.max.x,e.min.y,e.min.z),new w.Vector3(e.max.x,e.min.y,e.max.z),new w.Vector3(e.max.x,e.max.y,e.min.z),new w.Vector3(e.max.x,e.max.y,e.max.z)]}getDistanceRange(e){if(!this.box)return{min:0,max:0};const t=this.center??new w.Vector3((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),i=this.getBoxCorners(this.box);let s=1/0,r=-1/0;return i.forEach(o=>{const a=o.clone().sub(t).dot(e);s=Math.min(s,a),r=Math.max(r,a)}),{min:s,max:r}}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)}keepSingleDirectionArrow(e,t="X"){const i=e.getHelper(),s=[];i.traverse(r=>{if(r?.name!==t||!r.geometry)return;const o=r.geometry;o.boundingBox||o.computeBoundingBox();const a=o.boundingBox;if(!a)return;const l=a.getCenter(new w.Vector3);if(!(t==="X"&&l.x<0||t==="Y"&&l.y<0||t==="Z"&&l.z<0))return;const h=o.parameters,u=h&&h.radiusTop===0&&h.radiusBottom===.04&&h.height===.1,f=h&&h.radiusTop===.2&&h.radiusBottom===0&&h.height===.6;(u||f)&&s.push(r)}),s.forEach(r=>{r.parent?.remove(r)})}ensureTransformControl(){if(this.transformControl&&this.transformAnchor)return;const e=this.engine.renderer?.domElement,t=this.engine.camera;if(!e||!t)return;const i=new w.Object3D;i.name="SectionFaceTransformAnchor",i.visible=this.isActive,this.engine.scene.add(i);const s=new xx(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(i),this.keepSingleDirectionArrow(s,"X"),s.addEventListener("dragging-changed",o=>{this.engine.controls.enabled=!o.value,o.value===!0?this.clearClippingFaceFill():this.updateClippingFaceFill()}),s.addEventListener("objectChange",this.handleTransformObjectChange);const r=s.getHelper();r.visible=this.isActive,this.engine.scene.add(r),this.transformAnchor=i,this.transformControl=s,this.transformHelper=r}setTransformControlVisible(e){this.ensureTransformControl(),this.transformControl&&(this.transformControl.enabled=e),this.transformHelper&&(this.transformHelper.visible=e),this.transformAnchor&&(this.transformAnchor.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(),i=this.current_center.clone().add(e.clone().setLength(t)),s=new w.Quaternion().setFromUnitVectors(new w.Vector3(1,0,0),e.clone().normalize().multiplyScalar(-1));this.isSyncingTransformControl=!0,this.transformAnchor.position.copy(i),this.transformAnchor.quaternion.copy(s),this.transformAnchor.visible=this.isActive,this.transformControl.object!==this.transformAnchor&&this.transformControl.attach(this.transformAnchor),this.transformControl.enabled=this.isActive,this.transformHelper&&(this.transformHelper.visible=this.isActive),this.isSyncingTransformControl=!1}createRaycasterFromMouseEvent(e){const t=new w.Raycaster,i=new w.Vector2,s=this.engine.renderer.domElement.clientWidth,r=this.engine.renderer.domElement.clientHeight;return i.x=e.offsetX/s*2-1,i.y=-(e.offsetY/r)*2+1,t.setFromCamera(i,this.engine.camera),t}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),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)),window.removeEventListener("keydown",this.handleNativeKeyDown),window.removeEventListener("keyup",this.handleNativeKeyUp),this.listenersAttached=!1,this.isCtrlDown=!1}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 i=t[0],s=i.point.clone();this.isDrag=!0,this.pickPoint=s;const o=(i.face?.normal?.clone()??this.normal.clone()).clone();if(o.dot(this.normal)<0&&o.multiplyScalar(-1),o.normalize(),this.pickNormal=o,this.engine.controls.enabled=!1,this.dragStartDistance=Number(this.distance)||0,o.y==0){const a=new w.Plane;a.setFromNormalAndCoplanarPoint(new w.Vector3(0,1,0),s),this.plane=a}else{const a=new w.Vector3(this.engine.camera.position.x,s.y,this.engine.camera.position.z),l=new w.Plane;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.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 i=this.pickPoint,s=this.pickNormal,r=this.plane;if(i!=null&&s!=null&&r!=null){const o=new w.Vector3;if(e.raycaster.ray.intersectPlane(r,o)){const a=o.clone().sub(i.clone()).dot(s.clone()),l=this.getDistanceRange(this.normal.clone().normalize()),c=this.dragStartDistance+a;this.distance=Math.min(l.max,Math.max(l.min,c)),this.updata_face(this.distance)}}}}class MD{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})}}const Lx=0,ED=1,ID=2,Rx=2,yf=1.25,kx=1,li=32,Wt=li/4,Fx=65535,TD=Math.pow(2,-24),vf=Symbol("SKIP_GENERATION");function DD(n){return n.index?n.index.count:n.attributes.position.count}function fr(n){return DD(n)/3}function BD(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function PD(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=BD(t,i);n.setIndex(new v.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function Ox(n,e){const t=fr(n),i=e||n.drawRange,s=i.start/3,r=(i.start+i.count)/3,o=Math.max(0,s),a=Math.min(t,r)-o;return[{offset:Math.floor(o),count:Math.floor(a)}]}function Ux(n,e){if(!n.groups||!n.groups.length)return Ox(n,e);const t=[],i=e||n.drawRange,s=i.start/3,r=(i.start+i.count)/3,o=fr(n),a=[];for(const h of n.groups){const{start:u,count:f}=h,d=u/3,p=isFinite(f)?f:o*3-u,g=(u+p)/3;d<r&&g>s&&(a.push({pos:Math.max(s,d),isStart:!0}),a.push({pos:Math.min(r,g),isStart:!1}))}a.sort((h,u)=>h.pos!==u.pos?h.pos-u.pos:h.type==="end"?-1:1);let l=0,c=null;for(const h of a){const u=h.pos;l!==0&&u!==c&&t.push({offset:c,count:u-c}),l+=h.isStart?1:-1,c=u}return t}function _f(n,e,t,i,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,u=1/0,f=1/0,d=1/0,p=-1/0,g=-1/0,m=-1/0;const A=n.offset||0;for(let x=(e-A)*6,b=(e+t-A)*6;x<b;x+=6){const y=n[x+0],_=n[x+1],E=y-_,I=y+_;E<r&&(r=E),I>l&&(l=I),y<u&&(u=y),y>p&&(p=y);const B=n[x+2],C=n[x+3],S=B-C,P=B+C;S<o&&(o=S),P>c&&(c=P),B<f&&(f=B),B>g&&(g=B);const T=n[x+4],R=n[x+5],M=T-R,F=T+R;M<a&&(a=M),F>h&&(h=F),T<d&&(d=T),T>m&&(m=T)}i[0]=r,i[1]=o,i[2]=a,i[3]=l,i[4]=c,i[5]=h,s[0]=u,s[1]=f,s[2]=d,s[3]=p,s[4]=g,s[5]=m}function Nx(n,e,t=null,i=null,s=null){const r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(s===null)s=new Float32Array(t*6),s.offset=e;else if(e<0||t+e>s.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,c=r.offset||0;let h=3;r.isInterleavedBufferAttribute&&(h=r.data.stride);const u=["getX","getY","getZ"],f=s.offset;for(let d=e,p=e+t;d<p;d++){const m=(i?i[d]:d)*3,A=(d-f)*6;let x=m+0,b=m+1,y=m+2;o&&(x=o[x],b=o[b],y=o[y]),a||(x=x*h+c,b=b*h+c,y=y*h+c);for(let _=0;_<3;_++){let E,I,B;a?(E=r[u[_]](x),I=r[u[_]](b),B=r[u[_]](y)):(E=l[x+_],I=l[b+_],B=l[y+_]);let C=E;I<C&&(C=I),B<C&&(C=B);let S=E;I>S&&(S=I),B>S&&(S=B);const P=(S-C)/2,T=_*2;s[A+T+0]=C+P,s[A+T+1]=P+(Math.abs(C)+P)*TD}}return s}function It(n,e,t){return t.min.x=e[n],t.min.y=e[n+1],t.min.z=e[n+2],t.max.x=e[n+3],t.max.y=e[n+4],t.max.z=e[n+5],t}function zx(n){let e=-1,t=-1/0;for(let i=0;i<3;i++){const s=n[i+3]-n[i];s>t&&(t=s,e=i)}return e}function Gx(n,e){e.set(n)}function Vx(n,e,t){let i,s;for(let r=0;r<3;r++){const o=r+3;i=n[r],s=e[r],t[r]=i<s?i:s,i=n[o],s=e[o],t[o]=i>s?i:s}}function kc(n,e,t){for(let i=0;i<3;i++){const s=e[n+2*i],r=e[n+2*i+1],o=s-r,a=s+r;o<t[i]&&(t[i]=o),a>t[i+3]&&(t[i+3]=a)}}function Ma(n){const e=n[3]-n[0],t=n[4]-n[1],i=n[5]-n[2];return 2*(e*t+t*i+i*e)}const $n=32,LD=(n,e)=>n.candidate-e.candidate,Ms=new Array($n).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Fc=new Float32Array(6);function RD(n,e,t,i,s,r){let o=-1,a=0;if(r===Lx)o=zx(e),o!==-1&&(a=(e[o]+e[o+3])/2);else if(r===ED)o=zx(n),o!==-1&&(a=kD(t,i,s,o));else if(r===ID){const l=Ma(n);let c=yf*s;const h=t.offset||0,u=(i-h)*6,f=(i+s-h)*6;for(let d=0;d<3;d++){const p=e[d],A=(e[d+3]-p)/$n;if(s<$n/4){const x=[...Ms];x.length=s;let b=0;for(let _=u;_<f;_+=6,b++){const E=x[b];E.candidate=t[_+2*d],E.count=0;const{bounds:I,leftCacheBounds:B,rightCacheBounds:C}=E;for(let S=0;S<3;S++)C[S]=1/0,C[S+3]=-1/0,B[S]=1/0,B[S+3]=-1/0,I[S]=1/0,I[S+3]=-1/0;kc(_,t,I)}x.sort(LD);let y=s;for(let _=0;_<y;_++){const E=x[_];for(;_+1<y&&x[_+1].candidate===E.candidate;)x.splice(_+1,1),y--}for(let _=u;_<f;_+=6){const E=t[_+2*d];for(let I=0;I<y;I++){const B=x[I];E>=B.candidate?kc(_,t,B.rightCacheBounds):(kc(_,t,B.leftCacheBounds),B.count++)}}for(let _=0;_<y;_++){const E=x[_],I=E.count,B=s-E.count,C=E.leftCacheBounds,S=E.rightCacheBounds;let P=0;I!==0&&(P=Ma(C)/l);let T=0;B!==0&&(T=Ma(S)/l);const R=kx+yf*(P*I+T*B);R<c&&(o=d,c=R,a=E.candidate)}}else{for(let y=0;y<$n;y++){const _=Ms[y];_.count=0,_.candidate=p+A+y*A;const E=_.bounds;for(let I=0;I<3;I++)E[I]=1/0,E[I+3]=-1/0}for(let y=u;y<f;y+=6){let I=~~((t[y+2*d]-p)/A);I>=$n&&(I=$n-1);const B=Ms[I];B.count++,kc(y,t,B.bounds)}const x=Ms[$n-1];Gx(x.bounds,x.rightCacheBounds);for(let y=$n-2;y>=0;y--){const _=Ms[y],E=Ms[y+1];Vx(_.bounds,E.rightCacheBounds,_.rightCacheBounds)}let b=0;for(let y=0;y<$n-1;y++){const _=Ms[y],E=_.count,I=_.bounds,C=Ms[y+1].rightCacheBounds;E!==0&&(b===0?Gx(I,Fc):Vx(I,Fc,Fc)),b+=E;let S=0,P=0;b!==0&&(S=Ma(Fc)/l);const T=s-b;T!==0&&(P=Ma(C)/l);const R=kx+yf*(S*b+P*T);R<c&&(o=d,c=R,a=_.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}function kD(n,e,t,i){let s=0;const r=n.offset;for(let o=e,a=e+t;o<a;o++)s+=n[(o-r)*6+i*2];return s/t}class wf{constructor(){this.boundingData=new Float32Array(6)}}function FD(n,e,t,i,s,r){let o=i,a=i+s-1;const l=r.pos,c=r.axis*2,h=t.offset||0;for(;;){for(;o<=a&&t[(o-h)*6+c]<l;)o++;for(;o<=a&&t[(a-h)*6+c]>=l;)a--;if(o<a){for(let u=0;u<3;u++){let f=e[o*3+u];e[o*3+u]=e[a*3+u],e[a*3+u]=f}for(let u=0;u<6;u++){const f=o-h,d=a-h,p=t[f*6+u];t[f*6+u]=t[d*6+u],t[d*6+u]=p}o++,a--}else return o}}function OD(n,e,t,i,s,r){let o=i,a=i+s-1;const l=r.pos,c=r.axis*2,h=t.offset||0;for(;;){for(;o<=a&&t[(o-h)*6+c]<l;)o++;for(;o<=a&&t[(a-h)*6+c]>=l;)a--;if(o<a){let u=n[o];n[o]=n[a],n[a]=u;for(let f=0;f<6;f++){const d=o-h,p=a-h,g=t[d*6+f];t[d*6+f]=t[p*6+f],t[p*6+f]=g}o++,a--}else return o}}let Qx,Oc,Sf,jx;const UD=Math.pow(2,32);function Cf(n){return"count"in n?1:1+Cf(n.left)+Cf(n.right)}function ND(n,e,t){return Qx=new Float32Array(t),Oc=new Uint32Array(t),Sf=new Uint16Array(t),jx=new Uint8Array(t),Mf(n,e)}function Mf(n,e){const t=n/4,i=n/2,s="count"in e,r=e.boundingData;for(let o=0;o<6;o++)Qx[t+o]=r[o];if(s)return e.buffer?(jx.set(new Uint8Array(e.buffer),n),n+e.buffer.byteLength):(Oc[t+6]=e.offset,Sf[i+14]=e.count,Sf[i+15]=Fx,n+li);{const{left:o,right:a,splitAxis:l}=e,c=n+li;let h=Mf(c,o);const u=n/li,d=h/li-u;if(d>UD)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Oc[t+6]=d,Oc[t+7]=l,Mf(h,a)}}function zD(n,e,t){const s=(n.index?n.index.count:n.attributes.position.count)/3>2**16,r=t.reduce((h,u)=>h+u.count,0),o=s?4:2,a=e?new SharedArrayBuffer(r*o):new ArrayBuffer(r*o),l=s?new Uint32Array(a):new Uint16Array(a);let c=0;for(let h=0;h<t.length;h++){const{offset:u,count:f}=t[h];for(let d=0;d<f;d++)l[c+d]=u+d;c+=f}return l}function GD(n,e,t,i,s){const{maxDepth:r,verbose:o,maxLeafTris:a,strategy:l,onProgress:c,indirect:h}=s,u=n._indirectBuffer,f=n.geometry,d=f.index?f.index.array:null,p=h?OD:FD,g=fr(f),m=new Float32Array(6);let A=!1;const x=new wf;return _f(e,t,i,x.boundingData,m),y(x,t,i,m),x;function b(_){c&&c(_/g)}function y(_,E,I,B=null,C=0){if(!A&&C>=r&&(A=!0,o&&(console.warn(`MeshBVH: Max depth of ${r} reached when generating BVH. Consider increasing maxDepth.`),console.warn(f))),I<=a||C>=r)return b(E+I),_.offset=E,_.count=I,_;const S=RD(_.boundingData,B,e,E,I,l);if(S.axis===-1)return b(E+I),_.offset=E,_.count=I,_;const P=p(u,d,e,E,I,S);if(P===E||P===E+I)b(E+I),_.offset=E,_.count=I;else{_.splitAxis=S.axis;const T=new wf,R=E,M=P-E;_.left=T,_f(e,R,M,T.boundingData,m),y(T,R,M,m,C+1);const F=new wf,N=P,j=I-M;_.right=F,_f(e,N,j,F.boundingData,m),y(F,N,j,m,C+1)}return _}}function VD(n,e){const t=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=n.geometry;let s,r;if(e.indirect){const o=Ux(i,e.range),a=zD(i,e.useSharedArrayBuffer,o);n._indirectBuffer=a,s=Nx(i,0,a.length,a),r=[{offset:0,count:a.length}]}else{PD(i,e);const o=Ox(i,e.range)[0];s=Nx(i,o.offset,o.count),r=Ux(i,e.range)}n._roots=r.map(o=>{const a=GD(n,s,o.offset,o.count,e),l=Cf(a),c=new t(li*l);return ND(0,a,c),c})}class Jn{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,s=-1/0;for(let r=0,o=e.length;r<o;r++){const l=e[r][t];i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}setFromPoints(e,t){let i=1/0,s=-1/0;for(let r=0,o=t.length;r<o;r++){const a=t[r],l=e.dot(a);i=l<i?l:i,s=l>s?l:s}this.min=i,this.max=s}isSeparated(e){return this.min>e.max||e.min>this.max}}Jn.prototype.setFromBox=(function(){const n=new v.Vector3;return function(t,i){const s=i.min,r=i.max;let o=1/0,a=-1/0;for(let l=0;l<=1;l++)for(let c=0;c<=1;c++)for(let h=0;h<=1;h++){n.x=s.x*l+r.x*(1-l),n.y=s.y*c+r.y*(1-c),n.z=s.z*h+r.z*(1-h);const u=t.dot(n);o=Math.min(u,o),a=Math.max(u,a)}this.min=o,this.max=a}})();const QD=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Vector3;return function(s,r,o){const a=s.start,l=n,c=r.start,h=e;t.subVectors(a,c),n.subVectors(s.end,s.start),e.subVectors(r.end,r.start);const u=t.dot(h),f=h.dot(l),d=h.dot(h),p=t.dot(l),m=l.dot(l)*d-f*f;let A,x;m!==0?A=(u*f-p*d)/m:A=0,x=(u+A*f)/d,o.x=A,o.y=x}})(),Ef=(function(){const n=new v.Vector2,e=new v.Vector3,t=new v.Vector3;return function(s,r,o,a){QD(s,r,n);let l=n.x,c=n.y;if(l>=0&&l<=1&&c>=0&&c<=1){s.at(l,o),r.at(c,a);return}else if(l>=0&&l<=1){c<0?r.at(0,a):r.at(1,a),s.closestPointToPoint(a,!0,o);return}else if(c>=0&&c<=1){l<0?s.at(0,o):s.at(1,o),r.closestPointToPoint(o,!0,a);return}else{let h;l<0?h=s.start:h=s.end;let u;c<0?u=r.start:u=r.end;const f=e,d=t;if(s.closestPointToPoint(u,!0,e),r.closestPointToPoint(h,!0,t),f.distanceToSquared(u)<=d.distanceToSquared(h)){o.copy(f),a.copy(u);return}else{o.copy(h),a.copy(d);return}}}})(),jD=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Plane,i=new v.Line3;return function(r,o){const{radius:a,center:l}=r,{a:c,b:h,c:u}=o;if(i.start=c,i.end=h,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a||(i.start=c,i.end=u,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a)||(i.start=h,i.end=u,i.closestPointToPoint(l,!0,n).distanceTo(l)<=a))return!0;const g=o.getPlane(t);if(Math.abs(g.distanceToPoint(l))<=a){const A=g.projectPoint(l,e);if(o.containsPoint(A))return!0}return!1}})(),WD=["x","y","z"],Zn=1e-15,Wx=Zn*Zn;function Gi(n){return Math.abs(n)<Zn}class Vi extends v.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new v.Vector3),this.satBounds=new Array(4).fill().map(()=>new Jn),this.points=[this.a,this.b,this.c],this.plane=new v.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new v.Line3,this.needsUpdate=!0}intersectsSphere(e){return jD(e,this)}update(){const e=this.a,t=this.b,i=this.c,s=this.points,r=this.satAxes,o=this.satBounds,a=r[0],l=o[0];this.getNormal(a),l.setFromPoints(a,s);const c=r[1],h=o[1];c.subVectors(e,t),h.setFromPoints(c,s);const u=r[2],f=o[2];u.subVectors(t,i),f.setFromPoints(u,s);const d=r[3],p=o[3];d.subVectors(i,e),p.setFromPoints(d,s);const g=c.length(),m=u.length(),A=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,g<Zn?m<Zn||A<Zn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):m<Zn?A<Zn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):A<Zn&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(a,e),this.needsUpdate=!1}}Vi.prototype.closestPointToSegment=(function(){const n=new v.Vector3,e=new v.Vector3,t=new v.Line3;return function(s,r=null,o=null){const{start:a,end:l}=s,c=this.points;let h,u=1/0;for(let f=0;f<3;f++){const d=(f+1)%3;t.start.copy(c[f]),t.end.copy(c[d]),Ef(t,s,n,e),h=n.distanceToSquared(e),h<u&&(u=h,r&&r.copy(n),o&&o.copy(e))}return this.closestPointToPoint(a,n),h=a.distanceToSquared(n),h<u&&(u=h,r&&r.copy(n),o&&o.copy(a)),this.closestPointToPoint(l,n),h=l.distanceToSquared(n),h<u&&(u=h,r&&r.copy(n),o&&o.copy(l)),Math.sqrt(u)}})(),Vi.prototype.intersectsTriangle=(function(){const n=new Vi,e=new Jn,t=new Jn,i=new v.Vector3,s=new v.Vector3,r=new v.Vector3,o=new v.Vector3,a=new v.Line3,l=new v.Line3,c=new v.Vector3,h=new v.Vector2,u=new v.Vector2;function f(b,y,_,E){const I=i;!b.isDegenerateIntoPoint&&!b.isDegenerateIntoSegment?I.copy(b.plane.normal):I.copy(y.plane.normal);const B=b.satBounds,C=b.satAxes;for(let T=1;T<4;T++){const R=B[T],M=C[T];if(e.setFromPoints(M,y.points),R.isSeparated(e)||(o.copy(I).cross(M),e.setFromPoints(o,b.points),t.setFromPoints(o,y.points),e.isSeparated(t)))return!1}const S=y.satBounds,P=y.satAxes;for(let T=1;T<4;T++){const R=S[T],M=P[T];if(e.setFromPoints(M,b.points),R.isSeparated(e)||(o.crossVectors(I,M),e.setFromPoints(o,b.points),t.setFromPoints(o,y.points),e.isSeparated(t)))return!1}return _&&(E||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),_.start.set(0,0,0),_.end.set(0,0,0)),!0}function d(b,y,_,E,I,B,C,S,P,T,R){let M=C/(C-S);T.x=E+(I-E)*M,R.start.subVectors(y,b).multiplyScalar(M).add(b),M=C/(C-P),T.y=E+(B-E)*M,R.end.subVectors(_,b).multiplyScalar(M).add(b)}function p(b,y,_,E,I,B,C,S,P,T,R){if(I>0)d(b.c,b.a,b.b,E,y,_,P,C,S,T,R);else if(B>0)d(b.b,b.a,b.c,_,y,E,S,C,P,T,R);else if(S*P>0||C!=0)d(b.a,b.b,b.c,y,_,E,C,S,P,T,R);else if(S!=0)d(b.b,b.a,b.c,_,y,E,S,C,P,T,R);else if(P!=0)d(b.c,b.a,b.b,E,y,_,P,C,S,T,R);else return!0;return!1}function g(b,y,_,E){const I=y.degenerateSegment,B=b.plane.distanceToPoint(I.start),C=b.plane.distanceToPoint(I.end);return Gi(B)?Gi(C)?f(b,y,_,E):(_&&(_.start.copy(I.start),_.end.copy(I.start)),b.containsPoint(I.start)):Gi(C)?(_&&(_.start.copy(I.end),_.end.copy(I.end)),b.containsPoint(I.end)):b.plane.intersectLine(I,i)!=null?(_&&(_.start.copy(i),_.end.copy(i)),b.containsPoint(i)):!1}function m(b,y,_){const E=y.a;return Gi(b.plane.distanceToPoint(E))&&b.containsPoint(E)?(_&&(_.start.copy(E),_.end.copy(E)),!0):!1}function A(b,y,_){const E=b.degenerateSegment,I=y.a;return E.closestPointToPoint(I,!0,i),I.distanceToSquared(i)<Wx?(_&&(_.start.copy(I),_.end.copy(I)),!0):!1}function x(b,y,_,E){if(b.isDegenerateIntoSegment)if(y.isDegenerateIntoSegment){const I=b.degenerateSegment,B=y.degenerateSegment,C=s,S=r;I.delta(C),B.delta(S);const P=i.subVectors(B.start,I.start),T=C.x*S.y-C.y*S.x;if(Gi(T))return!1;const R=(P.x*S.y-P.y*S.x)/T,M=-(C.x*P.y-C.y*P.x)/T;if(R<0||R>1||M<0||M>1)return!1;const F=I.start.z+C.z*R,N=B.start.z+S.z*M;return Gi(F-N)?(_&&(_.start.copy(I.start).addScaledVector(C,R),_.end.copy(I.start).addScaledVector(C,R)),!0):!1}else return y.isDegenerateIntoPoint?A(b,y,_):g(y,b,_,E);else{if(b.isDegenerateIntoPoint)return y.isDegenerateIntoPoint?y.a.distanceToSquared(b.a)<Wx?(_&&(_.start.copy(b.a),_.end.copy(b.a)),!0):!1:y.isDegenerateIntoSegment?A(y,b,_):m(y,b,_);if(y.isDegenerateIntoPoint)return m(b,y,_);if(y.isDegenerateIntoSegment)return g(b,y,_,E)}}return function(y,_=null,E=!1){this.needsUpdate&&this.update(),y.isExtendedTriangle?y.needsUpdate&&y.update():(n.copy(y),n.update(),y=n);const I=x(this,y,_,E);if(I!==void 0)return I;const B=this.plane,C=y.plane;let S=C.distanceToPoint(this.a),P=C.distanceToPoint(this.b),T=C.distanceToPoint(this.c);Gi(S)&&(S=0),Gi(P)&&(P=0),Gi(T)&&(T=0);const R=S*P,M=S*T;if(R>0&&M>0)return!1;let F=B.distanceToPoint(y.a),N=B.distanceToPoint(y.b),j=B.distanceToPoint(y.c);Gi(F)&&(F=0),Gi(N)&&(N=0),Gi(j)&&(j=0);const q=F*N,U=F*j;if(q>0&&U>0)return!1;s.copy(B.normal),r.copy(C.normal);const H=s.cross(r);let z=0,G=Math.abs(H.x);const re=Math.abs(H.y);re>G&&(G=re,z=1),Math.abs(H.z)>G&&(z=2);const ue=WD[z],se=this.a[ue],fe=this.b[ue],Ae=this.c[ue],_e=y.a[ue],Ce=y.b[ue],Oe=y.c[ue];if(p(this,se,fe,Ae,R,M,S,P,T,h,a))return f(this,y,_,E);if(p(y,_e,Ce,Oe,q,U,F,N,j,u,l))return f(this,y,_,E);if(h.y<h.x){const Ke=h.y;h.y=h.x,h.x=Ke,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(u.y<u.x){const Ke=u.y;u.y=u.x,u.x=Ke,c.copy(l.start),l.start.copy(l.end),l.end.copy(c)}return h.y<u.x||u.y<h.x?!1:(_&&(u.x>h.x?_.start.copy(l.start):_.start.copy(a.start),u.y<h.y?_.end.copy(l.end):_.end.copy(a.end)),!0)}})(),Vi.prototype.distanceToPoint=(function(){const n=new v.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})(),Vi.prototype.distanceToTriangle=(function(){const n=new v.Vector3,e=new v.Vector3,t=["a","b","c"],i=new v.Line3,s=new v.Line3;return function(o,a=null,l=null){const c=a||l?i:null;if(this.intersectsTriangle(o,c))return(a||l)&&(a&&c.getCenter(a),l&&c.getCenter(l)),0;let h=1/0;for(let u=0;u<3;u++){let f;const d=t[u],p=o[d];this.closestPointToPoint(p,n),f=p.distanceToSquared(n),f<h&&(h=f,a&&a.copy(n),l&&l.copy(p));const g=this[d];o.closestPointToPoint(g,n),f=g.distanceToSquared(n),f<h&&(h=f,a&&a.copy(g),l&&l.copy(n))}for(let u=0;u<3;u++){const f=t[u],d=t[(u+1)%3];i.set(this[f],this[d]);for(let p=0;p<3;p++){const g=t[p],m=t[(p+1)%3];s.set(o[g],o[m]),Ef(i,s,n,e);const A=n.distanceToSquared(e);A<h&&(h=A,a&&a.copy(n),l&&l.copy(e))}}return Math.sqrt(h)}})();class ci{constructor(e,t,i){this.isOrientedBox=!0,this.min=new v.Vector3,this.max=new v.Vector3,this.matrix=new v.Matrix4,this.invMatrix=new v.Matrix4,this.points=new Array(8).fill().map(()=>new v.Vector3),this.satAxes=new Array(3).fill().map(()=>new v.Vector3),this.satBounds=new Array(3).fill().map(()=>new Jn),this.alignedSatBounds=new Array(3).fill().map(()=>new Jn),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}ci.prototype.update=(function(){return function(){const e=this.matrix,t=this.min,i=this.max,s=this.points;for(let c=0;c<=1;c++)for(let h=0;h<=1;h++)for(let u=0;u<=1;u++){const f=1*c|2*h|4*u,d=s[f];d.x=c?i.x:t.x,d.y=h?i.y:t.y,d.z=u?i.z:t.z,d.applyMatrix4(e)}const r=this.satBounds,o=this.satAxes,a=s[0];for(let c=0;c<3;c++){const h=o[c],u=r[c],f=1<<c,d=s[f];h.subVectors(a,d),u.setFromPoints(h,s)}const l=this.alignedSatBounds;l[0].setFromPointsField(s,"x"),l[1].setFromPointsField(s,"y"),l[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}})(),ci.prototype.intersectsBox=(function(){const n=new Jn;return function(t){this.needsUpdate&&this.update();const i=t.min,s=t.max,r=this.satBounds,o=this.satAxes,a=this.alignedSatBounds;if(n.min=i.x,n.max=s.x,a[0].isSeparated(n)||(n.min=i.y,n.max=s.y,a[1].isSeparated(n))||(n.min=i.z,n.max=s.z,a[2].isSeparated(n)))return!1;for(let l=0;l<3;l++){const c=o[l],h=r[l];if(n.setFromBox(c,t),h.isSeparated(n))return!1}return!0}})(),ci.prototype.intersectsTriangle=(function(){const n=new Vi,e=new Array(3),t=new Jn,i=new Jn,s=new v.Vector3;return function(o){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(n.copy(o),n.update(),o=n);const a=this.satBounds,l=this.satAxes;e[0]=o.a,e[1]=o.b,e[2]=o.c;for(let f=0;f<3;f++){const d=a[f],p=l[f];if(t.setFromPoints(p,e),d.isSeparated(t))return!1}const c=o.satBounds,h=o.satAxes,u=this.points;for(let f=0;f<3;f++){const d=c[f],p=h[f];if(t.setFromPoints(p,u),d.isSeparated(t))return!1}for(let f=0;f<3;f++){const d=l[f];for(let p=0;p<4;p++){const g=h[p];if(s.crossVectors(d,g),t.setFromPoints(s,e),i.setFromPoints(s,u),t.isSeparated(i))return!1}}return!0}})(),ci.prototype.closestPointToPoint=(function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}})(),ci.prototype.distanceToPoint=(function(){const n=new v.Vector3;return function(t){return this.closestPointToPoint(t,n),t.distanceTo(n)}})(),ci.prototype.distanceToBox=(function(){const n=["x","y","z"],e=new Array(12).fill().map(()=>new v.Line3),t=new Array(12).fill().map(()=>new v.Line3),i=new v.Vector3,s=new v.Vector3;return function(o,a=0,l=null,c=null){if(this.needsUpdate&&this.update(),this.intersectsBox(o))return(l||c)&&(o.getCenter(s),this.closestPointToPoint(s,i),o.closestPointToPoint(i,s),l&&l.copy(i),c&&c.copy(s)),0;const h=a*a,u=o.min,f=o.max,d=this.points;let p=1/0;for(let m=0;m<8;m++){const A=d[m];s.copy(A).clamp(u,f);const x=A.distanceToSquared(s);if(x<p&&(p=x,l&&l.copy(A),c&&c.copy(s),x<h))return Math.sqrt(x)}let g=0;for(let m=0;m<3;m++)for(let A=0;A<=1;A++)for(let x=0;x<=1;x++){const b=(m+1)%3,y=(m+2)%3,_=A<<b|x<<y,E=1<<m|A<<b|x<<y,I=d[_],B=d[E];e[g].set(I,B);const S=n[m],P=n[b],T=n[y],R=t[g],M=R.start,F=R.end;M[S]=u[S],M[P]=A?u[P]:f[P],M[T]=x?u[T]:f[P],F[S]=f[S],F[P]=A?u[P]:f[P],F[T]=x?u[T]:f[P],g++}for(let m=0;m<=1;m++)for(let A=0;A<=1;A++)for(let x=0;x<=1;x++){s.x=m?f.x:u.x,s.y=A?f.y:u.y,s.z=x?f.z:u.z,this.closestPointToPoint(s,i);const b=s.distanceToSquared(i);if(b<p&&(p=b,l&&l.copy(i),c&&c.copy(s),b<h))return Math.sqrt(b)}for(let m=0;m<12;m++){const A=e[m];for(let x=0;x<12;x++){const b=t[x];Ef(A,b,i,s);const y=i.distanceToSquared(s);if(y<p&&(p=y,l&&l.copy(i),c&&c.copy(s),y<h))return Math.sqrt(y)}}return Math.sqrt(p)}})();class If{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return e.length===0?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class HD extends If{constructor(){super(()=>new Vi)}}const Qi=new HD;function Ht(n,e){return e[n+15]===Fx}function Ii(n,e){return e[n+6]}function ji(n,e){return e[n+14]}function Xt(n){return n+Wt}function Yt(n,e){const t=e[n+6];return n+t*Wt}function Tf(n,e){return e[n+7]}function FF(n){return n}class qD{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,e.length!==0&&this.setBuffer(e.pop())}}}const _t=new qD;let Es,bo;const yo=[],Uc=new If(()=>new v.Box3);function XD(n,e,t,i,s,r){Es=Uc.getPrimitive(),bo=Uc.getPrimitive(),yo.push(Es,bo),_t.setBuffer(n._roots[e]);const o=Df(0,n.geometry,t,i,s,r);_t.clearBuffer(),Uc.releasePrimitive(Es),Uc.releasePrimitive(bo),yo.pop(),yo.pop();const a=yo.length;return a>0&&(bo=yo[a-1],Es=yo[a-2]),o}function Df(n,e,t,i,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=_t;let h=n*2;if(Ht(h,l)){const f=Ii(n,c),d=ji(h,l);return It(n,a,Es),i(f,d,!1,o,r+n/Wt,Es)}else{let S=function(T){const{uint16Array:R,uint32Array:M}=_t;let F=T*2;for(;!Ht(F,R);)T=Xt(T),F=T*2;return Ii(T,M)},P=function(T){const{uint16Array:R,uint32Array:M}=_t;let F=T*2;for(;!Ht(F,R);)T=Yt(T,M),F=T*2;return Ii(T,M)+ji(F,R)};const f=Xt(n),d=Yt(n,c);let p=f,g=d,m,A,x,b;if(s&&(x=Es,b=bo,It(p,a,x),It(g,a,b),m=s(x),A=s(b),A<m)){p=d,g=f;const T=m;m=A,A=T,x=b}x||(x=Es,It(p,a,x));const y=Ht(p*2,l),_=t(x,y,m,o+1,r+p/Wt);let E;if(_===Rx){const T=S(p),M=P(p)-T;E=i(T,M,!0,o+1,r+p/Wt,x)}else E=_&&Df(p,e,t,i,s,r,o+1);if(E)return!0;b=bo,It(g,a,b);const I=Ht(g*2,l),B=t(b,I,A,o+1,r+g/Wt);let C;if(B===Rx){const T=S(g),M=P(g)-T;C=i(T,M,!0,o+1,r+g/Wt,b)}else C=B&&Df(g,e,t,i,s,r,o+1);return!!C}}const Ea=new v.Vector3,Bf=new v.Vector3;function YD(n,e,t={},i=0,s=1/0){const r=i*i,o=s*s;let a=1/0,l=null;if(n.shapecast({boundsTraverseOrder:h=>(Ea.copy(e).clamp(h.min,h.max),Ea.distanceToSquared(e)),intersectsBounds:(h,u,f)=>f<a&&f<o,intersectsTriangle:(h,u)=>{h.closestPointToPoint(e,Ea);const f=e.distanceToSquared(Ea);return f<a&&(Bf.copy(Ea),a=f,l=u),f<r}}),a===1/0)return null;const c=Math.sqrt(a);return t.point?t.point.copy(Bf):t.point=Bf.clone(),t.distance=c,t.faceIndex=l,t}const Nc=parseInt(v.REVISION)>=169,KD=parseInt(v.REVISION)<=161,pr=new v.Vector3,gr=new v.Vector3,mr=new v.Vector3,zc=new v.Vector2,Gc=new v.Vector2,Vc=new v.Vector2,Hx=new v.Vector3,qx=new v.Vector3,Xx=new v.Vector3,Ia=new v.Vector3;function $D(n,e,t,i,s,r,o,a){let l;if(r===v.BackSide?l=n.intersectTriangle(i,t,e,!0,s):l=n.intersectTriangle(e,t,i,r!==v.DoubleSide,s),l===null)return null;const c=n.origin.distanceTo(s);return c<o||c>a?null:{distance:c,point:s.clone()}}function Yx(n,e,t,i,s,r,o,a,l,c,h){pr.fromBufferAttribute(e,r),gr.fromBufferAttribute(e,o),mr.fromBufferAttribute(e,a);const u=$D(n,pr,gr,mr,Ia,l,c,h);if(u){if(i){zc.fromBufferAttribute(i,r),Gc.fromBufferAttribute(i,o),Vc.fromBufferAttribute(i,a),u.uv=new v.Vector2;const d=v.Triangle.getInterpolation(Ia,pr,gr,mr,zc,Gc,Vc,u.uv);Nc||(u.uv=d)}if(s){zc.fromBufferAttribute(s,r),Gc.fromBufferAttribute(s,o),Vc.fromBufferAttribute(s,a),u.uv1=new v.Vector2;const d=v.Triangle.getInterpolation(Ia,pr,gr,mr,zc,Gc,Vc,u.uv1);Nc||(u.uv1=d),KD&&(u.uv2=u.uv1)}if(t){Hx.fromBufferAttribute(t,r),qx.fromBufferAttribute(t,o),Xx.fromBufferAttribute(t,a),u.normal=new v.Vector3;const d=v.Triangle.getInterpolation(Ia,pr,gr,mr,Hx,qx,Xx,u.normal);u.normal.dot(n.direction)>0&&u.normal.multiplyScalar(-1),Nc||(u.normal=d)}const f={a:r,b:o,c:a,normal:new v.Vector3,materialIndex:0};if(v.Triangle.getNormal(pr,gr,mr,f.normal),u.face=f,u.faceIndex=r,Nc){const d=new v.Vector3;v.Triangle.getBarycoord(Ia,pr,gr,mr,d),u.barycoord=d}}return u}function Kx(n){return n&&n.isMaterial?n.side:n}function Qc(n,e,t,i,s,r,o){const a=i*3;let l=a+0,c=a+1,h=a+2;const{index:u,groups:f}=n;n.index&&(l=u.getX(l),c=u.getX(c),h=u.getX(h));const{position:d,normal:p,uv:g,uv1:m}=n.attributes;if(Array.isArray(e)){const A=i*3;for(let x=0,b=f.length;x<b;x++){const{start:y,count:_,materialIndex:E}=f[x];if(A>=y&&A<y+_){const I=Kx(e[E]),B=Yx(t,d,p,g,m,l,c,h,I,r,o);if(B)if(B.faceIndex=i,B.face.materialIndex=E,s)s.push(B);else return B}}}else{const A=Kx(e),x=Yx(t,d,p,g,m,l,c,h,A,r,o);if(x)if(x.faceIndex=i,x.face.materialIndex=0,s)s.push(x);else return x}return null}function Ut(n,e,t,i){const s=n.a,r=n.b,o=n.c;let a=e,l=e+1,c=e+2;t&&(a=t.getX(a),l=t.getX(l),c=t.getX(c)),s.x=i.getX(a),s.y=i.getY(a),s.z=i.getZ(a),r.x=i.getX(l),r.y=i.getY(l),r.z=i.getZ(l),o.x=i.getX(c),o.y=i.getY(c),o.z=i.getZ(c)}function JD(n,e,t,i,s,r,o,a){const{geometry:l,_indirectBuffer:c}=n;for(let h=i,u=i+s;h<u;h++)Qc(l,e,t,h,r,o,a)}function ZD(n,e,t,i,s,r,o){const{geometry:a,_indirectBuffer:l}=n;let c=1/0,h=null;for(let u=i,f=i+s;u<f;u++){let d;d=Qc(a,e,t,u,null,r,o),d&&d.distance<c&&(h=d,c=d.distance)}return h}function eB(n,e,t,i,s,r,o){const{geometry:a}=t,{index:l}=a,c=a.attributes.position;for(let h=n,u=e+n;h<u;h++){let f;if(f=h,Ut(o,f*3,l,c),o.needsUpdate=!0,i(o,f,s,r))return!0}return!1}function tB(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,l,c=0;const h=n._roots;for(let f=0,d=h.length;f<d;f++)r=h[f],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(f,d,p=!1){const g=f*2;if(Ht(g,a)){const m=o[f+6],A=a[g+14];let x=1/0,b=1/0,y=1/0,_=-1/0,E=-1/0,I=-1/0;for(let B=3*m,C=3*(m+A);B<C;B++){let S=i[B];const P=s.getX(S),T=s.getY(S),R=s.getZ(S);P<x&&(x=P),P>_&&(_=P),T<b&&(b=T),T>E&&(E=T),R<y&&(y=R),R>I&&(I=R)}return l[f+0]!==x||l[f+1]!==b||l[f+2]!==y||l[f+3]!==_||l[f+4]!==E||l[f+5]!==I?(l[f+0]=x,l[f+1]=b,l[f+2]=y,l[f+3]=_,l[f+4]=E,l[f+5]=I,!0):!1}else{const m=Xt(f),A=Yt(f,o);let x=p,b=!1,y=!1;if(e){if(!x){const S=m/Wt+d/li,P=A/Wt+d/li;b=e.has(S),y=e.has(P),x=!b&&!y}}else b=!0,y=!0;const _=x||b,E=x||y;let I=!1;_&&(I=u(m,d,x));let B=!1;E&&(B=u(A,d,x));const C=I||B;if(C)for(let S=0;S<3;S++){const P=m+S,T=A+S,R=l[P],M=l[P+3],F=l[T],N=l[T+3];l[f+S]=R<F?R:F,l[f+S+3]=M>N?M:N}return C}}}function Is(n,e,t,i,s){let r,o,a,l,c,h;const u=1/t.direction.x,f=1/t.direction.y,d=1/t.direction.z,p=t.origin.x,g=t.origin.y,m=t.origin.z;let A=e[n],x=e[n+3],b=e[n+1],y=e[n+3+1],_=e[n+2],E=e[n+3+2];return u>=0?(r=(A-p)*u,o=(x-p)*u):(r=(x-p)*u,o=(A-p)*u),f>=0?(a=(b-g)*f,l=(y-g)*f):(a=(y-g)*f,l=(b-g)*f),r>l||a>o||((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),d>=0?(c=(_-m)*d,h=(E-m)*d):(c=(E-m)*d,h=(_-m)*d),r>h||c>o)?!1:((c>r||r!==r)&&(r=c),(h<o||o!==o)&&(o=h),r<=s&&o>=i)}function iB(n,e,t,i,s,r,o,a){const{geometry:l,_indirectBuffer:c}=n;for(let h=i,u=i+s;h<u;h++){let f=c?c[h]:h;Qc(l,e,t,f,r,o,a)}}function nB(n,e,t,i,s,r,o){const{geometry:a,_indirectBuffer:l}=n;let c=1/0,h=null;for(let u=i,f=i+s;u<f;u++){let d;d=Qc(a,e,t,l?l[u]:u,null,r,o),d&&d.distance<c&&(h=d,c=d.distance)}return h}function sB(n,e,t,i,s,r,o){const{geometry:a}=t,{index:l}=a,c=a.attributes.position;for(let h=n,u=e+n;h<u;h++){let f;if(f=t.resolveTriangleIndex(h),Ut(o,f*3,l,c),o.needsUpdate=!0,i(o,f,s,r))return!0}return!1}function rB(n,e,t,i,s,r,o){_t.setBuffer(n._roots[e]),Pf(0,n,t,i,s,r,o),_t.clearBuffer()}function Pf(n,e,t,i,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=_t,h=n*2;if(Ht(h,l)){const f=Ii(n,c),d=ji(h,l);JD(e,t,i,f,d,s,r,o)}else{const f=Xt(n);Is(f,a,i,r,o)&&Pf(f,e,t,i,s,r,o);const d=Yt(n,c);Is(d,a,i,r,o)&&Pf(d,e,t,i,s,r,o)}}const oB=["x","y","z"];function aB(n,e,t,i,s,r){_t.setBuffer(n._roots[e]);const o=Lf(0,n,t,i,s,r);return _t.clearBuffer(),o}function Lf(n,e,t,i,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=_t;let c=n*2;if(Ht(c,a)){const u=Ii(n,l),f=ji(c,a);return ZD(e,t,i,u,f,s,r)}else{const u=Tf(n,l),f=oB[u],p=i.direction[f]>=0;let g,m;p?(g=Xt(n),m=Yt(n,l)):(g=Yt(n,l),m=Xt(n));const x=Is(g,o,i,s,r)?Lf(g,e,t,i,s,r):null;if(x){const _=x.point[f];if(p?_<=o[m+u]:_>=o[m+u+3])return x}const y=Is(m,o,i,s,r)?Lf(m,e,t,i,s,r):null;return x&&y?x.distance<=y.distance?x:y:x||y||null}}const jc=new v.Box3,vo=new Vi,_o=new Vi,Ta=new v.Matrix4,$x=new ci,Wc=new ci;function lB(n,e,t,i){_t.setBuffer(n._roots[e]);const s=Rf(0,n,t,i);return _t.clearBuffer(),s}function Rf(n,e,t,i,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_t;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),$x.set(t.boundingBox.min,t.boundingBox.max,i),s=$x),Ht(l,o)){const h=e.geometry,u=h.index,f=h.attributes.position,d=t.index,p=t.attributes.position,g=Ii(n,a),m=ji(l,o);if(Ta.copy(i).invert(),t.boundsTree)return It(n,r,Wc),Wc.matrix.copy(Ta),Wc.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>Wc.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(i),x.b.applyMatrix4(i),x.c.applyMatrix4(i),x.needsUpdate=!0;for(let b=g*3,y=(m+g)*3;b<y;b+=3)if(Ut(_o,b,u,f),_o.needsUpdate=!0,x.intersectsTriangle(_o))return!0;return!1}});{const A=fr(t);for(let x=g*3,b=(m+g)*3;x<b;x+=3){Ut(vo,x,u,f),vo.a.applyMatrix4(Ta),vo.b.applyMatrix4(Ta),vo.c.applyMatrix4(Ta),vo.needsUpdate=!0;for(let y=0,_=A*3;y<_;y+=3)if(Ut(_o,y,d,p),_o.needsUpdate=!0,vo.intersectsTriangle(_o))return!0}}}else{const h=Xt(n),u=Yt(n,a);return It(h,r,jc),!!(s.intersectsBox(jc)&&Rf(h,e,t,i,s)||(It(u,r,jc),s.intersectsBox(jc)&&Rf(u,e,t,i,s)))}}const Hc=new v.Matrix4,kf=new ci,Da=new ci,cB=new v.Vector3,hB=new v.Vector3,uB=new v.Vector3,dB=new v.Vector3;function fB(n,e,t,i={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),kf.set(e.boundingBox.min,e.boundingBox.max,t),kf.needsUpdate=!0;const a=n.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,f=Qi.getPrimitive(),d=Qi.getPrimitive();let p=cB,g=hB,m=null,A=null;s&&(m=uB,A=dB);let x=1/0,b=null,y=null;return Hc.copy(t).invert(),Da.matrix.copy(Hc),n.shapecast({boundsTraverseOrder:_=>kf.distanceToBox(_),intersectsBounds:(_,E,I)=>I<x&&I<o?(E&&(Da.min.copy(_.min),Da.max.copy(_.max),Da.needsUpdate=!0),!0):!1,intersectsRange:(_,E)=>{if(e.boundsTree)return e.boundsTree.shapecast({boundsTraverseOrder:B=>Da.distanceToBox(B),intersectsBounds:(B,C,S)=>S<x&&S<o,intersectsRange:(B,C)=>{for(let S=B,P=B+C;S<P;S++){Ut(d,3*S,u,h),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let T=_,R=_+E;T<R;T++){Ut(f,3*T,c,l),f.needsUpdate=!0;const M=f.distanceToTriangle(d,p,m);if(M<x&&(g.copy(p),A&&A.copy(m),x=M,b=T,y=S),M<r)return!0}}}});{const I=fr(e);for(let B=0,C=I;B<C;B++){Ut(d,3*B,u,h),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let S=_,P=_+E;S<P;S++){Ut(f,3*S,c,l),f.needsUpdate=!0;const T=f.distanceToTriangle(d,p,m);if(T<x&&(g.copy(p),A&&A.copy(m),x=T,b=S,y=B),T<r)return!0}}}}}),Qi.releasePrimitive(f),Qi.releasePrimitive(d),x===1/0?null:(i.point?i.point.copy(g):i.point=g.clone(),i.distance=x,i.faceIndex=b,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Hc),g.applyMatrix4(Hc),s.distance=g.sub(s.point).length(),s.faceIndex=y),i)}function pB(n,e=null){e&&Array.isArray(e)&&(e=new Set(e));const t=n.geometry,i=t.index?t.index.array:null,s=t.attributes.position;let r,o,a,l,c=0;const h=n._roots;for(let f=0,d=h.length;f<d;f++)r=h[f],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(f,d,p=!1){const g=f*2;if(Ht(g,a)){const m=o[f+6],A=a[g+14];let x=1/0,b=1/0,y=1/0,_=-1/0,E=-1/0,I=-1/0;for(let B=m,C=m+A;B<C;B++){const S=3*n.resolveTriangleIndex(B);for(let P=0;P<3;P++){let T=S+P;T=i?i[T]:T;const R=s.getX(T),M=s.getY(T),F=s.getZ(T);R<x&&(x=R),R>_&&(_=R),M<b&&(b=M),M>E&&(E=M),F<y&&(y=F),F>I&&(I=F)}}return l[f+0]!==x||l[f+1]!==b||l[f+2]!==y||l[f+3]!==_||l[f+4]!==E||l[f+5]!==I?(l[f+0]=x,l[f+1]=b,l[f+2]=y,l[f+3]=_,l[f+4]=E,l[f+5]=I,!0):!1}else{const m=Xt(f),A=Yt(f,o);let x=p,b=!1,y=!1;if(e){if(!x){const S=m/Wt+d/li,P=A/Wt+d/li;b=e.has(S),y=e.has(P),x=!b&&!y}}else b=!0,y=!0;const _=x||b,E=x||y;let I=!1;_&&(I=u(m,d,x));let B=!1;E&&(B=u(A,d,x));const C=I||B;if(C)for(let S=0;S<3;S++){const P=m+S,T=A+S,R=l[P],M=l[P+3],F=l[T],N=l[T+3];l[f+S]=R<F?R:F,l[f+S+3]=M>N?M:N}return C}}}function gB(n,e,t,i,s,r,o){_t.setBuffer(n._roots[e]),Ff(0,n,t,i,s,r,o),_t.clearBuffer()}function Ff(n,e,t,i,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=_t,h=n*2;if(Ht(h,l)){const f=Ii(n,c),d=ji(h,l);iB(e,t,i,f,d,s,r,o)}else{const f=Xt(n);Is(f,a,i,r,o)&&Ff(f,e,t,i,s,r,o);const d=Yt(n,c);Is(d,a,i,r,o)&&Ff(d,e,t,i,s,r,o)}}const mB=["x","y","z"];function AB(n,e,t,i,s,r){_t.setBuffer(n._roots[e]);const o=Of(0,n,t,i,s,r);return _t.clearBuffer(),o}function Of(n,e,t,i,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=_t;let c=n*2;if(Ht(c,a)){const u=Ii(n,l),f=ji(c,a);return nB(e,t,i,u,f,s,r)}else{const u=Tf(n,l),f=mB[u],p=i.direction[f]>=0;let g,m;p?(g=Xt(n),m=Yt(n,l)):(g=Yt(n,l),m=Xt(n));const x=Is(g,o,i,s,r)?Of(g,e,t,i,s,r):null;if(x){const _=x.point[f];if(p?_<=o[m+u]:_>=o[m+u+3])return x}const y=Is(m,o,i,s,r)?Of(m,e,t,i,s,r):null;return x&&y?x.distance<=y.distance?x:y:x||y||null}}const qc=new v.Box3,wo=new Vi,So=new Vi,Ba=new v.Matrix4,Jx=new ci,Xc=new ci;function xB(n,e,t,i){_t.setBuffer(n._roots[e]);const s=Uf(0,n,t,i);return _t.clearBuffer(),s}function Uf(n,e,t,i,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=_t;let l=n*2;if(s===null&&(t.boundingBox||t.computeBoundingBox(),Jx.set(t.boundingBox.min,t.boundingBox.max,i),s=Jx),Ht(l,o)){const h=e.geometry,u=h.index,f=h.attributes.position,d=t.index,p=t.attributes.position,g=Ii(n,a),m=ji(l,o);if(Ba.copy(i).invert(),t.boundsTree)return It(n,r,Xc),Xc.matrix.copy(Ba),Xc.needsUpdate=!0,t.boundsTree.shapecast({intersectsBounds:x=>Xc.intersectsBox(x),intersectsTriangle:x=>{x.a.applyMatrix4(i),x.b.applyMatrix4(i),x.c.applyMatrix4(i),x.needsUpdate=!0;for(let b=g,y=m+g;b<y;b++)if(Ut(So,3*e.resolveTriangleIndex(b),u,f),So.needsUpdate=!0,x.intersectsTriangle(So))return!0;return!1}});{const A=fr(t);for(let x=g,b=m+g;x<b;x++){const y=e.resolveTriangleIndex(x);Ut(wo,3*y,u,f),wo.a.applyMatrix4(Ba),wo.b.applyMatrix4(Ba),wo.c.applyMatrix4(Ba),wo.needsUpdate=!0;for(let _=0,E=A*3;_<E;_+=3)if(Ut(So,_,d,p),So.needsUpdate=!0,wo.intersectsTriangle(So))return!0}}}else{const h=Xt(n),u=Yt(n,a);return It(h,r,qc),!!(s.intersectsBox(qc)&&Uf(h,e,t,i,s)||(It(u,r,qc),s.intersectsBox(qc)&&Uf(u,e,t,i,s)))}}const Yc=new v.Matrix4,Nf=new ci,Pa=new ci,bB=new v.Vector3,yB=new v.Vector3,vB=new v.Vector3,_B=new v.Vector3;function wB(n,e,t,i={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Nf.set(e.boundingBox.min,e.boundingBox.max,t),Nf.needsUpdate=!0;const a=n.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,f=Qi.getPrimitive(),d=Qi.getPrimitive();let p=bB,g=yB,m=null,A=null;s&&(m=vB,A=_B);let x=1/0,b=null,y=null;return Yc.copy(t).invert(),Pa.matrix.copy(Yc),n.shapecast({boundsTraverseOrder:_=>Nf.distanceToBox(_),intersectsBounds:(_,E,I)=>I<x&&I<o?(E&&(Pa.min.copy(_.min),Pa.max.copy(_.max),Pa.needsUpdate=!0),!0):!1,intersectsRange:(_,E)=>{if(e.boundsTree){const I=e.boundsTree;return I.shapecast({boundsTraverseOrder:B=>Pa.distanceToBox(B),intersectsBounds:(B,C,S)=>S<x&&S<o,intersectsRange:(B,C)=>{for(let S=B,P=B+C;S<P;S++){const T=I.resolveTriangleIndex(S);Ut(d,3*T,u,h),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let R=_,M=_+E;R<M;R++){const F=n.resolveTriangleIndex(R);Ut(f,3*F,c,l),f.needsUpdate=!0;const N=f.distanceToTriangle(d,p,m);if(N<x&&(g.copy(p),A&&A.copy(m),x=N,b=R,y=S),N<r)return!0}}}})}else{const I=fr(e);for(let B=0,C=I;B<C;B++){Ut(d,3*B,u,h),d.a.applyMatrix4(t),d.b.applyMatrix4(t),d.c.applyMatrix4(t),d.needsUpdate=!0;for(let S=_,P=_+E;S<P;S++){const T=n.resolveTriangleIndex(S);Ut(f,3*T,c,l),f.needsUpdate=!0;const R=f.distanceToTriangle(d,p,m);if(R<x&&(g.copy(p),A&&A.copy(m),x=R,b=S,y=B),R<r)return!0}}}}}),Qi.releasePrimitive(f),Qi.releasePrimitive(d),x===1/0?null:(i.point?i.point.copy(g):i.point=g.clone(),i.distance=x,i.faceIndex=b,s&&(s.point?s.point.copy(A):s.point=A.clone(),s.point.applyMatrix4(Yc),g.applyMatrix4(Yc),s.distance=g.sub(s.point).length(),s.faceIndex=y),i)}function SB(){return typeof SharedArrayBuffer<"u"}const La=new _t.constructor,Kc=new _t.constructor,Ts=new If(()=>new v.Box3),Co=new v.Box3,Mo=new v.Box3,zf=new v.Box3,Gf=new v.Box3;let Vf=!1;function CB(n,e,t,i){if(Vf)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Vf=!0;const s=n._roots,r=e._roots;let o,a=0,l=0;const c=new v.Matrix4().copy(t).invert();for(let h=0,u=s.length;h<u;h++){La.setBuffer(s[h]),l=0;const f=Ts.getPrimitive();It(0,La.float32Array,f),f.applyMatrix4(c);for(let d=0,p=r.length;d<p&&(Kc.setBuffer(r[d]),o=rn(0,0,t,c,i,a,l,0,0,f),Kc.clearBuffer(),l+=r[d].byteLength/li,!o);d++);if(Ts.releasePrimitive(f),La.clearBuffer(),a+=s[h].byteLength/li,o)break}return Vf=!1,o}function rn(n,e,t,i,s,r=0,o=0,a=0,l=0,c=null,h=!1){let u,f;h?(u=Kc,f=La):(u=La,f=Kc);const d=u.float32Array,p=u.uint32Array,g=u.uint16Array,m=f.float32Array,A=f.uint32Array,x=f.uint16Array,b=n*2,y=e*2,_=Ht(b,g),E=Ht(y,x);let I=!1;if(E&&_)h?I=s(Ii(e,A),ji(e*2,x),Ii(n,p),ji(n*2,g),l,o+e/Wt,a,r+n/Wt):I=s(Ii(n,p),ji(n*2,g),Ii(e,A),ji(e*2,x),a,r+n/Wt,l,o+e/Wt);else if(E){const B=Ts.getPrimitive();It(e,m,B),B.applyMatrix4(t);const C=Xt(n),S=Yt(n,p);It(C,d,Co),It(S,d,Mo);const P=B.intersectsBox(Co),T=B.intersectsBox(Mo);I=P&&rn(e,C,i,t,s,o,r,l,a+1,B,!h)||T&&rn(e,S,i,t,s,o,r,l,a+1,B,!h),Ts.releasePrimitive(B)}else{const B=Xt(e),C=Yt(e,A);It(B,m,zf),It(C,m,Gf);const S=c.intersectsBox(zf),P=c.intersectsBox(Gf);if(S&&P)I=rn(n,B,t,i,s,r,o,a,l+1,c,h)||rn(n,C,t,i,s,r,o,a,l+1,c,h);else if(S)if(_)I=rn(n,B,t,i,s,r,o,a,l+1,c,h);else{const T=Ts.getPrimitive();T.copy(zf).applyMatrix4(t);const R=Xt(n),M=Yt(n,p);It(R,d,Co),It(M,d,Mo);const F=T.intersectsBox(Co),N=T.intersectsBox(Mo);I=F&&rn(B,R,i,t,s,o,r,l,a+1,T,!h)||N&&rn(B,M,i,t,s,o,r,l,a+1,T,!h),Ts.releasePrimitive(T)}else if(P)if(_)I=rn(n,C,t,i,s,r,o,a,l+1,c,h);else{const T=Ts.getPrimitive();T.copy(Gf).applyMatrix4(t);const R=Xt(n),M=Yt(n,p);It(R,d,Co),It(M,d,Mo);const F=T.intersectsBox(Co),N=T.intersectsBox(Mo);I=F&&rn(C,R,i,t,s,o,r,l,a+1,T,!h)||N&&rn(C,M,i,t,s,o,r,l,a+1,T,!h),Ts.releasePrimitive(T)}}return I}const $c=new ci,Zx=new v.Box3,MB={strategy:Lx,maxDepth:40,maxLeafTris:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null};class Qf{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,s=e._roots,r=e._indirectBuffer,o=i.getIndex(),a={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(a.roots=s.map(l=>l.slice()),a.index=o?o.array.slice():null,a.indirectBuffer=r?r.slice():null):(a.roots=s,a.index=o?o.array:null,a.indirectBuffer=r),a}static deserialize(e,t,i={}){i={setIndex:!0,indirect:!!e.indirectBuffer,...i};const{index:s,roots:r,indirectBuffer:o}=e;e.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),l(r));const a=new Qf(t,{...i,[vf]:!0});if(a._roots=r,a._indirectBuffer=o||null,i.setIndex){const c=t.getIndex();if(c===null){const h=new v.BufferAttribute(e.index,1,!1);t.setIndex(h)}else c.array!==s&&(c.array.set(s),c.needsUpdate=!0)}return a;function l(c){for(let h=0;h<c.length;h++){const u=c[h],f=new Uint32Array(u),d=new Uint16Array(u);for(let p=0,g=u.byteLength/li;p<g;p++){const m=Wt*p,A=2*m;Ht(A,d)||(f[m+6]=f[m+6]/Wt-p)}}}}get indirect(){return!!this._indirectBuffer}constructor(e,t={}){if(e.isBufferGeometry){if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.")}else throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t=Object.assign({...MB,[vf]:!1},t),t.useSharedArrayBuffer&&!SB())throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=e,this._roots=null,this._indirectBuffer=null,t[vf]||(VD(this,t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new v.Box3))),this.resolveTriangleIndex=t.indirect?i=>this._indirectBuffer[i]:i=>i}shiftTriangleOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,s=t.length;i<s;i++)t[i]+=e;else{const i=this._roots;for(let s=0;s<i.length;s++){const r=i[s],o=new Uint32Array(r),a=new Uint16Array(r),l=r.byteLength/li;for(let c=0;c<l;c++){const h=Wt*c,u=2*h;Ht(u,a)&&(o[h+6]+=e)}}}}refit(e=null){return(this.indirect?pB:tB)(this,e)}traverse(e,t=0){const i=this._roots[t],s=new Uint32Array(i),r=new Uint16Array(i);o(0);function o(a,l=0){const c=a*2,h=Ht(c,r);if(h){const u=s[a+6],f=r[c+14];e(l,h,new Float32Array(i,a*4,6),u,f)}else{const u=Xt(a),f=Yt(a,s),d=Tf(a,s);e(l,h,new Float32Array(i,a*4,6),d)||(o(u,l+1),o(f,l+1))}}}raycast(e,t=v.FrontSide,i=0,s=1/0){const r=this._roots,o=[],a=this.indirect?gB:rB;for(let l=0,c=r.length;l<c;l++)a(this,l,t,e,o,i,s);return o}raycastFirst(e,t=v.FrontSide,i=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?AB:aB;for(let l=0,c=r.length;l<c;l++){const h=a(this,l,t,e,i,s);h!=null&&(o==null||h.distance<o.distance)&&(o=h)}return o}intersectsGeometry(e,t){let i=!1;const s=this._roots,r=this.indirect?xB:lB;for(let o=0,a=s.length;o<a&&(i=r(this,o,e,t),!i);o++);return i}shapecast(e){const t=Qi.getPrimitive(),i=this.indirect?sB:eB;let{boundsTraverseOrder:s,intersectsBounds:r,intersectsRange:o,intersectsTriangle:a}=e;if(o&&a){const u=o;o=(f,d,p,g,m)=>u(f,d,p,g,m)?!0:i(f,d,this,a,p,g,t)}else o||(a?o=(u,f,d,p)=>i(u,f,this,a,d,p,t):o=(u,f,d)=>d);let l=!1,c=0;const h=this._roots;for(let u=0,f=h.length;u<f;u++){const d=h[u];if(l=XD(this,u,r,o,s,c),l)break;c+=d.byteLength/li}return Qi.releasePrimitive(t),l}bvhcast(e,t,i){let{intersectsRanges:s,intersectsTriangles:r}=i;const o=Qi.getPrimitive(),a=this.geometry.index,l=this.geometry.attributes.position,c=this.indirect?p=>{const g=this.resolveTriangleIndex(p);Ut(o,g*3,a,l)}:p=>{Ut(o,p*3,a,l)},h=Qi.getPrimitive(),u=e.geometry.index,f=e.geometry.attributes.position,d=e.indirect?p=>{const g=e.resolveTriangleIndex(p);Ut(h,g*3,u,f)}:p=>{Ut(h,p*3,u,f)};if(r){const p=(g,m,A,x,b,y,_,E)=>{for(let I=A,B=A+x;I<B;I++){d(I),h.a.applyMatrix4(t),h.b.applyMatrix4(t),h.c.applyMatrix4(t),h.needsUpdate=!0;for(let C=g,S=g+m;C<S;C++)if(c(C),o.needsUpdate=!0,r(o,h,C,I,b,y,_,E))return!0}return!1};if(s){const g=s;s=function(m,A,x,b,y,_,E,I){return g(m,A,x,b,y,_,E,I)?!0:p(m,A,x,b,y,_,E,I)}}else s=p}return CB(this,e,t,s)}intersectsBox(e,t){return $c.set(e.min,e.max,t),$c.needsUpdate=!0,this.shapecast({intersectsBounds:i=>$c.intersectsBox(i),intersectsTriangle:i=>$c.intersectsTriangle(i)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},s={},r=0,o=1/0){return(this.indirect?wB:fB)(this,e,t,i,s,r,o)}closestPointToPoint(e,t={},i=0,s=1/0){return YD(this,e,t,i,s)}getBoundingBox(e){return e.makeEmpty(),this._roots.forEach(i=>{It(0,new Float32Array(i),Zx),e.union(Zx)}),e}}const eb=1e-6,EB=eb*.5,tb=Math.pow(10,-Math.log10(eb)),IB=EB*tb;function Sn(n){return~~(n*tb+IB)}function TB(n){return`${Sn(n.x)},${Sn(n.y)}`}function ib(n){return`${Sn(n.x)},${Sn(n.y)},${Sn(n.z)}`}function DB(n){return`${Sn(n.x)},${Sn(n.y)},${Sn(n.z)},${Sn(n.w)}`}function BB(n,e,t){t.direction.subVectors(e,n).normalize();const i=n.dot(t.direction);return t.origin.copy(n).addScaledVector(t.direction,-i),t}function nb(){return typeof SharedArrayBuffer<"u"}function PB(n){if(n.buffer instanceof SharedArrayBuffer)return n;const e=n.constructor,t=n.buffer,i=new SharedArrayBuffer(t.byteLength),s=new Uint8Array(t);return new Uint8Array(i).set(s,0),new e(i)}function LB(n,e=ArrayBuffer){return n>65535?new Uint32Array(new e(4*n)):new Uint16Array(new e(2*n))}function RB(n,e){if(!n.index){const t=n.attributes.position.count,i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,s=LB(t,i);n.setIndex(new v.BufferAttribute(s,1));for(let r=0;r<t;r++)s[r]=r}}function kB(n){return n.index?n.index.count:n.attributes.position.count}function jf(n){return kB(n)/3}const FB=1e-8,OB=new v.Vector3;function UB(n){return~~(n/3)}function NB(n){return n%3}function sb(n,e){return n.start-e.start}function rb(n,e){return OB.subVectors(e,n.origin).dot(n.direction)}function zB(n,e,t,i=FB){n.sort(sb),e.sort(sb);for(let a=0;a<n.length;a++){const l=n[a];for(let c=0;c<e.length;c++){const h=e[c];if(!(h.start>l.end)){if(l.end<h.start||h.end<l.start)continue;if(l.start<=h.start&&l.end>=h.end)r(h.end,l.end)||n.splice(a+1,0,{start:h.end,end:l.end,index:l.index}),l.end=h.start,h.start=0,h.end=0;else if(l.start>=h.start&&l.end<=h.end)r(l.end,h.end)||e.splice(c+1,0,{start:l.end,end:h.end,index:h.index}),h.end=l.start,l.start=0,l.end=0;else if(l.start<=h.start&&l.end<=h.end){const u=l.end;l.end=h.start,h.start=u}else if(l.start>=h.start&&l.end>=h.end){const u=h.end;h.end=l.start,l.start=u}else throw new Error}if(t.has(l.index)||t.set(l.index,[]),t.has(h.index)||t.set(h.index,[]),t.get(l.index).push(h.index),t.get(h.index).push(l.index),o(h)&&(e.splice(c,1),c--),o(l)){n.splice(a,1),a--;break}}}s(n),s(e);function s(a){for(let l=0;l<a.length;l++)o(a[l])&&(a.splice(l,1),l--)}function r(a,l){return Math.abs(l-a)<i}function o(a){return Math.abs(a.end-a.start)<i}}const ob=1e-5,ab=1e-4;class GB{constructor(){this._rays=[]}addRay(e){this._rays.push(e)}findClosestRay(e){const t=this._rays,i=e.clone();i.direction.multiplyScalar(-1);let s=1/0,r=null;for(let l=0,c=t.length;l<c;l++){const h=t[l];if(o(h,e)&&o(h,i))continue;const u=a(h,e),f=a(h,i),d=Math.min(u,f);d<s&&(s=d,r=h)}return r;function o(l,c){const h=l.origin.distanceTo(c.origin)>ob;return l.direction.angleTo(c.direction)>ab||h}function a(l,c){const h=l.origin.distanceTo(c.origin),u=l.direction.angleTo(c.direction);return h/ob+u/ab}}}const Wf=new v.Vector3,Hf=new v.Vector3,Jc=new v.Ray;function VB(n,e,t){const i=n.attributes,s=n.index,r=i.position,o=new Map,a=new Map,l=Array.from(e),c=new GB;for(let h=0,u=l.length;h<u;h++){const f=l[h],d=UB(f),p=NB(f);let g=3*d+p,m=3*d+(p+1)%3;s&&(g=s.getX(g),m=s.getX(m)),Wf.fromBufferAttribute(r,g),Hf.fromBufferAttribute(r,m),BB(Wf,Hf,Jc);let A,x=c.findClosestRay(Jc);x===null&&(x=Jc.clone(),c.addRay(x)),a.has(x)||a.set(x,{forward:[],reverse:[],ray:x}),A=a.get(x);let b=rb(x,Wf),y=rb(x,Hf);b>y&&([b,y]=[y,b]),Jc.direction.dot(x.direction)<0?A.reverse.push({start:b,end:y,index:f}):A.forward.push({start:b,end:y,index:f})}return a.forEach(({forward:h,reverse:u},f)=>{zB(h,u,o,t),h.length===0&&u.length===0&&a.delete(f)}),{disjointConnectivityMap:o,fragmentMap:a}}const QB=new v.Vector2,qf=new v.Vector3,jB=new v.Vector4,Xf=["","",""];class WB{constructor(e=null){this.data=null,this.disjointConnections=null,this.unmatchedDisjointEdges=null,this.unmatchedEdges=-1,this.matchedEdges=-1,this.useDrawRange=!0,this.useAllAttributes=!1,this.matchDisjointEdges=!1,this.degenerateEpsilon=1e-8,e&&this.updateFrom(e)}getSiblingTriangleIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:~~(i/3)}getSiblingEdgeIndex(e,t){const i=this.data[e*3+t];return i===-1?-1:i%3}getDisjointSiblingTriangleIndices(e,t){const i=e*3+t,s=this.disjointConnections.get(i);return s?s.map(r=>~~(r/3)):[]}getDisjointSiblingEdgeIndices(e,t){const i=e*3+t,s=this.disjointConnections.get(i);return s?s.map(r=>r%3):[]}isFullyConnected(){return this.unmatchedEdges===0}updateFrom(e){const{useAllAttributes:t,useDrawRange:i,matchDisjointEdges:s,degenerateEpsilon:r}=this,o=t?b:x,a=new Map,{attributes:l}=e,c=t?Object.keys(l):null,h=e.index,u=l.position;let f=jf(e);const d=f;let p=0;i&&(p=e.drawRange.start,e.drawRange.count!==1/0&&(f=~~(e.drawRange.count/3)));let g=this.data;(!g||g.length<3*d)&&(g=new Int32Array(3*d)),g.fill(-1);let m=0,A=new Set;for(let y=p,_=f*3+p;y<_;y+=3){const E=y;for(let I=0;I<3;I++){let B=E+I;h&&(B=h.getX(B)),Xf[I]=o(B)}for(let I=0;I<3;I++){const B=(I+1)%3,C=Xf[I],S=Xf[B],P=`${S}_${C}`;if(a.has(P)){const T=E+I,R=a.get(P);g[T]=R,g[R]=T,a.delete(P),m+=2,A.delete(R)}else{const T=`${C}_${S}`,R=E+I;a.set(T,R),A.add(R)}}}if(s){const{fragmentMap:y,disjointConnectivityMap:_}=VB(e,A,r);A.clear(),y.forEach(({forward:E,reverse:I})=>{E.forEach(({index:B})=>A.add(B)),I.forEach(({index:B})=>A.add(B))}),this.unmatchedDisjointEdges=y,this.disjointConnections=_,m=f*3-A.size}this.matchedEdges=m,this.unmatchedEdges=A.size,this.data=g;function x(y){return qf.fromBufferAttribute(u,y),ib(qf)}function b(y){let _="";for(let E=0,I=c.length;E<I;E++){const B=l[c[E]];let C;switch(B.itemSize){case 1:C=Sn(B.getX(y));break;case 2:C=TB(QB.fromBufferAttribute(B,y));break;case 3:C=ib(qf.fromBufferAttribute(B,y));break;case 4:C=DB(jB.fromBufferAttribute(B,y));break}_!==""&&(_+="|"),_+=C}return _}}}class Zc extends v.Mesh{constructor(...e){super(...e),this.isBrush=!0,this._previousMatrix=new v.Matrix4,this._previousMatrix.elements.fill(0)}markUpdated(){this._previousMatrix.copy(this.matrix)}isDirty(){const{matrix:e,_previousMatrix:t}=this,i=e.elements,s=t.elements;for(let r=0;r<16;r++)if(i[r]!==s[r])return!0;return!1}prepareGeometry(){const e=this.geometry,t=e.attributes,i=nb();if(i)for(const s in t){const r=t[s];if(r.isInterleavedBufferAttribute)throw new Error("Brush: InterleavedBufferAttributes are not supported.");r.array=PB(r.array)}if(e.boundsTree||(RB(e,{useSharedArrayBuffer:i}),e.boundsTree=new Qf(e,{maxLeafTris:3,indirect:!0,useSharedArrayBuffer:i})),e.halfEdges||(e.halfEdges=new WB(e)),!e.groupIndices){const s=jf(e),r=new Uint16Array(s),o=e.groups;for(let a=0,l=o.length;a<l;a++){const{start:c,count:h}=o[a];for(let u=c/3,f=(c+h)/3;u<f;u++)r[u]=a}e.groupIndices=r}}disposeCacheData(){const{geometry:e}=this;e.halfEdges=null,e.boundsTree=null,e.groupIndices=null}}const HB=1e-14,Yf=new v.Vector3,lb=new v.Vector3,cb=new v.Vector3;function Ds(n,e=HB){Yf.subVectors(n.b,n.a),lb.subVectors(n.c,n.a),cb.subVectors(n.b,n.c);const t=Yf.angleTo(lb),i=Yf.angleTo(cb),s=Math.PI-t-i;return Math.abs(t)<e||Math.abs(i)<e||Math.abs(s)<e||n.a.distanceToSquared(n.b)<e||n.a.distanceToSquared(n.c)<e||n.b.distanceToSquared(n.c)<e}const Kf=1e-10,Ra=1e-10,qB=1e-10,es=new v.Line3,Ft=new v.Line3,ts=new v.Vector3,$f=new v.Vector3,hb=new v.Vector3,eh=new v.Plane,Jf=new Vi;class XB{constructor(){this._pool=[],this._index=0}getTriangle(){return this._index>=this._pool.length&&this._pool.push(new v.Triangle),this._pool[this._index++]}clear(){this._index=0}reset(){this._pool.length=0,this._index=0}}class YB{constructor(){this.trianglePool=new XB,this.triangles=[],this.normal=new v.Vector3,this.coplanarTriangleUsed=!1}initialize(e){this.reset();const{triangles:t,trianglePool:i,normal:s}=this;if(Array.isArray(e))for(let r=0,o=e.length;r<o;r++){const a=e[r];if(r===0)a.getNormal(s);else if(Math.abs(1-a.getNormal(ts).dot(s))>Kf)throw new Error("Triangle Splitter: Cannot initialize with triangles that have different normals.");const l=i.getTriangle();l.copy(a),t.push(l)}else{e.getNormal(s);const r=i.getTriangle();r.copy(e),t.push(r)}}splitByTriangle(e){const{normal:t,triangles:i}=this;if(e.getNormal($f).normalize(),Math.abs(1-Math.abs($f.dot(t)))<qB){this.coplanarTriangleUsed=!0;for(let r=0,o=i.length;r<o;r++){const a=i[r];a.coplanarCount=0}const s=[e.a,e.b,e.c];for(let r=0;r<3;r++){const o=(r+1)%3,a=s[r],l=s[o];ts.subVectors(l,a).normalize(),hb.crossVectors($f,ts),eh.setFromNormalAndCoplanarPoint(hb,a),this.splitByPlane(eh,e)}}else e.getPlane(eh),this.splitByPlane(eh,e)}splitByPlane(e,t){const{triangles:i,trianglePool:s}=this;Jf.copy(t),Jf.needsUpdate=!0;for(let r=0,o=i.length;r<o;r++){const a=i[r];if(!Jf.intersectsTriangle(a,es,!0))continue;const{a:l,b:c,c:h}=a;let u=0,f=-1,d=!1,p=[],g=[];const m=[l,c,h];for(let A=0;A<3;A++){const x=(A+1)%3;es.start.copy(m[A]),es.end.copy(m[x]);const b=e.distanceToPoint(es.start),y=e.distanceToPoint(es.end);if(Math.abs(b)<Ra&&Math.abs(y)<Ra){d=!0;break}if(b>0?p.push(A):g.push(A),Math.abs(b)<Ra)continue;let _=!!e.intersectLine(es,ts);!_&&Math.abs(y)<Ra&&(ts.copy(es.end),_=!0),_&&!(ts.distanceTo(es.start)<Kf)&&(ts.distanceTo(es.end)<Kf&&(f=A),u===0?Ft.start.copy(ts):Ft.end.copy(ts),u++)}if(!d&&u===2&&Ft.distance()>Ra)if(f!==-1){f=(f+1)%3;let A=0;A===f&&(A=(A+1)%3);let x=A+1;x===f&&(x=(x+1)%3);const b=s.getTriangle();b.a.copy(m[x]),b.b.copy(Ft.end),b.c.copy(Ft.start),Ds(b)||i.push(b),a.a.copy(m[A]),a.b.copy(Ft.start),a.c.copy(Ft.end),Ds(a)&&(i.splice(r,1),r--,o--)}else{const A=p.length>=2?g[0]:p[0];if(A===0){let E=Ft.start;Ft.start=Ft.end,Ft.end=E}const x=(A+1)%3,b=(A+2)%3,y=s.getTriangle(),_=s.getTriangle();m[x].distanceToSquared(Ft.start)<m[b].distanceToSquared(Ft.end)?(y.a.copy(m[x]),y.b.copy(Ft.start),y.c.copy(Ft.end),_.a.copy(m[x]),_.b.copy(m[b]),_.c.copy(Ft.start)):(y.a.copy(m[b]),y.b.copy(Ft.start),y.c.copy(Ft.end),_.a.copy(m[x]),_.b.copy(m[b]),_.c.copy(Ft.end)),a.a.copy(m[A]),a.b.copy(Ft.end),a.c.copy(Ft.start),Ds(y)||i.push(y),Ds(_)||i.push(_),Ds(a)&&(i.splice(r,1),r--,o--)}else u===3&&console.warn("TriangleClipper: Coplanar clip not handled")}}reset(){this.triangles.length=0,this.trianglePool.clear(),this.coplanarTriangleUsed=!1}}function KB(n){return n=~~n,n+4-n%4}class ub{constructor(e,t=500){this.expansionFactor=1.5,this.type=e,this.length=0,this.array=null,this.setSize(t)}setType(e){if(this.length!==0)throw new Error("TypeBackedArray: Cannot change the type while there is used data in the buffer.");const t=this.array.buffer;this.array=new e(t),this.type=e}setSize(e){if(this.array&&e===this.array.length)return;const t=this.type,i=nb()?SharedArrayBuffer:ArrayBuffer,s=new t(new i(KB(e*t.BYTES_PER_ELEMENT)));this.array&&s.set(this.array,0),this.array=s}expand(){const{array:e,expansionFactor:t}=this;this.setSize(e.length*t)}push(...e){let{array:t,length:i}=this;i+e.length>t.length&&(this.expand(),t=this.array);for(let s=0,r=e.length;s<r;s++)t[i+s]=e[s];this.length+=e.length}clear(){this.length=0}}class $B{constructor(){this.groupAttributes=[{}],this.groupCount=0}getType(e){return this.groupAttributes[0][e].type}getItemSize(e){return this.groupAttributes[0][e].itemSize}getNormalized(e){return this.groupAttributes[0][e].normalized}getCount(e){if(this.groupCount<=e)return 0;const t=this.getGroupAttrArray("position",e);return t.length/t.itemSize}getTotalLength(e){const{groupCount:t,groupAttributes:i}=this;let s=0;for(let r=0;r<t;r++){const o=i[r];s+=o[e].length}return s}getGroupAttrSet(e=0){const{groupAttributes:t}=this;if(t[e])return this.groupCount=Math.max(this.groupCount,e+1),t[e];const i=t[0];for(this.groupCount=Math.max(this.groupCount,e+1);e>=t.length;){const s={};t.push(s);for(const r in i){const o=i[r],a=new ub(o.type);a.itemSize=o.itemSize,a.normalized=o.normalized,s[r]=a}}return t[e]}getGroupAttrArray(e,t=0){const{groupAttributes:i}=this;if(!i[0][e])throw new Error(`TypedAttributeData: Attribute with "${e}" has not been initialized`);return this.getGroupAttrSet(t)[e]}initializeArray(e,t,i,s){const{groupAttributes:r}=this,a=r[0][e];if(a){if(a.type!==t)for(let l=0,c=r.length;l<c;l++){const h=r[l][e];h.setType(t),h.itemSize=i,h.normalized=s}}else for(let l=0,c=r.length;l<c;l++){const h=new ub(t);h.itemSize=i,h.normalized=s,r[l][e]=h}}clear(){this.groupCount=0;const{groupAttributes:e}=this;e.forEach(t=>{for(const i in t)t[i].clear()})}delete(e){this.groupAttributes.forEach(t=>{delete t[e]})}reset(){this.groupAttributes=[],this.groupCount=0}}class db{constructor(){this.intersectionSet={},this.ids=[]}add(e,t){const{intersectionSet:i,ids:s}=this;i[e]||(i[e]=[],s.push(e)),i[e].push(t)}}const JB=0,ZB=1,eP=2,fb=3,tP=4,pb=5,gb=6,Wi=new v.Ray,mb=new v.Matrix4,hi=new v.Triangle,is=new v.Vector3,Ab=new v.Vector4,xb=new v.Vector4,bb=new v.Vector4,Zf=new v.Vector4,th=new v.Vector4,ih=new v.Vector4,yb=new v.Line3,ep=new v.Vector3,tp=1e-8,iP=1e-15,Ar=-1,xr=1,nh=-2,sh=2,ka=0,br=1,ip=2,nP=1e-14;let rh=null;function vb(n){rh=n}function _b(n,e){n.getMidpoint(Wi.origin),n.getNormal(Wi.direction);const t=e.raycastFirst(Wi,v.DoubleSide);return!!(t&&Wi.direction.dot(t.face.normal)>0)?Ar:xr}function sP(n,e){function t(){return Math.random()-.5}n.getNormal(ep),Wi.direction.copy(ep),n.getMidpoint(Wi.origin);const i=3;let s=0,r=1/0;for(let o=0;o<i;o++){Wi.direction.x+=t()*tp,Wi.direction.y+=t()*tp,Wi.direction.z+=t()*tp,Wi.direction.multiplyScalar(-1);const a=e.raycastFirst(Wi,v.DoubleSide);if(!!(a&&Wi.direction.dot(a.face.normal)>0)&&s++,a!==null&&(r=Math.min(r,a.distance)),r<=iP)return a.face.normal.dot(ep)>0?sh:nh;if(s/i>.5||(o-s+1)/i>.5)break}return s/i>.5?Ar:xr}function rP(n,e){const t=new db,i=new db;return mb.copy(n.matrixWorld).invert().multiply(e.matrixWorld),n.geometry.boundsTree.bvhcast(e.geometry.boundsTree,mb,{intersectsTriangles(s,r,o,a){if(!Ds(s)&&!Ds(r)){let l=s.intersectsTriangle(r,yb,!0);if(!l){const c=s.plane,h=r.plane,u=c.normal,f=h.normal;u.dot(f)===1&&Math.abs(c.constant-h.constant)<nP&&(l=!0)}if(l){let c=n.geometry.boundsTree.resolveTriangleIndex(o),h=e.geometry.boundsTree.resolveTriangleIndex(a);t.add(c,h),i.add(h,c),rh&&(rh.addEdge(yb),rh.addIntersectingTriangles(o,s,a,r))}}return!1}}),{aIntersections:t,bIntersections:i}}function oP(n,e,t,i,s,r,o=!1){const a=t.attributes,l=t.index,c=n*3,h=l.getX(c+0),u=l.getX(c+1),f=l.getX(c+2);for(const d in r){const p=a[d],g=r[d];if(!(d in a))throw new Error(`CSG Operations: Attribute ${d} not available on geometry.`);const m=p.itemSize;d==="position"?(hi.a.fromBufferAttribute(p,h).applyMatrix4(i),hi.b.fromBufferAttribute(p,u).applyMatrix4(i),hi.c.fromBufferAttribute(p,f).applyMatrix4(i),np(hi.a,hi.b,hi.c,e,3,g,o)):d==="normal"?(hi.a.fromBufferAttribute(p,h).applyNormalMatrix(s),hi.b.fromBufferAttribute(p,u).applyNormalMatrix(s),hi.c.fromBufferAttribute(p,f).applyNormalMatrix(s),o&&(hi.a.multiplyScalar(-1),hi.b.multiplyScalar(-1),hi.c.multiplyScalar(-1)),np(hi.a,hi.b,hi.c,e,3,g,o,!0)):(Ab.fromBufferAttribute(p,h),xb.fromBufferAttribute(p,u),bb.fromBufferAttribute(p,f),np(Ab,xb,bb,e,m,g,o))}}function aP(n,e,t,i,s,r,o,a=!1){sp(n,i,s,r,o,a),sp(a?t:e,i,s,r,o,a),sp(a?e:t,i,s,r,o,a)}function wb(n,e,t=!1){switch(n){case JB:if(e===xr||e===sh&&!t)return br;break;case ZB:if(t){if(e===Ar)return ka}else if(e===xr||e===nh)return br;break;case eP:if(t){if(e===xr||e===nh)return br}else if(e===Ar)return ka;break;case tP:if(e===Ar)return ka;if(e===xr)return br;break;case fb:if(e===Ar||e===sh&&!t)return br;break;case pb:if(!t&&(e===xr||e===nh))return br;break;case gb:if(!t&&(e===Ar||e===sh))return br;break;default:throw new Error(`Unrecognized CSG operation enum "${n}".`)}return ip}function np(n,e,t,i,s,r,o=!1,a=!1){const l=c=>{r.push(c.x),s>1&&r.push(c.y),s>2&&r.push(c.z),s>3&&r.push(c.w)};Zf.set(0,0,0,0).addScaledVector(n,i.a.x).addScaledVector(e,i.a.y).addScaledVector(t,i.a.z),th.set(0,0,0,0).addScaledVector(n,i.b.x).addScaledVector(e,i.b.y).addScaledVector(t,i.b.z),ih.set(0,0,0,0).addScaledVector(n,i.c.x).addScaledVector(e,i.c.y).addScaledVector(t,i.c.z),a&&(Zf.normalize(),th.normalize(),ih.normalize()),l(Zf),o?(l(ih),l(th)):(l(th),l(ih))}function sp(n,e,t,i,s,r=!1){for(const o in s){const a=e[o],l=s[o];if(!(o in e))throw new Error(`CSG Operations: Attribute ${o} no available on geometry.`);const c=a.itemSize;o==="position"?(is.fromBufferAttribute(a,n).applyMatrix4(t),l.push(is.x,is.y,is.z)):o==="normal"?(is.fromBufferAttribute(a,n).applyNormalMatrix(i),r&&is.multiplyScalar(-1),l.push(is.x,is.y,is.z)):(l.push(a.getX(n)),c>1&&l.push(a.getY(n)),c>2&&l.push(a.getZ(n)),c>3&&l.push(a.getW(n)))}}class lP{constructor(e){this.triangle=new v.Triangle().copy(e),this.intersects={}}addTriangle(e,t){this.intersects[e]=new v.Triangle().copy(t)}getIntersectArray(){const e=[],{intersects:t}=this;for(const i in t)e.push(t[i]);return e}}class Sb{constructor(){this.data={}}addTriangleIntersection(e,t,i,s){const{data:r}=this;r[e]||(r[e]=new lP(t)),r[e].addTriangle(i,s)}getTrianglesAsArray(e=null){const{data:t}=this,i=[];if(e!==null)e in t&&i.push(t[e].triangle);else for(const s in t)i.push(t[s].triangle);return i}getTriangleIndices(){return Object.keys(this.data).map(e=>parseInt(e))}getIntersectionIndices(e){const{data:t}=this;return t[e]?Object.keys(t[e].intersects).map(i=>parseInt(i)):[]}getIntersectionsAsArray(e=null,t=null){const{data:i}=this,s=new Set,r=[],o=a=>{if(i[a])if(t!==null)i[a].intersects[t]&&r.push(i[a].intersects[t]);else{const l=i[a].intersects;for(const c in l)s.has(c)||(s.add(c),r.push(l[c]))}};if(e!==null)o(e);else for(const a in i)o(a);return r}reset(){this.data={}}}class cP{constructor(){this.enabled=!1,this.triangleIntersectsA=new Sb,this.triangleIntersectsB=new Sb,this.intersectionEdges=[]}addIntersectingTriangles(e,t,i,s){const{triangleIntersectsA:r,triangleIntersectsB:o}=this;r.addTriangleIntersection(e,t,i,s),o.addTriangleIntersection(i,s,e,t)}addEdge(e){this.intersectionEdges.push(e.clone())}reset(){this.triangleIntersectsA.reset(),this.triangleIntersectsB.reset(),this.intersectionEdges=[]}init(){this.enabled&&(this.reset(),vb(this))}complete(){this.enabled&&vb(null)}}const Bs=new v.Matrix4,oh=new v.Matrix3,yr=new v.Triangle,ah=new v.Triangle,Ps=new v.Triangle,lh=new v.Triangle,on=[],vr=[];function hP(n){for(const e of n)return e}function uP(n,e,t,i,s,r={}){const{useGroups:o=!0}=r,{aIntersections:a,bIntersections:l}=rP(n,e),c=[];let h=null,u;return u=o?0:-1,Cb(n,e,a,t,!1,i,s,u),Mb(n,e,a,t,!1,s,u),t.findIndex(d=>d!==gb&&d!==pb)!==-1&&(u=o?n.geometry.groups.length||1:-1,Cb(e,n,l,t,!0,i,s,u),Mb(e,n,l,t,!0,s,u)),on.length=0,vr.length=0,{groups:c,materials:h}}function Cb(n,e,t,i,s,r,o,a=0){const l=n.matrixWorld.determinant()<0;Bs.copy(e.matrixWorld).invert().multiply(n.matrixWorld),oh.getNormalMatrix(n.matrixWorld).multiplyScalar(l?-1:1);const c=n.geometry.groupIndices,h=n.geometry.index,u=n.geometry.attributes.position,f=e.geometry.boundsTree,d=e.geometry.index,p=e.geometry.attributes.position,g=t.ids,m=t.intersectionSet;for(let A=0,x=g.length;A<x;A++){const b=g[A],y=a===-1?0:c[b]+a,_=3*b,E=h.getX(_+0),I=h.getX(_+1),B=h.getX(_+2);yr.a.fromBufferAttribute(u,E).applyMatrix4(Bs),yr.b.fromBufferAttribute(u,I).applyMatrix4(Bs),yr.c.fromBufferAttribute(u,B).applyMatrix4(Bs),r.reset(),r.initialize(yr);const C=m[b];for(let P=0,T=C.length;P<T;P++){const R=3*C[P],M=d.getX(R+0),F=d.getX(R+1),N=d.getX(R+2);ah.a.fromBufferAttribute(p,M),ah.b.fromBufferAttribute(p,F),ah.c.fromBufferAttribute(p,N),r.splitByTriangle(ah)}const S=r.triangles;for(let P=0,T=S.length;P<T;P++){const R=S[P],M=r.coplanarTriangleUsed?sP(R,f):_b(R,f);on.length=0,vr.length=0;for(let F=0,N=i.length;F<N;F++){const j=wb(i[F],M,s);j!==ip&&(vr.push(j),on.push(o[F].getGroupAttrSet(y)))}if(on.length!==0){yr.getBarycoord(R.a,lh.a),yr.getBarycoord(R.b,lh.b),yr.getBarycoord(R.c,lh.c);for(let F=0,N=on.length;F<N;F++){const j=on[F],U=vr[F]===ka;oP(b,lh,n.geometry,n.matrixWorld,oh,j,l!==U)}}}}return g.length}function Mb(n,e,t,i,s,r,o=0){const a=n.matrixWorld.determinant()<0;Bs.copy(e.matrixWorld).invert().multiply(n.matrixWorld),oh.getNormalMatrix(n.matrixWorld).multiplyScalar(a?-1:1);const l=e.geometry.boundsTree,c=n.geometry.groupIndices,h=n.geometry.index,u=n.geometry.attributes,f=u.position,d=[],p=n.geometry.halfEdges,g=new Set,m=jf(n.geometry);for(let A=0,x=m;A<x;A++)A in t.intersectionSet||g.add(A);for(;g.size>0;){const A=hP(g);g.delete(A),d.push(A);const x=3*A,b=h.getX(x+0),y=h.getX(x+1),_=h.getX(x+2);Ps.a.fromBufferAttribute(f,b).applyMatrix4(Bs),Ps.b.fromBufferAttribute(f,y).applyMatrix4(Bs),Ps.c.fromBufferAttribute(f,_).applyMatrix4(Bs);const E=_b(Ps,l);vr.length=0,on.length=0;for(let I=0,B=i.length;I<B;I++){const C=wb(i[I],E,s);C!==ip&&(vr.push(C),on.push(r[I]))}for(;d.length>0;){const I=d.pop();for(let B=0;B<3;B++){const C=p.getSiblingTriangleIndex(I,B);C!==-1&&g.has(C)&&(d.push(C),g.delete(C))}if(on.length!==0){const B=3*I,C=h.getX(B+0),S=h.getX(B+1),P=h.getX(B+2),T=o===-1?0:c[I]+o;if(Ps.a.fromBufferAttribute(f,C),Ps.b.fromBufferAttribute(f,S),Ps.c.fromBufferAttribute(f,P),!Ds(Ps))for(let R=0,M=on.length;R<M;R++){const F=vr[R],N=on[R].getGroupAttrSet(T),j=F===ka;aP(C,S,P,u,n.matrixWorld,oh,N,j!==a)}}}}}function dP(n){for(let e=0;e<n.length-1;e++){const t=n[e],i=n[e+1];if(t.materialIndex===i.materialIndex){const s=t.start,r=i.start+i.count;i.start=s,i.count=r-s,n.splice(e,1),e--}}}function fP(n,e,t,i){t.clear();const s=n.attributes;for(let r=0,o=i.length;r<o;r++){const a=i[r],l=s[a];t.initializeArray(a,l.array.constructor,l.itemSize,l.normalized)}for(const r in t.attributes)i.includes(r)||t.delete(r);for(const r in e.attributes)i.includes(r)||(e.deleteAttribute(r),e.dispose())}function pP(n,e,t){let i=!1,s=-1;const r=n.attributes,o=e.groupAttributes[0];for(const l in o){const c=e.getTotalLength(l),h=e.getType(l),u=e.getItemSize(l),f=e.getNormalized(l);let d=r[l];(!d||d.array.length<c)&&(d=new v.BufferAttribute(new h(c),u,f),n.setAttribute(l,d),i=!0);let p=0;for(let g=0,m=Math.min(t.length,e.groupCount);g<m;g++){const A=t[g].index,{array:x,type:b,length:y}=e.groupAttributes[A][l],_=new b(x.buffer,0,y);d.array.set(_,p),p+=_.length}d.needsUpdate=!0,s=c/d.itemSize}if(n.index){const l=n.index.array;if(l.length<s)n.index=null,i=!0;else for(let c=0,h=l.length;c<h;c++)l[c]=c}let a=0;n.clearGroups();for(let l=0,c=Math.min(t.length,e.groupCount);l<c;l++){const{index:h,materialIndex:u}=t[l],f=e.getCount(h);f!==0&&(n.addGroup(a,f,u),a+=f)}n.setDrawRange(0,s),n.boundsTree=null,i&&n.dispose()}function Eb(n,e){let t=e;return Array.isArray(e)||(t=[],n.forEach(i=>{t[i.materialIndex]=e})),t}class gP{constructor(){this.triangleSplitter=new YB,this.attributeData=[],this.attributes=["position","uv","normal"],this.useGroups=!0,this.consolidateGroups=!0,this.debug=new cP}getGroupRanges(e){return!this.useGroups||e.groups.length===0?[{start:0,count:1/0,materialIndex:0}]:e.groups.map(t=>({...t}))}evaluate(e,t,i,s=new Zc){let r=!0;if(Array.isArray(i)||(i=[i]),Array.isArray(s)||(s=[s],r=!1),s.length!==i.length)throw new Error("Evaluator: operations and target array passed as different sizes.");e.prepareGeometry(),t.prepareGeometry();const{triangleSplitter:o,attributeData:a,attributes:l,useGroups:c,consolidateGroups:h,debug:u}=this;for(;a.length<s.length;)a.push(new $B);s.forEach((A,x)=>{fP(e.geometry,A.geometry,a[x],l)}),u.init(),uP(e,t,i,o,a,{useGroups:c}),u.complete();const f=this.getGroupRanges(e.geometry),d=Eb(f,e.material),p=this.getGroupRanges(t.geometry),g=Eb(p,t.material);p.forEach(A=>A.materialIndex+=d.length);let m=[...f,...p].map((A,x)=>({...A,index:x}));if(c){const A=[...d,...g];h&&(m=m.map(b=>{const y=A[b.materialIndex];return b.materialIndex=A.indexOf(y),b}).sort((b,y)=>b.materialIndex-y.materialIndex));const x=[];for(let b=0,y=A.length;b<y;b++){let _=!1;for(let E=0,I=m.length;E<I;E++){const B=m[E];B.materialIndex===b&&(_=!0,B.materialIndex=x.length)}_&&x.push(A[b])}s.forEach(b=>{b.material=x})}else m=[{start:0,count:1/0,index:0,materialIndex:0}],s.forEach(A=>{A.material=d[0]});return s.forEach((A,x)=>{const b=A.geometry;pP(b,a[x],m),h&&dP(b.groups)}),r?s:s[0]}evaluateHierarchy(e,t=new Zc){e.updateMatrixWorld(!0);const i=(r,o)=>{const a=r.children;for(let l=0,c=a.length;l<c;l++){const h=a[l];h.isOperationGroup?i(h,o):o(h)}},s=r=>{const o=r.children;let a=!1;for(let c=0,h=o.length;c<h;c++){const u=o[c];a=s(u)||a}const l=r.isDirty();if(l&&r.markUpdated(),a&&!r.isOperationGroup){let c;return i(r,h=>{c?c=this.evaluate(c,h,h.operation):c=this.evaluate(r,h,h.operation)}),r._cachedGeometry=c.geometry,r._cachedMaterials=c.material,!0}else return a||l};return s(e),t.geometry=e._cachedGeometry,t.material=e._cachedMaterials,t}reset(){this.triangleSplitter.reset()}}class mP{engine;evaluator;fillMeshName="ClippingFaceFillMesh";fillMeshes=new Map;maxCandidates=22e5;maxTriangleCountPerMesh=12e4;fillMaterial;fillTextureRepeat=60;fillTextureRotation=0;constructor(e){this.engine=e,this.evaluator=new gP;const t=new URL("/texture/fill.png",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,i=new w.TextureLoader().load(t);i.wrapS=w.RepeatWrapping,i.wrapT=w.RepeatWrapping,i.center.set(.5,.5),i.rotation=this.fillTextureRotation,this.fillMaterial=new w.MeshStandardMaterial({color:14079687,map:i,side:w.DoubleSide,toneMapped:!1}),this.fillMaterial.clipShadows=!0,this.fillMaterial.clippingPlanes=e.sectionPlane}clear(){this.fillMeshes.forEach(e=>{e.parent?.remove(e),e.geometry?.dispose?.();const t=e.material;Array.isArray(t)?t.forEach(i=>i.dispose?.()):t&&t!==this.fillMaterial&&t.dispose?.()}),this.fillMeshes.clear()}updataFace(e){this.clear(),e instanceof w.Plane&&this.engine.clipping.fillCutFace&&this.buildSinglePlaneFill(e,"face")}updataFaces(e){this.clear(),!(!Array.isArray(e)||e.length===0)&&this.engine.clipping.fillCutFace&&e.forEach((t,i)=>{if(!(t instanceof w.Plane))return;const s=`plane-${i}-${String(t.name??i)}`;this.buildSinglePlaneFill(t,s)})}buildSinglePlaneFill(e,t){const i=this.engine?.octreeBox?.getBoundingBox?.();if(i==null||i.min==null||i.max==null)return;const s=this.collectCandidateMeshesFromOctree(e);if(s.length===0)return;const r=this.filterMeshesByBoxAndComplexity(e,s);if(r.length===0)return;const o=i.min.distanceTo(i.max),a=o*5,l=.1,c=this.createPlaneBrush(e,a,l),h=[];for(const g of r.slice(0,this.maxCandidates)){const m=this.createWorldBrushFromMesh(g);if(m!=null)try{const x=this.evaluator.evaluate(m,c,fb)?.geometry;if(!x)continue;const b=this.extractPlaneCapGeometry(x,e,l);b&&h.push(b),x.dispose()}catch{}finally{m.geometry.dispose()}}if(c.geometry.dispose(),h.length===0)return;const u=Xn(h,!1);if(h.forEach(g=>g.dispose()),!u)return;this.applyPlanarUv(u,e);const f=this.getFaceOffsetDistance(o),d=this.getFaceOffsetSign();u.translate(e.normal.x*f*d,e.normal.y*f*d,e.normal.z*f*d);const p=new w.Mesh(u,this.fillMaterial);p.name=`${this.fillMeshName}_${t}`,p.frustumCulled=!1,p.renderOrder=20,p.castShadow=!1,p.receiveShadow=!1,this.engine.scene.add(p),this.fillMeshes.set(t,p)}getFaceOffsetDistance(e){return-.001}getFaceOffsetSign(){const e=this.engine?.engineStatus?.clippingFaceOffsetSign;return e===1||e===-1?e:-1}collectCandidateMeshesFromOctree(e){const t=[],i=new Set,s=Array.isArray(this.engine?.engineStatus?.models)?this.engine.engineStatus.models:[];for(const r of s){const o=this.engine.models?.find?.(c=>c.url===r.url);if(!o?.nodesMap)continue;const a=this.getIgnoredIds(r.url),l=Array.isArray(r?.info?.lods)?r.info.lods:[];for(const c of l){const h=c?.octreeBox;if(!h)continue;const u=this.collectIntersectElementIds(h,e);for(const f of u){if(a.has(f))continue;const d=o.nodesMap.get(f);if(!(d?.instance===!0||!Array.isArray(d?.infos)))for(const p of d.infos){const g=p?.mesh;g instanceof w.Mesh&&(i.has(g.uuid)||(i.add(g.uuid),t.push(g)))}}}}return t}getIgnoredIds(e){const t=new Set,i=Array.isArray(this.engine?.engineStatus?.hideModels)?this.engine.engineStatus.hideModels:[],s=Array.isArray(this.engine?.engineStatus?.translucentModels)?this.engine.engineStatus.translucentModels:[],r=i.find(a=>a.url===e)?.ids;Array.isArray(r)&&r.forEach(a=>t.add(a));const o=s.find(a=>a.url===e)?.ids;return Array.isArray(o)&&o.forEach(a=>t.add(a)),t}collectIntersectElementIds(e,t){const i=new Set,s=[e];for(;s.length>0;){const r=s.pop();if(!r)continue;const o=this.octreeNodeToBox3(r);!o||!t.intersectsBox(o)||(Array.isArray(r.elements)&&r.elements.forEach(a=>i.add(a)),Array.isArray(r.children)&&r.children.forEach(a=>s.push(a)))}return i}octreeNodeToBox3(e){if(!e?.min||!e?.max)return null;const t=new w.Vector3(e.min.X*.3048,e.min.Z*.3048,-e.min.Y*.3048),i=new w.Vector3(e.max.X*.3048,e.max.Z*.3048,-e.max.Y*.3048),s=new w.Vector3(Math.min(t.x,i.x),Math.min(t.y,i.y),Math.min(t.z,i.z)),r=new w.Vector3(Math.max(t.x,i.x),Math.max(t.y,i.y),Math.max(t.z,i.z));return new w.Box3(s,r)}filterMeshesByBoxAndComplexity(e,t){const i=[],s=new w.Box3;for(const r of t){const o=r.geometry,a=o?.attributes?.position;!o||!a||a.count===0||(o.index?Math.floor(o.index.count/3):Math.floor(a.count/3))>this.maxTriangleCountPerMesh||(o.boundingBox||o.computeBoundingBox(),o.boundingBox&&(s.copy(o.boundingBox),r.updateWorldMatrix(!0,!1),s.applyMatrix4(r.matrixWorld),e.intersectsBox(s)&&(r.geometry.attributes.position.count>500||i.push(r))))}return i}createPlaneBrush(e,t,i){const s=new w.BoxGeometry(t,t,i),r=e.coplanarPoint(new w.Vector3),o=new w.Quaternion().setFromUnitVectors(new w.Vector3(0,0,1),e.normal.clone().normalize()),a=new w.Matrix4().compose(r,o,new w.Vector3(1,1,1));s.applyMatrix4(a);const l=this.toCsgReadyGeometry(s);return s.dispose(),new Zc(l)}createWorldBrushFromMesh(e){const t=e.geometry;if(!t||!t.attributes?.position)return null;e.updateWorldMatrix(!0,!1);const i=t.clone();i.applyMatrix4(e.matrixWorld);const s=this.toCsgReadyGeometry(i);return i.dispose(),new Zc(s)}toCsgReadyGeometry(e){const t=e.index?e.toNonIndexed():e.clone();t.getAttribute("normal")||t.computeVertexNormals();const i=t.getAttribute("position");if(i&&!t.getAttribute("uv")){const r=new Float32Array(i.count*2);t.setAttribute("uv",new w.Float32BufferAttribute(r,2))}const s=new Set(["position","normal","uv"]);return Object.keys(t.attributes).forEach(r=>{s.has(r)||t.deleteAttribute(r)}),t}extractPlaneCapGeometry(e,t,i){const s=e.index?e.toNonIndexed():e.clone(),r=s.getAttribute("position");if(!r||r.count<3)return s.dispose(),null;const o=t.normal.clone().normalize(),a=new w.Vector3,l=new w.Vector3,c=new w.Vector3,h=new w.Vector3,u=new w.Vector3,f=new w.Vector3,d=new w.Vector3,p=new w.Vector3,g=new w.Vector3,m=Math.max(i*.35,1e-4),A=Math.max(i*.7,1e-4),x=[];for(let y=0;y<r.count;y+=3){if(h.fromBufferAttribute(r,y),u.fromBufferAttribute(r,y+1),f.fromBufferAttribute(r,y+2),l.subVectors(u,h),c.subVectors(f,h),a.crossVectors(l,c),a.lengthSq()<1e-14||(a.normalize(),Math.abs(a.dot(o))<.9))continue;const _=t.distanceToPoint(h),E=t.distanceToPoint(u),I=t.distanceToPoint(f),B=Math.min(_,E,I);if(Math.max(_,E,I)-B>m)continue;const S=(_+E+I)/3;Math.abs(S)>A||S<0||(d.copy(h).addScaledVector(o,-_),p.copy(u).addScaledVector(o,-E),g.copy(f).addScaledVector(o,-I),a.dot(o)<=0?(x.push(d.x,d.y,d.z),x.push(p.x,p.y,p.z),x.push(g.x,g.y,g.z)):(x.push(d.x,d.y,d.z),x.push(g.x,g.y,g.z),x.push(p.x,p.y,p.z)))}if(s.dispose(),x.length<9)return null;const b=new w.BufferGeometry;return b.setAttribute("position",new w.Float32BufferAttribute(x,3)),b.computeVertexNormals(),b}applyPlanarUv(e,t){const i=e.getAttribute("position");if(!i||i.count===0)return;const{tangent:s,bitangent:r}=this.getPlaneBasis(t.normal.clone().normalize()),o=new w.Vector3,a=new Float32Array(i.count*2);let l=1/0,c=-1/0,h=1/0,u=-1/0;for(let p=0;p<i.count;p++){o.fromBufferAttribute(i,p);const g=o.dot(s),m=o.dot(r),A=p*2;a[A]=g,a[A+1]=m,l=Math.min(l,g),c=Math.max(c,g),h=Math.min(h,m),u=Math.max(u,m)}const f=Math.max(c-l,1e-6),d=Math.max(u-h,1e-6);for(let p=0;p<a.length;p+=2)a[p]=(a[p]-l)/f*this.fillTextureRepeat,a[p+1]=(a[p+1]-h)/d*this.fillTextureRepeat;e.setAttribute("uv",new w.BufferAttribute(a,2))}getPlaneBasis(e){const t=new w.Vector3(1,0,0),i=new w.Vector3(0,1,0),s=new w.Vector3(0,0,1),r=Math.abs(e.dot(t)),o=Math.abs(e.dot(i)),a=Math.abs(e.dot(s));let l=t;o<=r&&o<=a?l=i:a<=r&&a<=o&&(l=s),l=l.clone().sub(e.clone().multiplyScalar(l.dot(e))).normalize();const c=new w.Vector3().crossVectors(e,l).normalize();return{tangent:l,bitangent:c}}}class AP{engine;clippingTolerance=1e-4;sectionBox;sectionFace;clippingStencil;clippingCSGSimple=null;currentClippingMode="";sectionCatchFace;fillCutFace=!0;constructor(e){this.engine=e,this.sectionCatchFace=new MD(this.engine);let t=new w.Plane(new w.Vector3(0,0,1),1e5);t.name="前";let i=new w.Plane(new w.Vector3(0,0,1),1e5);i.name="左";let s=new w.Plane(new w.Vector3(0,0,1),1e5);s.name="后";let r=new w.Plane(new w.Vector3(0,0,1),1e5);r.name="右";let o=new w.Plane(new w.Vector3(0,0,1),1e5);o.name="顶";let a=new w.Plane(new w.Vector3(0,0,1),1e5);a.name="底";let l=new w.Plane(new w.Vector3(0,0,1),1e5);l.name="face",this.engine.sectionPlane=[t,i,s,r,o,a,l]}init(){this.sectionBox=new SD(this.engine),this.sectionFace=new CD(this.engine),this.clippingCSGSimple=new mP(this.engine)}scaleBox(){let e=this.engine.octreeBox.getBoundingBox();this.sectionBox.setBox(e)}setFillCutFace(e){this.fillCutFace=e}getFillCutFace(){return this.fillCutFace}clippingModel(e){let t=[];e.forEach(r=>{let o=this.engine.models.find(a=>a.url===r.url);r.ids.forEach(a=>{o.nodesMap.get(a).infos.forEach(l=>{t.push(l.box)})})}),this.active("box");let i=s(t);this.sectionBox.setBox(i);function s(r){let o=new w.Vector3(1e8,1e9,1e10),a=new w.Vector3(-1e8,-1e9,-1e10);return r.forEach(l=>{l.min.x<o.x&&(o.x=l.min.x),l.min.y<o.y&&(o.y=l.min.y),l.min.z<o.z&&(o.z=l.min.z),l.max.x>a.x&&(a.x=l.max.x),l.max.y>a.y&&(a.y=l.max.y),l.max.z>a.z&&(a.z=l.max.z)}),new w.Box3(o,a)}}updateClippingValue(e){let t=this.sectionBox.maxBox,i=t.min.x+(t.max.x-t.min.x)*e.x.min*.01,s=t.min.y+(t.max.y-t.min.y)*e.y.min*.01,r=t.min.z+(t.max.z-t.min.z)*e.z.min*.01,o=t.min.x+(t.max.x-t.min.x)*e.x.max*.01,a=t.min.y+(t.max.y-t.min.y)*e.y.max*.01,l=t.min.z+(t.max.z-t.min.z)*e.z.max*.01;this.sectionBox.setboxXyz({minX:i,minY:s,minZ:r,maxX:o,maxY:a,maxZ:l})}active(e){this.engine.engineStatus.isForceFree=!0,this.sectionFace.disActive(),this.sectionBox.disActive(),this.sectionCatchFace.cancel(),this.currentClippingMode=e,e=="x"?(this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(-1,0,0))):e=="y"?(this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(0,0,-1))):e=="z"?(this.sectionFace.init(),this.sectionFace.active(),this.sectionFace.setFaceNormal(new w.Vector3(0,-1,0))):e=="box"?(this.sectionBox.init(),this.sectionBox.active()):e=="face"&&(this.sectionCatchFace.init(),this.sectionCatchFace.catch_face(t=>{this.sectionFace.init(),this.sectionFace.active();let i=this.engine.octreeBox.getBoundingBox(),s=i.min.clone().add(i.max.clone()).multiplyScalar(.5),r=t.position.clone().sub(s),o=new w.Vector3(t.dir.x,t.dir.y,t.dir.z),a=r.dot(o);this.sectionFace.setFaceNormal(t.dir,a)}))}disabled(){this.currentClippingMode=="box"?this.sectionBox.disabled():this.sectionFace.disabled(),this.engine.engineStatus.isForceFree=!1}recover(){this.currentClippingMode=="box"?this.sectionBox.recover():this.sectionFace.recover()}reverse(){this.sectionFace.reverse()}disActive(){this.sectionFace.disActive(),this.sectionBox.disActive(),this.clippingCSGSimple?.clear(),this.sectionCatchFace.cancel(),this.currentClippingMode="",this.engine.engineStatus.isForceFree=!1}isPointInClippingRange(e,t=this.clippingTolerance){if(!this.isVector3Like(e))return!1;const i=this.getEffectiveClippingPlanes();return i.length===0?!0:i.every(s=>s.distanceToPoint(e)>=-t)}filterIntersectionsByClipping(e,t=this.clippingTolerance){return!Array.isArray(e)||e.length===0?[]:e.filter(i=>this.isPointInClippingRange(i?.point,t))}getEffectiveClippingPlanes(){const e=Array.isArray(this.engine.sectionPlane)?this.engine.sectionPlane:[];if(this.currentClippingMode==="box")return e.slice(0,6).filter(t=>t instanceof w.Plane);if(this.currentClippingMode==="x"||this.currentClippingMode==="y"||this.currentClippingMode==="z"||this.currentClippingMode==="face"){const t=e[6];return t instanceof w.Plane?[t]:[]}return[]}isVector3Like(e){return e!=null&&typeof e.x=="number"&&typeof e.y=="number"&&typeof e.z=="number"}setSectionByView(e,t){this.sectionFace.disActive(),this.sectionBox.disActive(),this.scaleBox(),this.sectionFace.init(!0);const i=this.engine.octreeBox.getBoundingBox(),s=new w.Vector3((i.min.x+i.max.x)/2,(i.min.y+i.max.y)/2,(i.min.z+i.max.z)/2),o=new w.Vector3(t.x,t.y,t.z).normalize().clone().negate(),l=new w.Vector3(e.x,e.y,e.z).clone().sub(s).dot(o);this.sectionFace.setFaceNormalPlaneOnly(o,l),this.sectionFace.activateClippingOnly(),this.currentClippingMode="face"}}class xP{engine;constructor(e){this.engine=e}getLevelTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeLevel,name:t.info.baseInfo.name,url:t.url})}),e}getTypeTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeType,name:t.info.baseInfo.name,url:t.url})}),e}getMajorTreeData(){let e=[];return this.engine.engineStatus.models.forEach(t=>{e.push({children:t.info.modelTree.modelTreeMajor,name:t.info.baseInfo.name,url:t.url})}),e}}class bP{engine;constructor(e){this.engine=e}getEngineInfo(){let e=0,t=0,i=0;return!this.engine||!this.engine.scene?{totalVertices:0,totalTriangles:0,meshCount:0}:(this.engine.scene.traverse(s=>{if(s instanceof w.Mesh){const r=s.geometry;if(r&&r.attributes){const o=r.attributes.position;if(o){const a=o.count;e+=a;let l=0;r.index?l=r.index.count/3:l=a/3,t+=l}}}}),this.engine.engineStatus.models.forEach(s=>{i=i+(Array.isArray(s?.info?.modelEdge)?s.info.modelEdge.length:0)}),{totalVertices:Math.floor(e),totalTriangles:Math.floor(t),meshCount:i})}}class yP{engine;extended‌=new Map;constructor(e){this.engine=e}init(){}updateExtended(e,t){let i=this.extended‌.get(e);i==null?this.extended‌.set(e,t):t.forEach((s,r)=>{i.set(r,s)})}getModelPropertiesWithName(e,t,i,s){let r=this.extended‌.get(e),o=this.engine.engineStatus.models.find(l=>l.url===e);o.properties==null?pa(e+"/property",l=>{let c=JSON.parse(l);o.properties=c,setTimeout(()=>{a(c,i,t,s)},100)},()=>{},o?.key):a(o.properties,i,t,s);function a(l,c,h,u){let f={};l.models[h.toString()||""].forEach(p=>{i.includes(l.names[p[1]])&&(f[l.names[p[1]]]=l.values[p[2]])}),r!=null&&r.has(h)&&f.push(r.get(h)),u?.({id:h,properties:f})}}getModelProperties(e,t,i){let s=this.extended‌.get(e),r=this.engine.engineStatus.models.find(a=>a.url===e);r.properties==null&&pa(e+"/property",a=>{let l=JSON.parse(a);r.properties=l,setTimeout(()=>{o(l,t,i)},100)},()=>{},r?.key),o(r.properties,t,i);function o(a,l,c){let h=[],u=a.models[l.toString()||""],f=u.map(p=>p[0]);f=f.filter((p,g)=>f.indexOf(p)===g),f.forEach(p=>{let g={name:a.categorys[p],children:[]};h.push(g),u.filter(m=>m[0]===p).forEach(m=>{g.children.push({name:a.names[m[1]],value:a.values[m[2]]})})}),s!=null&&s.has(l)&&h.push(s.get(l));const d={基础数据:0,基礎信息:0,标识数据:1,尺寸标注:2,文字:3,约束:4,阶段化:5,结构:6,图形:7,材质和装饰:8,构造:9,分析属性:10,其他:11,基礎資料:0,識別資料:1,尺寸:2,文字:3,約束:4,階段:5,結構:6,圖形:7,材料及飾面:8,構造:9,分析性質:10,其他:11};h.sort((p,g)=>{const m=d[p.name]??99,A=d[g.name]??99;return m-A}),c?.({properties:h,materials:h})}}}class vP{engine;constructor(e){this.engine=e}getModelTypes(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.typeName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelMajors(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.majorName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelLevels(){let e=[];return this.engine.engineStatus.models.forEach(t=>{t.info.modelMapper.forEach(s=>{e.push(s.levelName)})}),e=e.filter((t,i,s)=>s.indexOf(t)===i),e}getModelMappers(e){}getModelMapper(e,t){let i=this.engine.engineStatus.models.find(o=>o.url==e);return i?i.info.modelMapper.find(o=>o.id==t):null}getModelsWithLevelType(e,t,i=null){let s=[];return this.engine.engineStatus.models.forEach(r=>{let o={url:r.url,ids:[]};s.push(o),r.info.modelMapper.filter(l=>l.levelName===e&&l.typeName===t).forEach(l=>{o.ids.push(Number(l.id))})}),i&&i(s),s}getModelsWithType(e,t=null){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.typeName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithLevel(e,t){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.levelName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}getModelsWithMajor(e,t){let i=[];return this.engine.engineStatus.models.forEach(s=>{let r={url:s.url,ids:[]};i.push(r),s.info.modelMapper.filter(a=>a.majorName===e).forEach(a=>{r.ids.push(Number(a.id))})}),t&&t(i),i}}class _P{config;constructor(e){this.config={temperature:.7,maxTokens:2e4,timeout:3e5,...e}}async chat(e){const t=new AbortController,i=setTimeout(()=>t.abort(),this.config.timeout);try{const s=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!1}),signal:t.signal});if(clearTimeout(i),!s.ok){const o=await s.json().catch(()=>({}));throw new Error(`API请求失败 (${s.status}): ${o.error?.message||o.message||s.statusText}`)}return(await s.json()).choices?.[0]?.message?.content||""}catch(s){throw clearTimeout(i),s.name==="AbortError"?new Error("请求超时,请重试"):s.message.includes("Failed to fetch")?new Error(`网络请求失败,请检查:
5261
5261
  1. 网络连接
5262
5262
  2. API地址是否正确
5263
5263
  3. 是否有CORS限制`):s}}async chatStream(e,t){const i=new AbortController,s=setTimeout(()=>i.abort(),this.config.timeout);try{const r=await fetch(`${this.config.baseURL}/chat/completions`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.config.apiKey}`},body:JSON.stringify({model:this.config.model,messages:e,temperature:this.config.temperature,max_tokens:this.config.maxTokens,stream:!0}),signal:i.signal});if(clearTimeout(s),!r.ok){const c=await r.json().catch(()=>({}));throw new Error(`API请求失败 (${r.status}): ${c.error?.message||c.message||r.statusText}`)}const o=r.body?.getReader();if(!o)throw new Error("无法读取响应流");const a=new TextDecoder;let l="";for(;;){const{done:c,value:h}=await o.read();if(c){t("",!0);break}l+=a.decode(h,{stream:!0});const u=l.split(`
@@ -6053,7 +6053,7 @@ void main() {
6053
6053
  color.b += max != color.b ? (max - color.b) * amt : 0.00;
6054
6054
  gl_FragColor = color;
6055
6055
  }
6056
- `}applyTo2d({imageData:{data:n}}){let e=-this.vibrance;for(let t=0;t<n.length;t+=4){let i=n[t],s=n[t+1],r=n[t+2],o=Math.max(i,s,r),a=(i+s+r)/3,l=2*Math.abs(o-a)/255*e;n[t]+=o===i?0:(o-i)*l,n[t+1]+=o===s?0:(o-s)*l,n[t+2]+=o===r?0:(o-r)*l}}sendUniformData(n,e){n.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}};K(gl,"type","Vibrance"),K(gl,"defaults",{vibrance:0}),K(gl,"uniformLocations",["uVibrance"]),ke.setClass(gl),Oa({BaseFilter:()=>Nt,BlackWhite:()=>pR,BlendColor:()=>tl,BlendImage:()=>il,Blur:()=>nl,Brightness:()=>sl,Brownie:()=>lR,ColorMatrix:()=>Rr,Composed:()=>ig,Contrast:()=>rl,Convolute:()=>ol,Gamma:()=>al,Grayscale:()=>ll,HueRotation:()=>jh,Invert:()=>cl,Kodachrome:()=>hR,Noise:()=>hl,Pixelate:()=>ul,Polaroid:()=>dR,RemoveColor:()=>dl,Resize:()=>fl,Saturation:()=>pl,Sepia:()=>fR,Technicolor:()=>uR,Vibrance:()=>gl,Vintage:()=>cR});function xR(n,e,t="bim-snapshot.png"){const i=n?.renderer,s=i?.domElement;if(!i||!s||!e)return null;const r=s.width||s.clientWidth,o=s.height||s.clientHeight;if(r<=0||o<=0)return null;let a=bR(s,r,o);if(!yR(a)){const f=vR(n,r,o);f&&(a=f)}const l=document.createElement("canvas");l.width=r,l.height=o;const c=l.getContext("2d");if(!c)return null;c.drawImage(a,0,0,r,o),c.drawImage(e,0,0,r,o);const h=l.toDataURL("image/png"),u=document.createElement("a");return u.href=h,u.download=t.toLowerCase().endsWith(".png")?t:`${t}.png`,u.click(),h}function bR(n,e,t){const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");return s&&s.drawImage(n,0,0,e,t),i}function yR(n){const e=n.getContext("2d");if(!e||n.width<=0||n.height<=0)return!1;const t=Math.min(32,n.width),i=Math.min(32,n.height),s=Math.max(1,Math.floor(n.width/t)),r=Math.max(1,Math.floor(n.height/i));for(let o=0;o<n.height;o+=r)for(let a=0;a<n.width;a+=s){const l=e.getImageData(a,o,1,1).data;if(l[0]!==0||l[1]!==0||l[2]!==0||l[3]!==0)return!0}return!1}function vR(n,e,t){const i=n?.renderer,s=n?.scene,r=n?.camera;if(!i||!s||!r)return null;const o=new w.WebGLRenderTarget(e,t,{minFilter:w.LinearFilter,magFilter:w.LinearFilter,format:w.RGBAFormat,depthBuffer:!0,stencilBuffer:!0}),a=i.getRenderTarget(),l=i.autoClear,c=i.xr?.enabled??!1;try{i.xr&&(i.xr.enabled=!1),i.autoClear=!0,i.setRenderTarget(o),i.clear(!0,!0,!0),i.render(s,r);const h=new Uint8Array(e*t*4);return i.readRenderTargetPixels(o,0,0,e,t,h),_R(h,e,t)}catch{return null}finally{i.setRenderTarget(a),i.autoClear=l,i.xr&&(i.xr.enabled=c),o.dispose()}}function _R(n,e,t){const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)return i;const r=s.createImageData(e,t),o=e*4;for(let a=0;a<t;a++){const l=(t-1-a)*o,c=a*o;for(let h=0;h<o;h++)r.data[c+h]=n[l+h]}return s.putImageData(r,0,0),i}const wR=["#ffffff","#000000","#ff4d4f","#fa8c16","#fadb14","#52c41a","#13c2c2","#1677ff","#722ed1","#eb2f96"],SR={none:new URL("/assets/icon/%E9%80%89%E6%8B%A9.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,line:new URL("/assets/icon/%E7%BA%BF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,arrow:new URL("/assets/icon/%E7%AE%AD%E5%A4%B4.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,rect:new URL("/assets/icon/%E7%9F%A9%E5%BD%A2.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,circle:new URL("/assets/icon/%E5%9C%86%E5%BD%A2.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,text:new URL("/assets/icon/%E6%96%87%E5%AD%97.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,cloudline:new URL("/assets/icon/%E4%BA%91%E7%BA%BF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href},CR=new URL("/assets/icon/%E6%B5%8B%E8%B7%9D.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,MR=new URL("/assets/icon/%E6%88%AA%E5%9B%BE.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,ER=new URL("/assets/icon/%E7%BA%BF%E5%AE%BD.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,IR=new URL("/assets/icon/%E5%AD%97%E5%8F%B7.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,TR=[{type:"distance",label:"距离"},{type:"clearDistance",label:"净距"},{type:"clearHeight",label:"净高"},{type:"elevation",label:"标高"},{type:"point",label:"坐标"},{type:"angle",label:"角度"},{type:"area",label:"面积"},{type:"slope",label:"坡度"}],DR={distance:new URL("/assets/icon/%E8%B7%9D%E7%A6%BB.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,clearDistance:new URL("/assets/icon/%E5%87%80%E8%B7%9D.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,clearHeight:new URL("/assets/icon/%E5%87%80%E9%AB%98.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,elevation:new URL("/assets/icon/%E6%A0%87%E9%AB%98.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,point:new URL("/assets/icon/%E5%9D%90%E6%A0%87.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,angle:new URL("/assets/icon/%E8%A7%92%E5%BA%A6.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,area:new URL("/assets/icon/%E9%9D%A2%E7%A7%AF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,slope:new URL("/assets/icon/%E5%9D%A1%E5%BA%A6.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href};class BR{constructor(e,t){this.handlers=e,this.root=document.createElement("div"),this.root.style.position="absolute",this.root.style.top="8px",this.root.style.left="50%",this.root.style.transform="translateX(-50%)",this.root.style.display="none",this.root.style.padding="6px",this.root.style.background="#ffffff",this.root.style.border="1px solid #d9d9d9",this.root.style.borderRadius="8px",this.root.style.pointerEvents="auto",this.root.style.userSelect="none",this.root.style.boxShadow="0 4px 14px rgba(0, 0, 0, 0.12)",this.root.style.zIndex="1300",this.root.style.overflow="visible",this.editPanel=document.createElement("div"),this.editPanel.style.display="flex",this.editPanel.style.flexDirection="column",this.editPanel.style.gap="6px",this.viewPanel=document.createElement("div"),this.viewPanel.style.display="none",this.viewPanel.style.alignItems="center",this.viewPanel.style.gap="6px";const i=document.createElement("div");i.style.display="flex",i.style.alignItems="center",i.style.gap="6px",i.style.flexWrap="wrap",[{type:"none",label:"选择"},{type:"line",label:"线"},{type:"arrow",label:"箭头"},{type:"rect",label:"矩形"},{type:"circle",label:"圆形"},{type:"text",label:"文字"},{type:"cloudline",label:"云线"}].forEach(d=>{const p=this.createIconButton(d.label,SR[d.type]);p.onclick=()=>this.handlers.onDrawTypeChange(d.type),this.drawButtons[d.type]=p,i.appendChild(p)});const r=document.createElement("div");r.style.position="relative",r.style.display="flex",r.style.alignItems="center",this.colorTrigger=document.createElement("button"),this.colorTrigger.type="button",this.colorTrigger.title="颜色",this.colorTrigger.style.width="32px",this.colorTrigger.style.height="24px",this.colorTrigger.style.padding="2px",this.colorTrigger.style.border="1px solid #d9d9d9",this.colorTrigger.style.borderRadius="4px",this.colorTrigger.style.background="#ffffff",this.colorTrigger.style.cursor="pointer",this.colorTrigger.style.display="flex",this.colorTrigger.style.alignItems="center",this.colorTrigger.style.justifyContent="center",this.colorTrigger.onclick=()=>this.setColorPresetVisible(!this.isColorPresetOpen);const o=document.createElement("span");o.style.display="block",o.style.width="100%",o.style.height="100%",o.style.borderRadius="2px",o.style.border="1px solid rgba(0, 0, 0, 0.12)",this.colorTrigger.appendChild(o),r.appendChild(this.colorTrigger),this.colorInput=document.createElement("input"),this.colorInput.type="color",this.colorInput.value=t.stroke,this.colorInput.style.position="absolute",this.colorInput.style.width="1px",this.colorInput.style.height="1px",this.colorInput.style.opacity="0",this.colorInput.style.pointerEvents="none",this.colorInput.style.left="0",this.colorInput.style.top="0",this.colorInput.tabIndex=-1,this.colorInput.oninput=()=>{this.updateColorControl(this.colorInput.value),this.handlers.onColorChange(this.colorInput.value),this.setColorPresetVisible(!1)},r.appendChild(this.colorInput),this.colorPresetPanel=document.createElement("div"),this.colorPresetPanel.style.position="absolute",this.colorPresetPanel.style.top="30px",this.colorPresetPanel.style.left="0",this.colorPresetPanel.style.display="none",this.colorPresetPanel.style.padding="8px",this.colorPresetPanel.style.background="#ffffff",this.colorPresetPanel.style.border="1px solid #d9d9d9",this.colorPresetPanel.style.borderRadius="6px",this.colorPresetPanel.style.boxShadow="0 6px 18px rgba(0, 0, 0, 0.14)",this.colorPresetPanel.style.zIndex="20",this.colorPresetPanel.style.width="152px";const a=document.createElement("div");a.style.display="grid",a.style.gridTemplateColumns="repeat(5, 1fr)",a.style.gap="6px",wR.forEach(d=>{const p=document.createElement("button");p.type="button",p.title=d,p.style.width="22px",p.style.height="22px",p.style.padding="0",p.style.border="1px solid #d9d9d9",p.style.borderRadius="4px",p.style.background=d,p.style.cursor="pointer",p.onclick=()=>{this.updateColorControl(d),this.handlers.onColorChange(d),this.setColorPresetVisible(!1)},a.appendChild(p)}),this.colorPresetPanel.appendChild(a);const l=document.createElement("button");l.type="button",l.textContent="自定义",l.style.marginTop="8px",l.style.width="100%",l.style.height="26px",l.style.border="1px solid #d9d9d9",l.style.borderRadius="4px",l.style.background="#ffffff",l.style.color="#333333",l.style.cursor="pointer",l.onclick=()=>this.openNativeColorPicker(),this.colorPresetPanel.appendChild(l),r.appendChild(this.colorPresetPanel),this.updateColorControl(t.stroke),i.appendChild(this.createField("",r)),this.strokeWidthInput=document.createElement("input"),this.strokeWidthInput.type="number",this.strokeWidthInput.min="1",this.strokeWidthInput.max="20",this.strokeWidthInput.step="1",this.strokeWidthInput.value=String(t.strokeWidth),this.strokeWidthInput.style.width="46px",this.strokeWidthInput.oninput=()=>this.handlers.onStrokeWidthChange(this.strokeWidthInput.value),i.appendChild(this.createField("",this.strokeWidthInput,ER,"线宽")),this.fontSizeInput=document.createElement("input"),this.fontSizeInput.type="number",this.fontSizeInput.min="10",this.fontSizeInput.max="96",this.fontSizeInput.step="1",this.fontSizeInput.value=String(t.fontSize),this.fontSizeInput.style.width="46px",this.fontSizeInput.oninput=()=>this.handlers.onFontSizeChange(this.fontSizeInput.value),i.appendChild(this.createField("",this.fontSizeInput,IR,"字号")),this.distanceButton=this.createIconButton("测量",CR),this.distanceButton.onclick=()=>this.handlers.onMeasureToggle(),i.appendChild(this.distanceButton);const c=this.createIconButton("截图",MR);c.onclick=()=>this.handlers.onScreenshot(),i.appendChild(c);const h=this.createTextButton("×","取消");h.onclick=()=>this.handlers.onCancel(),h.style.background="#ff4d4f",h.style.borderColor="#ff4d4f",h.style.color="#ffffff",i.appendChild(h);const u=this.createTextButton("✔","确定");u.onclick=()=>this.handlers.onConfirm(),u.style.background="#52c41a",u.style.borderColor="#52c41a",u.style.color="#ffffff",i.appendChild(u),this.measureSubPanel=document.createElement("div"),this.measureSubPanel.style.display="none",this.measureSubPanel.style.alignItems="center",this.measureSubPanel.style.gap="6px",this.measureSubPanel.style.flexWrap="wrap",this.measureSubPanel.style.paddingTop="2px",TR.forEach(d=>{const p=this.createSmallIconButton(d.label,DR[d.type]);p.onclick=()=>this.handlers.onMeasureTypeChange(d.type),this.measureTypeButtons[d.type]=p,this.measureSubPanel.appendChild(p)}),this.editPanel.appendChild(i),this.editPanel.appendChild(this.measureSubPanel);const f=this.createTextButton("关闭","关闭");f.onclick=()=>this.handlers.onClose(),this.viewPanel.appendChild(f),this.root.appendChild(this.editPanel),this.root.appendChild(this.viewPanel),this.disabledMask=document.createElement("div"),this.disabledMask.style.position="absolute",this.disabledMask.style.inset="0",this.disabledMask.style.display="none",this.disabledMask.style.background="rgba(255, 255, 255, 0.55)",this.disabledMask.style.backdropFilter="blur(1px)",this.disabledMask.style.cursor="not-allowed",this.disabledMask.style.pointerEvents="auto",this.disabledMask.style.zIndex="10",this.root.appendChild(this.disabledMask),document.addEventListener("pointerdown",this.onDocumentPointerDown),this.setMode("edit")}root;disabledMask;drawButtons={};measureTypeButtons={};distanceButton;colorTrigger;colorInput;colorPresetPanel;strokeWidthInput;fontSizeInput;editPanel;viewPanel;measureSubPanel;mode="edit";isEditPanelMasked=!1;isColorPresetOpen=!1;onDocumentPointerDown=e=>{const t=e.target;t&&this.root.contains(t)||this.setColorPresetVisible(!1)};mount(e){e.appendChild(this.root)}show(){this.root.style.display="block"}hide(){this.root.style.display="none"}setMode(e){this.mode=e,this.editPanel.style.display=e==="edit"?"flex":"none",this.viewPanel.style.display=e==="view"?"flex":"none",e==="view"&&(this.setMeasurePanelVisible(!1),this.setColorPresetVisible(!1)),this.applyEditPanelMaskState()}setEditPanelMasked(e){this.isEditPanelMasked=e,this.applyEditPanelMaskState()}setDrawType(e){for(const t in this.drawButtons){const i=this.drawButtons[t];if(!i)continue;const s=t===e;i.style.background=s?"#eaf2ff":"#ffffff",i.style.borderColor=s?"#2f80ed":"#d9d9d9"}}setMeasurePanelVisible(e){if(this.mode!=="edit"){this.measureSubPanel.style.display="none";return}this.measureSubPanel.style.display=e?"flex":"none"}setMeasureState(e,t){this.distanceButton.style.background=e?"#eaf2ff":"#ffffff",this.distanceButton.style.borderColor=e?"#2f80ed":"#d9d9d9";for(const i in this.measureTypeButtons){const s=this.measureTypeButtons[i];if(!s)continue;const r=e&&t===i;s.style.background=r?"#eaf2ff":"#ffffff",s.style.borderColor=r?"#2f80ed":"#d9d9d9"}}setStyleValues(e){e.stroke&&this.updateColorControl(e.stroke),typeof e.strokeWidth=="number"&&(this.strokeWidthInput.value=String(e.strokeWidth)),typeof e.fontSize=="number"&&(this.fontSizeInput.value=String(e.fontSize))}dispose(){this.colorInput.oninput=null,this.strokeWidthInput.oninput=null,this.fontSizeInput.oninput=null,document.removeEventListener("pointerdown",this.onDocumentPointerDown),this.root.remove()}applyEditPanelMaskState(){const e=this.mode==="edit"&&this.isEditPanelMasked;this.disabledMask.style.display=e?"block":"none",e&&this.setColorPresetVisible(!1),this.editPanel.querySelectorAll("button, input").forEach(i=>{const s=i;s.disabled=e})}createField(e,t,i,s=""){const r=document.createElement("div");if(r.style.display="flex",r.style.alignItems="center",r.style.gap="4px",r.style.padding="0 2px",r.style.color="#333333",r.style.fontSize="12px",e){const o=document.createElement("span");o.textContent=e,r.appendChild(o)}if(i){const o=document.createElement("img");o.src=i,o.alt=s,o.style.width="14px",o.style.height="14px",o.style.display="block",r.appendChild(o)}return t instanceof HTMLInputElement&&(t.style.height="24px",t.style.border="1px solid #d9d9d9",t.style.borderRadius="4px",t.style.background="#ffffff",t.style.color="#333333",t.style.outline="none",t.style.padding="0 4px"),r.appendChild(t),r}updateColorControl(e){this.colorInput.value=e;const t=this.colorTrigger.firstElementChild;t&&(t.style.background=e)}setColorPresetVisible(e){this.isColorPresetOpen=e,this.colorPresetPanel.style.display=e?"block":"none",this.colorTrigger.style.borderColor=e?"#2f80ed":"#d9d9d9"}openNativeColorPicker(){const e=this.colorInput;if(typeof e.showPicker=="function"){e.showPicker();return}e.click()}createIconButton(e,t){const i=document.createElement("button");i.type="button",i.style.width="28px",i.style.height="28px",i.style.padding="0",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.cursor="pointer";const s=document.createElement("img");return s.src=t,s.alt=e,s.style.width="16px",s.style.height="16px",s.style.display="block",i.appendChild(s),i}createSmallIconButton(e,t){const i=document.createElement("button");i.type="button",i.style.width="26px",i.style.height="26px",i.style.padding="0",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.cursor="pointer";const s=document.createElement("img");return s.src=t,s.alt=e,s.style.width="14px",s.style.height="14px",s.style.display="block",i.appendChild(s),i}createTextButton(e,t){const i=document.createElement("button");return i.type="button",i.title=t,i.textContent=e,i.style.width="28px",i.style.height="28px",i.style.padding="0 10px",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.color="#333333",i.style.fontSize="13px",i.style.lineHeight="1",i.style.cursor="pointer",i}}class PR{engine;wrapper;canvasEl;canvas;toolbar;isActive=!1;isVisible=!0;isViewLocked=!0;isDistanceMeasureMode=!1;isMeasurePanelExpanded=!1;drawType="none";mode="edit";currentMeasureType=null;sessionSnapshot=null;actionHandlers={};drawStyle={stroke:"#ff4d4f",strokeWidth:2,fill:"rgba(255, 77, 79, 0.08)",fontSize:16,text:"T",cloudRadius:10};startPoint=null;tempObject=null;cloudPoints=[];onMouseDown=e=>this.handleMouseDown(e);onMouseMove=e=>this.handleMouseMove(e);onMouseUp=e=>this.handleMouseUp(e);onMouseDblClick=e=>this.handleMouseDblClick(e);onSelectionChanged=()=>this.syncStyleFromSelection();onKeyDown=e=>this.handleKeyDown(e);constructor(e){this.engine=e;const t=this.engine.container;if(!t)throw new Error("FabricDraw: engine container not found.");this.wrapper=document.createElement("div"),this.wrapper.className="fabric-draw-layer",this.wrapper.style.position="absolute",this.wrapper.style.left="0",this.wrapper.style.top="0",this.wrapper.style.right="0",this.wrapper.style.bottom="0",this.wrapper.style.zIndex="1200",this.wrapper.style.pointerEvents="none",this.canvasEl=document.createElement("canvas"),this.canvasEl.style.width="100%",this.canvasEl.style.height="100%",this.wrapper.appendChild(this.canvasEl),this.toolbar=new BR({onDrawTypeChange:i=>this.setDrawType(i),onMeasureToggle:()=>this.toggleMeasurePanel(),onMeasureTypeChange:i=>this.activateDistanceMeasure(i),onScreenshot:()=>{this.saveScreenshot(this.createScreenshotFileName())},onColorChange:i=>this.handleColorInputChange(i),onStrokeWidthChange:i=>this.handleStrokeWidthInputChange(i),onFontSizeChange:i=>this.handleFontSizeInputChange(i),onCancel:()=>{this.handleCancelClick()},onConfirm:()=>this.handleConfirmClick(),onClose:()=>{this.handleCloseClick()}},{stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,fontSize:this.drawStyle.fontSize}),this.toolbar.mount(this.wrapper),t.appendChild(this.wrapper),this.canvas=new Xp(this.canvasEl,{selection:!0,preserveObjectStacking:!0}),this.resize(),this.canvas.on("mouse:down",this.onMouseDown),this.canvas.on("mouse:move",this.onMouseMove),this.canvas.on("mouse:up",this.onMouseUp),this.canvas.on("mouse:dblclick",this.onMouseDblClick),this.canvas.on("selection:created",this.onSelectionChanged),this.canvas.on("selection:updated",this.onSelectionChanged),this.canvas.on("selection:cleared",this.onSelectionChanged),window.addEventListener("keydown",this.onKeyDown),this.refreshToolbarState()}active(e="edit"){this.isActive=!0,this.mode=e,this.isViewLocked=!0,this.drawType="none",this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.canvas.defaultCursor="default",this.sessionSnapshot=e==="edit"?this.cloneJson(this.getAllShapes()):null,this.toolbar.setMode(e),this.applyCanvasInteractive(e==="edit"),this.isVisible&&this.toolbar.show(),this.updateOverlayPointerEvents(),this.refreshToolbarState()}disActive(){this.isActive=!1,this.isViewLocked=!0,this.startPoint=null,this.cloudPoints=[],this.tempObject=null,this.drawType="none",this.mode="edit",this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.sessionSnapshot=null,this.stopDistanceMeasureMode(),this.canvas.defaultCursor="default",this.canvas.discardActiveObject(),this.applyCanvasInteractive(!0),this.canvas.requestRenderAll(),this.toolbar.setMode("edit"),this.toolbar.hide(),this.updateOverlayPointerEvents(),this.refreshToolbarState()}close(){this.disActive()}hide(){this.isVisible=!1,this.wrapper.style.display="none",this.toolbar.hide()}show(){this.isVisible=!0,this.wrapper.style.display="block",this.isActive&&this.toolbar.show(),this.resize()}isShown(){return this.isVisible}setDrawType(e,t){this.mode!=="view"&&(this.stopDistanceMeasureMode(),this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.drawType=e,t&&(this.drawStyle={...this.drawStyle,...t}),this.canvas.defaultCursor=e==="none"?"default":"crosshair",this.updateOverlayPointerEvents(),this.refreshToolbarState())}getDrawType(){return this.drawType}setActionHandlers(e){this.actionHandlers={...e}}drawLine(e,t,i){const s=this.mergeStyle(i),r=this.createLineObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawArrow(e,t,i){const s=this.mergeStyle(i),r=this.createArrowObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawRect(e,t,i){const s=this.mergeStyle(i),r=this.createRectObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawCircle(e,t,i){const s=this.mergeStyle(i),r=this.createCircleObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawText(e,t,i){const s=this.mergeStyle(i),r=new Pr(t??s.text,{left:e.x,top:e.y,...this.createTextStyle(s),selectable:!0,evented:!0,objectCaching:!1});return r.annotationType="text",this.canvas.add(r),this.canvas.requestRenderAll(),r}drawCloudLine(e,t){if(e.length<2)return null;const i=this.mergeStyle(t),s=this.createCloudObject(e,i,!0);return s?(this.canvas.add(s),this.canvas.requestRenderAll(),s):null}getAllShapes(){return this.canvas.toObject(["annotationType"])}clearAllShapes(){this.canvas.clear(),this.canvas.requestRenderAll()}async restoreAllShapes(e){await this.canvas.loadFromJSON(e),this.canvas.requestRenderAll()}saveScreenshot(e="bim-snapshot.png"){const t=this.canvas.lowerCanvasEl;return t?xR(this.engine,t,e):null}resize(e,t){const i=this.engine.container;if(!i)return;const s=e??i.clientWidth??1,r=t??i.clientHeight??1;this.canvas.setDimensions({width:s,height:r}),this.canvas.requestRenderAll()}dispose(){this.stopDistanceMeasureMode(),window.removeEventListener("keydown",this.onKeyDown),this.canvas.off("mouse:down",this.onMouseDown),this.canvas.off("mouse:move",this.onMouseMove),this.canvas.off("mouse:up",this.onMouseUp),this.canvas.off("mouse:dblclick",this.onMouseDblClick),this.canvas.off("selection:created",this.onSelectionChanged),this.canvas.off("selection:updated",this.onSelectionChanged),this.canvas.off("selection:cleared",this.onSelectionChanged),this.toolbar.dispose(),this.canvas.dispose(),this.wrapper.remove()}handleMouseDown(e){if(!this.isActive||this.mode==="view"||!this.isViewLocked||this.drawType==="none"||e?.target)return;const t=this.getPointFromEvent(e);if(this.drawType==="text"){const s=this.drawText(t);this.canvas.setActiveObject(s),this.canvas.requestRenderAll(),setTimeout(()=>{s.enterEditing(),s.hiddenTextarea?.focus(),s.selectAll()},0);return}this.startPoint=t,this.cloudPoints=[t],this.canvas.selection=!1,this.canvas.discardActiveObject();const i=this.createDraftObject(t,t);i&&(this.tempObject=i,this.canvas.add(i),this.canvas.requestRenderAll())}handleMouseMove(e){if(!this.isActive||this.mode==="view"||!this.isViewLocked||!this.startPoint||!this.tempObject)return;const t=this.getPointFromEvent(e),i=this.drawStyle;if(this.drawType==="cloudline"){if(this.shouldAppendCloudPoint(t)){this.cloudPoints.push(t),this.canvas.remove(this.tempObject);const s=this.createCloudObject(this.cloudPoints,i,!1);if(!s)return;this.tempObject=s,this.canvas.add(s),this.canvas.requestRenderAll()}return}if(this.drawType==="arrow"){this.canvas.remove(this.tempObject),this.tempObject=this.createArrowObject(this.startPoint,t,i,!1),this.canvas.add(this.tempObject),this.canvas.requestRenderAll();return}this.updateDraftObject(this.startPoint,t),this.canvas.requestRenderAll()}handleMouseUp(e){if(!this.isActive||this.mode==="view"||!this.isViewLocked||!this.startPoint)return;const t=this.getPointFromEvent(e);this.drawType==="cloudline"&&this.cloudPoints.length===1&&(this.cloudPoints.push(t),this.canvas.remove(this.tempObject),this.tempObject=this.createCloudObject(this.cloudPoints,this.drawStyle,!0),this.tempObject&&this.canvas.add(this.tempObject)),this.tempObject&&(this.tempObject.set({selectable:!0,evented:!0}),this.tempObject.setCoords?.(),this.canvas.requestRenderAll()),this.startPoint=null,this.tempObject=null,this.cloudPoints=[],this.canvas.selection=!0}handleMouseDblClick(e){const t=e?.target;this.isTextObject(t)&&(t.enterEditing(),t.hiddenTextarea?.focus(),t.selectAll?.())}handleKeyDown(e){if(!this.isActive)return;const t=this.canvas.getActiveObject();if(this.isTextObject(t)&&t?.isEditing||this.isInputElement(e.target))return;if(e.key==="Control"&&!e.repeat){this.toggleViewLock();return}if(e.key==="Escape"){e.preventDefault(),this.mode==="view"?this.handleCloseClick():this.handleCancelClick();return}if(e.key==="Enter"){this.mode==="edit"&&(e.preventDefault(),this.handleConfirmClick());return}if(e.key!=="Delete"&&e.key!=="Backspace"||!t)return;e.preventDefault(),this.canvas.getActiveObjects().forEach(r=>this.canvas.remove(r)),this.canvas.discardActiveObject(),this.canvas.requestRenderAll()}getPointFromEvent(e){if(e?.e){const i=this.canvas.getScenePoint(e.e);return{x:i.x,y:i.y}}const t=e?.scenePoint??e?.pointer??e?.absolutePointer;return t?{x:t.x,y:t.y}:{x:0,y:0}}shouldAppendCloudPoint(e){if(this.cloudPoints.length===0)return!0;const t=this.cloudPoints[this.cloudPoints.length-1],i=e.x-t.x,s=e.y-t.y;return Math.sqrt(i*i+s*s)>=6}createDraftObject(e,t){const i=this.drawStyle;switch(this.drawType){case"line":return this.createLineObject(e,t,i,!1);case"arrow":return this.createArrowObject(e,t,i,!1);case"rect":return this.createRectObject(e,t,i,!1);case"circle":return this.createCircleObject(e,t,i,!1);case"cloudline":return this.createCloudObject([e,t],i,!1);default:return null}}updateDraftObject(e,t){if(this.tempObject){if(this.drawType==="line"){this.tempObject.set({x2:t.x,y2:t.y});return}if(this.drawType==="rect"){const i=this.getBoxFromPoints(e,t);this.tempObject.set({left:i.left,top:i.top,width:i.width,height:i.height});return}if(this.drawType==="circle"){const i=this.getCircleFromPoints(e,t);this.tempObject.set({left:i.left,top:i.top,radius:i.radius})}}}mergeStyle(e){return{...this.drawStyle,...e??{}}}createObjectBase(e,t){return{stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,selectable:t,evented:t,objectCaching:!1}}createLineObject(e,t,i,s){const r=new Qs([e.x,e.y,t.x,t.y],{...this.createObjectBase(i,s),fill:"",strokeLineCap:"round"});return r.annotationType="line",r}createRectObject(e,t,i,s){const r=this.getBoxFromPoints(e,t),o=new zs({...this.createObjectBase(i,s),left:r.left,top:r.top,width:r.width,height:r.height,originX:"left",originY:"top"});return o.annotationType="rect",o}createCircleObject(e,t,i,s){const r=this.getCircleFromPoints(e,t),o=new Br({...this.createObjectBase(i,s),left:r.left,top:r.top,radius:r.radius,originX:"left",originY:"top"});return o.annotationType="circle",o}createArrowObject(e,t,i,s){const r=t.x-e.x,o=t.y-e.y,a=Math.sqrt(r*r+o*o);if(a<1e-6){const B=new Qs([e.x,e.y,t.x,t.y],{stroke:i.stroke,strokeWidth:i.strokeWidth,fill:"",selectable:s,evented:s}),C=new Gs([B],{selectable:s,evented:s,objectCaching:!1});return C.annotationType="arrow",C}const l=r/a,c=o/a,h=-c,u=l,f=Math.max(10,i.strokeWidth*6),d=f*.72,p=t.x-l*f,g=t.y-c*f,m=p+h*(d*.5),A=g+u*(d*.5),x=p-h*(d*.5),b=g-u*(d*.5),y=new Qs([e.x,e.y,t.x,t.y],{stroke:i.stroke,strokeWidth:i.strokeWidth,fill:"",strokeLineCap:"round",selectable:!1,evented:!1}),_=`M ${t.x} ${t.y} L ${m} ${A} L ${x} ${b} Z`,E=new Dr(_,{fill:i.stroke,stroke:i.stroke,strokeWidth:1,selectable:!1,evented:!1,objectCaching:!1}),I=new Gs([y,E],{selectable:s,evented:s,objectCaching:!1});return I.annotationType="arrow",I}createCloudObject(e,t,i){const s=this.buildCloudPath(e,t.cloudRadius);if(!s)return null;const r=new Dr(s,{stroke:t.stroke,strokeWidth:t.strokeWidth,fill:"",strokeLineCap:"round",strokeLineJoin:"round",selectable:i,evented:i});return r.annotationType="cloudline",r}getBoxFromPoints(e,t){return{left:Math.min(e.x,t.x),top:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}}getCircleFromPoints(e,t){const i=t.x-e.x,s=t.y-e.y,r=Math.max(Math.abs(i),Math.abs(s)),o=i>=0?e.x:e.x-r,a=s>=0?e.y:e.y-r;return{left:o,top:a,radius:Math.max(r/2,1)}}buildCloudPath(e,t){if(e.length<2)return"";const i=Math.max(2,t),s=i*1.4;let r=`M ${e[0].x} ${e[0].y}`,o=1;for(let a=1;a<e.length;a++){const l=e[a-1],c=e[a],h=c.x-l.x,u=c.y-l.y,f=Math.sqrt(h*h+u*u);if(f<.1)continue;const d=-u/f,p=h/f,g=Math.max(1,Math.round(f/s));for(let m=1;m<=g;m++){const A=m/g,x=l.x+h*A,b=l.y+u*A,y=o%2===0?-1:1,_=x+d*i*y,E=b+p*i*y;r+=` Q ${_} ${E} ${x} ${b}`,o++}}return r}handleColorInputChange(e){this.drawStyle.stroke=e||this.drawStyle.stroke,this.drawStyle.fill=this.colorToAlpha(this.drawStyle.stroke,.08),this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}handleStrokeWidthInputChange(e){const t=this.parseNumber(e,this.drawStyle.strokeWidth,1,20);this.drawStyle.strokeWidth=t,this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}handleFontSizeInputChange(e){const t=this.parseNumber(e,this.drawStyle.fontSize,1,200);this.drawStyle.fontSize=t,this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}applyCurrentStyleToSelection(){const e=this.canvas.getActiveObjects();e.length!==0&&(e.forEach(t=>this.applyStyleToObject(t)),this.canvas.requestRenderAll())}applyStyleToObject(e){if(!e)return;if(e.annotationType==="arrow"&&Array.isArray(e._objects)){e._objects.forEach(i=>{if(i?.type==="triangle"||i?.type==="path"){i.set({fill:this.drawStyle.stroke,stroke:this.drawStyle.stroke,strokeWidth:1});return}i?.set({stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,strokeLineCap:"round"})}),e.set({dirty:!0}),e.setCoords?.();return}if(this.isTextObject(e)){e.set({...this.createTextStyle(this.drawStyle),fontSize:this.drawStyle.fontSize}),e.setCoords?.();return}const t={stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth};e?.type==="line"||e?.type==="path"?t.fill="":t.fill=this.drawStyle.fill,e.set(t),e.setCoords?.()}syncStyleFromSelection(){const e=this.canvas.getActiveObject();if(!e)return;const t=this.readStyleFromObject(e);t.stroke&&(this.drawStyle.stroke=t.stroke,this.drawStyle.fill=this.colorToAlpha(t.stroke,.08)),typeof t.strokeWidth=="number"&&(this.drawStyle.strokeWidth=t.strokeWidth),typeof t.fontSize=="number"&&(this.drawStyle.fontSize=t.fontSize),this.refreshToolbarStyleValues()}readStyleFromObject(e){if(!e)return{};if(e.annotationType==="arrow"&&Array.isArray(e._objects)){const t=e._objects.find(i=>i?.type==="line")??e._objects[0];return{stroke:t?.stroke,strokeWidth:t?.strokeWidth}}return this.isTextObject(e)?{stroke:e.fill??this.drawStyle.stroke,fontSize:e.fontSize??this.drawStyle.fontSize}:{stroke:e.stroke??this.drawStyle.stroke,strokeWidth:e.strokeWidth??this.drawStyle.strokeWidth}}isTextObject(e){return e?e.type==="i-text"||e.type==="textbox"||e.annotationType==="text":!1}createTextStyle(e){return{fontSize:e.fontSize,fill:e.stroke,stroke:this.getTextOutlineColor(e.stroke),strokeWidth:3,strokeLineJoin:"round",paintFirst:"stroke"}}getTextOutlineColor(e){return this.isWhiteTextColor(e)?"#000000":"#ffffff"}isWhiteTextColor(e){const t=e.trim().toLowerCase();if(t==="#fff"||t==="#ffffff"||t==="white")return!0;const i=t.match(/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})/);if(i){const[,s,r,o]=i;return Number(s)>=245&&Number(r)>=245&&Number(o)>=245}return!1}isInputElement(e){const t=e;if(!t||!t.tagName)return!1;const i=t.tagName.toLowerCase();return i==="input"||i==="textarea"||!!t.isContentEditable}applyCanvasInteractive(e){this.canvas.selection=e,this.canvas.getObjects().forEach(t=>{t.set({selectable:e,evented:e}),t.setCoords?.()}),this.canvas.discardActiveObject(),this.canvas.requestRenderAll()}parseNumber(e,t,i,s){const r=Number(e);return Number.isFinite(r)?Math.min(s,Math.max(i,r)):t}colorToAlpha(e,t){const i=e.trim(),s=/^#([0-9a-fA-F]{3})$/.exec(i);if(s){const o=s[1],a=parseInt(o[0]+o[0],16),l=parseInt(o[1]+o[1],16),c=parseInt(o[2]+o[2],16);return`rgba(${a}, ${l}, ${c}, ${t})`}const r=/^#([0-9a-fA-F]{6})$/.exec(i);if(r){const o=r[1],a=parseInt(o.slice(0,2),16),l=parseInt(o.slice(2,4),16),c=parseInt(o.slice(4,6),16);return`rgba(${a}, ${l}, ${c}, ${t})`}return this.drawStyle.fill}toggleMeasurePanel(){!this.isActive||this.mode!=="edit"||(this.isMeasurePanelExpanded=!this.isMeasurePanelExpanded,this.refreshToolbarState())}activateDistanceMeasure(e){if(!this.isActive||this.mode!=="edit")return;this.drawType="none",this.canvas.defaultCursor="default",this.isDistanceMeasureMode=!0,this.isMeasurePanelExpanded=!0,this.currentMeasureType=e,this.canvas.discardActiveObject(),this.canvas.requestRenderAll();const t=this.engine.measure;t?.active?.(),this.disActiveMeasureTools(t),this.activeMeasureTool(t,e),this.updateOverlayPointerEvents(),this.refreshToolbarState()}stopDistanceMeasureMode(){if(!this.isDistanceMeasureMode)return;const e=this.engine.measure;this.disActiveMeasureTools(e),this.isDistanceMeasureMode=!1,this.currentMeasureType=null,this.updateOverlayPointerEvents(),this.refreshToolbarState()}disActiveMeasureTools(e){e?.distanceMeasure?.disActive?.(),e?.faceDistanceMeasure?.disActive?.(),e?.clearHeightMeasure?.disActive?.(),e?.elevationMeasure?.disActive?.(),e?.pointMeasure?.disActive?.(),e?.angleMeasure?.disActive?.(),e?.areaMeasure?.disActive?.(),e?.slopeMeasure?.disActive?.()}activeMeasureTool(e,t){const s={distance:"distanceMeasure",clearDistance:"faceDistanceMeasure",clearHeight:"clearHeightMeasure",elevation:"elevationMeasure",point:"pointMeasure",angle:"angleMeasure",area:"areaMeasure",slope:"slopeMeasure"}[t];s&&e?.[s]?.active?.()}updateOverlayPointerEvents(){if(!this.isActive){this.wrapper.style.pointerEvents="none",this.canvasEl.style.pointerEvents="none";return}if(this.mode==="view"||this.isDistanceMeasureMode||!this.isViewLocked){this.wrapper.style.pointerEvents="none",this.canvasEl.style.pointerEvents="none",this.toolbar.root.style.pointerEvents="auto";return}this.wrapper.style.pointerEvents="auto",this.canvasEl.style.pointerEvents="auto",this.toolbar.root.style.pointerEvents="auto"}toggleViewLock(){!this.isActive||this.mode!=="edit"||this.isDistanceMeasureMode||(this.isViewLocked=!this.isViewLocked,this.isViewLocked?this.canvas.selection=!0:(this.startPoint=null,this.tempObject=null,this.cloudPoints=[],this.canvas.discardActiveObject(),this.canvas.selection=!1),this.canvas.requestRenderAll(),this.updateOverlayPointerEvents(),this.refreshToolbarState())}async handleCancelClick(){this.sessionSnapshot&&await this.restoreAllShapes(this.cloneJson(this.sessionSnapshot)),this.actionHandlers.onCancel?.(),this.disActive()}async handleCloseClick(){this.disActive()}handleConfirmClick(){const e=this.cloneJson(this.getAllShapes());this.actionHandlers.onConfirm?.(e),this.disActive()}refreshToolbarStyleValues(){this.toolbar.setStyleValues({stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,fontSize:this.drawStyle.fontSize})}refreshToolbarState(){this.toolbar.setDrawType(this.drawType),this.toolbar.setMode(this.mode),this.toolbar.setMeasurePanelVisible(this.isMeasurePanelExpanded),this.toolbar.setMeasureState(this.isDistanceMeasureMode,this.currentMeasureType),this.toolbar.setEditPanelMasked(!this.isViewLocked),this.refreshToolbarStyleValues()}createScreenshotFileName(){const e=new Date,t=e.getFullYear(),i=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),r=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return`bim-snapshot-${t}${i}${s}-${r}${o}${a}.png`}cloneJson(e){return JSON.parse(JSON.stringify(e))}}class LR{engine;constructor(e){this.engine=e}get(){return{cameraPose:this.engine.cameraModule?.getCameraPose?.()??null,clipping:this.captureClippingState(),measureData:this.captureMeasureData(),annotationData:this.captureAnnotationData()}}async restore(e,t="view",i){if(!e){i?.(null);return}e.cameraPose&&this.engine.cameraModule?.restoreCameraPose?.(e.cameraPose),this.restoreClippingState(e.clipping),this.restoreMeasureData(e.measureData),await this.restoreAnnotationData(e.annotationData),this.applyAnnotationMode(t);const s=this.engine.fabricDraw;s&&s.setActionHandlers({onConfirm:r=>{const o=this.get();o.annotationData=this.serializeSnapshotValue(r),i&&i(o),this.clearAnnotation()},onCancel:()=>{this.clearAnnotation()}})}create(e){const t=this.engine.fabricDraw;if(!t){e?.(this.get());return}t.setActionHandlers({onConfirm:i=>{const s=this.get();s.annotationData=this.serializeSnapshotValue(i),e?.(s),this.clearAnnotation()},onCancel:()=>{this.clearAnnotation()}}),t.show?.(),t.active?.("edit"),t.setDrawType?.("none")}clearAnnotation(){this.engine.fabricDraw?.clearAllShapes?.(),this.engine.measure.disActive?.()}captureClippingState(){const e=this.engine.clipping,t=e?.sectionFace,i=e?.currentClippingMode??"",s={mode:i,fillCutFace:e?.getFillCutFace?.()??!0};if(i==="box"&&e?.sectionBox?.getboxXyz&&(s.box=e.sectionBox.getboxXyz()),i==="x"||i==="y"||i==="z"||i==="face"){const r=t?.normal;r&&(s.face={normal:{x:Number(r.x)||0,y:Number(r.y)||0,z:Number(r.z)||1},distance:Number(t?.distance)||0,direction:Number(t?.direction)===-1?-1:1})}return s}restoreClippingState(e){const t=this.engine.clipping;if(!t)return;typeof e?.fillCutFace=="boolean"&&t.setFillCutFace?.(e.fillCutFace);const i=e?.mode??"";if(!i){t.disActive?.();return}if(i==="box"){t.active?.("box"),e.box&&t.sectionBox?.setboxXyz?.(e.box);return}if(i==="x"||i==="y"||i==="z"){t.active?.(i),this.applyFaceState(e.face);return}if(i==="face"){this.restoreFaceMode(e.face);return}t.active?.(i)}restoreFaceMode(e){const t=this.engine.clipping,i=t?.sectionFace;!t||!i||(t.sectionBox?.disActive?.(),i.disActive?.(),i.active?.(),t.currentClippingMode="face",this.applyFaceState(e))}applyFaceState(e){if(!e)return;const t=this.engine.clipping?.sectionFace;if(!t)return;const i=new w.Vector3(e.normal.x,e.normal.y,e.normal.z).normalize();t.direction=e.direction===-1?-1:1,t.setFaceNormal?.(i,e.distance??0)}captureMeasureData(){const e=this.engine.measure?.annotationData;return e?this.serializeSnapshotValue(e):null}restoreMeasureData(e){const t=this.engine.measure;if(!t)return;try{t.clearAll?.()}catch{}if(!e)return;const i=this.deserializeSnapshotValue(e);(!t.annotationData||typeof t.annotationData!="object")&&(t.annotationData={}),Object.keys(t.annotationData).forEach(s=>{t.annotationData[s]=[]}),Object.keys(i).forEach(s=>{t.annotationData[s]=Array.isArray(i[s])?i[s]:[]}),t.tools?.drawNormalAnnotation?.()}captureAnnotationData(){const e=this.engine.fabricDraw;return e?.getAllShapes?this.serializeSnapshotValue(e.getAllShapes()):null}async restoreAnnotationData(e){const t=this.engine.fabricDraw;if(!t)return;if(!e){t.clearAllShapes?.();return}const i=this.deserializeSnapshotValue(e);await t.restoreAllShapes?.(i)}applyAnnotationMode(e){const t=this.engine.fabricDraw;t&&(t.setActionHandlers?.({}),t.show?.(),t.active?.(e),t.setDrawType?.("none"))}serializeSnapshotValue(e){if(e==null)return e;if(e instanceof w.Vector3)return{__type:"Vector3",x:e.x,y:e.y,z:e.z};if(Array.isArray(e))return e.map(t=>this.serializeSnapshotValue(t));if(typeof e=="object"){if(e instanceof HTMLElement||e instanceof SVGElement)return;const t={};return Object.keys(e).forEach(i=>{if(i==="container")return;const s=this.serializeSnapshotValue(e[i]);s!==void 0&&(t[i]=s)}),t}if(typeof e!="function")return e}deserializeSnapshotValue(e){if(e==null)return e;if(Array.isArray(e))return e.map(t=>this.deserializeSnapshotValue(t));if(typeof e=="object"){if(e.__type==="Vector3")return new w.Vector3(e.x,e.y,e.z);const t={};return Object.keys(e).forEach(i=>{t[i]=this.deserializeSnapshotValue(e[i])}),t}return e}}class RR{options;deviceType;animationId=null;isDisposed=!1;isRenderingPaused=!1;controlsEnabledBeforePause=!0;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=5;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewTree;merge2d;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;modelMapperBatch;modelEdge;ai;pathRoaming;hoverHighLight;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;fabricDraw;drawingPin;models=[];reactBoundingClientRect={left:0,top:0};version="3.7.13";versionEl=null;container;constructor(e){if(window.THREE=w,this.options=e,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);if(this.engineModelModule=new R2(this),this.engineModelModule.init(),this.ai=new wP(this),this.deviceModule=new x_(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new wi(this),this.sceneModule=new A_(this),this.scene=this.sceneModule.scene,this.renderModule=new Y1(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.orthographicCamera,this.scene.camera=this.camera,this.renderer){const r=this.renderer;r.interactionCullingEnabled=!0,r.interactionActive=!1,r.interactionRenderScene=this.scene,r.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,r.interactionSkipShadows=this.options.interactionSkipShadows??!0}this.controlModule=new nE(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.clipping=new AP(this),this.clipping.init(),this.composerModule=new mE(this),this.composerModule.init(),this.events=new S2,this.engineStatus=new w2(this),this.engineStatus.init(),this.loaderModule=new _2(this),this.lightModule=new I2(this),this.lightModule.init(),this.viewCube=new Z2(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=eD(this),this.rangeScale=new tD(this),this.rangeScale.init(),this.setting=new fD(this),this.engineModelModule.init(),this.handelBehaved=Rd(this),this.modelMapperBatch=new vP(this),this.measure=new wD(this),this.modelToolModule=new D2(this),this.modelProperties=new yP(this),this.interactionModule=new T2(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new Ic(this),this.modelEdge=new uD(this),this.modelTree=new xP(this),this.viewTree=new PP(this),this.merge2d=new zP(this),this.engineInfo=new bP(this),this.pathRoaming=new SP(this),this.pathRoaming.init(),this.oneClickEncoding=new BP(this),this.minMap=new CP(this),this.linkElement2d3d=new IP(this),this.linkView2d3d=new TP(this),this.grid=new sD(this),this.level=new hD(this),this.issueReport=new MP(this),this.fabricDraw=new PR(this),this.drawingPin=new LR(this),this.text=new EP(this),this.hdr=new aD(this),this.ground=new mf(this),this.ground.init(),this.skyManager=new dD(this),this.setting.init(),this.worldToScreen=new rt(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new U2,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let t=document.createElement("div");t.className="versionText",this.versionEl=t,this.updateVersionDisplay(),this.container.appendChild(t);let i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.style.position="absolute",i.style.zIndex="1000",i.style.left="0px",i.style.top="0px",i.style.pointerEvents="none",this.container.appendChild(i),this.catchSvg=i,this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let s=this;this.controls.addEventListener("start",()=>{s.renderer&&(s.renderer.interactionActive=!0),s.events.trigger(Ss.EngineBusy),s.container&&(s.container.style.cursor="none")}),this.controls.addEventListener("end",()=>{s.renderer&&(s.renderer.interactionActive=!1),s.events.trigger(Ss.EngineFree),s.container&&(s.container.style.cursor="default")}),this.controls.addEventListener("change",()=>{const r=new w.Vector3;s.camera.getWorldDirection(r);const o=Math.atan2(r.x,-r.z);let a=new CustomEvent("D3ViewUpdate",{detail:{position:s.camera.position,rotation:o,type:s.camera.type}});window.dispatchEvent(a)}),this.events.on(Ss.LoadingCompleted,r=>{s.modelEdge.active()}),this.animate=()=>{if(!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}this.stats&&this.stats.begin(),this.composerModule&&this.composerModule.composer.render(),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.skyManager.update(),this.hoverHighLight.update(),this.controlModule.update(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.stats&&this.stats.end(),this._fpsFrameCount++;const r=performance.now();if(r-this._fpsLastCheck>=this._fpsCheckInterval){const o=r-this._fpsLastCheck,a=this._fpsFrameCount/o*1e3;this._fpsFrameCount=0,this._fpsLastCheck=r,a<this._fpsThreshold?(this._lowFpsCount++,this._highFpsCount=0,this._lowFpsCount>=this._lowFpsRequired&&r-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=r,this._lowFpsCount=0)):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let o=this.scene?.dirLight;o&&this.camera&&this.updateLightPosition(this.camera,o)}},this.animate()}updateVersionDisplay(){if(!this.versionEl)return;const e={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",i=e[t]??t;this.versionEl.innerHTML=`v${this.version} | ${i}`}updateLightPosition(e,t,i=!0){const s=new w.Vector3;e.getWorldDirection(s);const r=100,o=new w.Vector3().copy(s).multiplyScalar(-r),a=new w.Vector3(0,1,0),l=new w.Vector3().crossVectors(s,a).normalize();o.addScaledVector(a,r*.5),o.addScaledVector(l,r*.3),t.position.copy(e.position).add(o);const c=new w.Vector3().copy(e.position).add(s.multiplyScalar(20));t.target.position.copy(c),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i>0){const s=e[i-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${s}`),this.engineModelModule.autoSwitch(s)}}_adaptiveRenderingUpgrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i<e.length-1){const s=e[i+1];console.log(`[AdaptiveRendering] FPS高于${this._fpsUpgradeThreshold},自动升级: ${t} → ${s}`),this.engineModelModule.autoSwitch(s)}}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(!this.container||!this.renderer||!this.camera)return;if(e===void 0||t===void 0){const c=this.deviceModule.getContainerSize();e=e??c.width,t=t??c.height}if(!e||!t)return;const i=this.camera.position.clone(),s=this.camera.quaternion.clone(),r=this.camera.up.clone(),o=this.controls?.target?.clone?.(),a=this.controlModule?.orbitControls?.origin?.clone?.();this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,t);const l=e/t;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=l,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const c=this.cameraModule.orthographicCamera,h=this.cameraModule.getOrthographicVisibleHeight(c);this.cameraModule.setOrthographicVisibleHeight(h,c,l),c.updateProjectionMatrix()}if(this.composerModule&&(typeof this.composerModule.resize=="function"?this.composerModule.resize(e,t):this.composerModule.composer&&this.composerModule.composer.setSize(e,t)),this.catchSvg&&this.catchSvg.setAttribute("viewBox",`0 0 ${e} ${t}`),this.fabricDraw&&this.fabricDraw.resize(e,t),this.camera.position.copy(i),this.camera.quaternion.copy(s),this.camera.up.copy(r),this.camera.updateMatrix(),this.camera.updateMatrixWorld(!0),o&&this.controls?.target&&this.controls.target.copy(o),a&&this.controlModule?.orbitControls?.origin&&this.controlModule.orbitControls.origin.copy(a),this.controlModule?.orbitControls){const c=this.controlModule.orbitControls;c._lastPosition?.copy?.(this.camera.position),c._lastTarget?.copy?.(c.target),c._lastUp?.copy?.(this.camera.up),c._lastQuaternion?.copy?.(this.camera.quaternion),c._lastZoom=this.camera.zoom}this.controlModule?.firstPersonControls?.syncRotationStateFromCamera?.(),this.controlModule?.firstPersonControls?.syncSharedTargetFromCamera?.(),this.events&&this.events.trigger(Ss.ViewportResize,{width:e,height:t})}dispose(){if(this.isDisposed)return;this.isDisposed=!0,console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.invokeIfExists(this.rangeScale,"dispose"),this.invokeIfExists(this.measure,"dispose"),this.invokeIfExists(this.clipping,"disActive"),this.invokeIfExists(this.interactionModule,"dispose"),this.invokeIfExists(this.controlModule,"dispose"),this.invokeIfExists(this.pathRoaming,"dispose"),this.invokeIfExists(this.hoverHighLight,"dispose"),this.invokeIfExists(this.linkElement2d3d,"dispose"),this.invokeIfExists(this.linkView2d3d,"dispose"),this.invokeIfExists(this.skyManager,"close",!0),this.invokeIfExists(this.hdr,"dispose"),this.invokeIfExists(this.minMap,"dispose"),this.invokeIfExists(this.grid,"dispose"),this.invokeIfExists(this.level,"dispose"),this.invokeIfExists(this.ground,"dispose"),this.invokeIfExists(this.text,"dispose"),this.invokeIfExists(this.issueReport,"dispose"),this.invokeIfExists(this.fabricDraw,"dispose"),this.invokeIfExists(this.viewCube?.cubeTool,"dispose"),this.invokeIfExists(this.handelBehaved,"disActive")}catch(t){console.warn("[BimEngine] Error disposing managers:",t)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose())}catch(t){console.warn("[BimEngine] Error disposing controls:",t)}this.scene&&(this.disposeSceneAttachments(this.scene),this.clearScene(this.scene));try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(t=>{t?.dispose?.()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose(),this.composerModule.composer.dispose?.(),this.composerModule.composer.passes=[])}catch(t){console.warn("[BimEngine] Error disposing composer:",t)}try{this.renderModule?.disposeRenderer?.(),this.renderer&&(this.renderer.renderLists?.dispose?.(),this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(t){console.warn("[BimEngine] Error disposing renderer:",t)}try{this.stats?.dom?.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg?.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg),this.versionEl?.parentElement&&this.versionEl.parentElement.removeChild(this.versionEl)}catch(t){console.warn("[BimEngine] Error disposing DOM elements:",t)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(t){console.warn("[BimEngine] Error clearing event listeners:",t)}const e=this;e.scene=null,e.camera=null,e.renderer=null,e.controls=null,e.models=[],e.container=null,e.catchSvg=null,e.stats=null,e.versionEl=null,e.worldToScreen=null,e.measure=null,e.clipping=null,e.interactionModule=null,e.controlModule=null,e.sceneModule=null,e.cameraModule=null,e.deviceModule=null,e.renderModule=null,e.composerModule=null,e.loaderModule=null,e.lightModule=null,e.engineStatus=null,e.hoverHighLight=null,e.pathRoaming=null,e.hdr=null,e.skyManager=null,e.viewCube=null,e.grid=null,e.level=null,e.ground=null,e.minMap=null,e.fabricDraw=null,e.linkElement2d3d=null,e.linkView2d3d=null,e.rangeScale=null,e.text=null,e.issueReport=null,e.modelEdge=null,e.modelTree=null,e.modelProperties=null,e.modelMapperBatch=null,e.engineInfo=null,e.ai=null,e.oneClickEncoding=null,e.drawingPin=null,e.events=null,console.log("[BimEngine] Engine disposal completed")}clearScene(e){if(!e)return;[...e.children].forEach(i=>{this.clearScene(i)}),e.parent&&e.parent.remove(e),e instanceof w.Mesh&&!(e instanceof w.InstancedMesh)&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>this.disposeMaterial(i)):this.disposeMaterial(e.material))),e instanceof w.Line&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof w.Points&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof w.InstancedMesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>this.disposeMaterial(i)):this.disposeMaterial(e.material)),e.instanceMatrix&&(e.instanceMatrix=null),e.instanceColor&&(e.instanceColor=null)),e instanceof w.Sprite&&e.material&&this.disposeMaterial(e.material),e instanceof w.Light&&e.shadow?.dispose?.()}invokeIfExists(e,t,...i){const s=e?.[t];typeof s=="function"&&s.apply(e,i)}disposeSceneAttachments(e){new Set([e.background,e.environment,e.overrideMaterial]).forEach(i=>{this.disposeSceneAttachment(i)}),e.background=null,e.environment=null,e.overrideMaterial=null,e.dirLight=null,e.camera=null}disposeSceneAttachment(e){e&&(e instanceof w.Material||e instanceof w.Texture)&&e.dispose?.()}disposeMaterial(e){if(!e)return;["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(i=>{const s=e[i];s&&s instanceof w.Texture&&s.dispose()}),e.dispose()}}const kR=`
6056
+ `}applyTo2d({imageData:{data:n}}){let e=-this.vibrance;for(let t=0;t<n.length;t+=4){let i=n[t],s=n[t+1],r=n[t+2],o=Math.max(i,s,r),a=(i+s+r)/3,l=2*Math.abs(o-a)/255*e;n[t]+=o===i?0:(o-i)*l,n[t+1]+=o===s?0:(o-s)*l,n[t+2]+=o===r?0:(o-r)*l}}sendUniformData(n,e){n.uniform1f(e.uVibrance,-this.vibrance)}isNeutralState(){return this.vibrance===0}};K(gl,"type","Vibrance"),K(gl,"defaults",{vibrance:0}),K(gl,"uniformLocations",["uVibrance"]),ke.setClass(gl),Oa({BaseFilter:()=>Nt,BlackWhite:()=>pR,BlendColor:()=>tl,BlendImage:()=>il,Blur:()=>nl,Brightness:()=>sl,Brownie:()=>lR,ColorMatrix:()=>Rr,Composed:()=>ig,Contrast:()=>rl,Convolute:()=>ol,Gamma:()=>al,Grayscale:()=>ll,HueRotation:()=>jh,Invert:()=>cl,Kodachrome:()=>hR,Noise:()=>hl,Pixelate:()=>ul,Polaroid:()=>dR,RemoveColor:()=>dl,Resize:()=>fl,Saturation:()=>pl,Sepia:()=>fR,Technicolor:()=>uR,Vibrance:()=>gl,Vintage:()=>cR});function xR(n,e,t="bim-snapshot.png"){const i=n?.renderer,s=i?.domElement;if(!i||!s||!e)return null;const r=s.width||s.clientWidth,o=s.height||s.clientHeight;if(r<=0||o<=0)return null;let a=bR(s,r,o);if(!yR(a)){const f=vR(n,r,o);f&&(a=f)}const l=document.createElement("canvas");l.width=r,l.height=o;const c=l.getContext("2d");if(!c)return null;c.drawImage(a,0,0,r,o),c.drawImage(e,0,0,r,o);const h=l.toDataURL("image/png"),u=document.createElement("a");return u.href=h,u.download=t.toLowerCase().endsWith(".png")?t:`${t}.png`,u.click(),h}function bR(n,e,t){const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");return s&&s.drawImage(n,0,0,e,t),i}function yR(n){const e=n.getContext("2d");if(!e||n.width<=0||n.height<=0)return!1;const t=Math.min(32,n.width),i=Math.min(32,n.height),s=Math.max(1,Math.floor(n.width/t)),r=Math.max(1,Math.floor(n.height/i));for(let o=0;o<n.height;o+=r)for(let a=0;a<n.width;a+=s){const l=e.getImageData(a,o,1,1).data;if(l[0]!==0||l[1]!==0||l[2]!==0||l[3]!==0)return!0}return!1}function vR(n,e,t){const i=n?.renderer,s=n?.scene,r=n?.camera;if(!i||!s||!r)return null;const o=new w.WebGLRenderTarget(e,t,{minFilter:w.LinearFilter,magFilter:w.LinearFilter,format:w.RGBAFormat,depthBuffer:!0,stencilBuffer:!0}),a=i.getRenderTarget(),l=i.autoClear,c=i.xr?.enabled??!1;try{i.xr&&(i.xr.enabled=!1),i.autoClear=!0,i.setRenderTarget(o),i.clear(!0,!0,!0),i.render(s,r);const h=new Uint8Array(e*t*4);return i.readRenderTargetPixels(o,0,0,e,t,h),_R(h,e,t)}catch{return null}finally{i.setRenderTarget(a),i.autoClear=l,i.xr&&(i.xr.enabled=c),o.dispose()}}function _R(n,e,t){const i=document.createElement("canvas");i.width=e,i.height=t;const s=i.getContext("2d");if(!s)return i;const r=s.createImageData(e,t),o=e*4;for(let a=0;a<t;a++){const l=(t-1-a)*o,c=a*o;for(let h=0;h<o;h++)r.data[c+h]=n[l+h]}return s.putImageData(r,0,0),i}const wR=["#ffffff","#000000","#ff4d4f","#fa8c16","#fadb14","#52c41a","#13c2c2","#1677ff","#722ed1","#eb2f96"],SR={none:new URL("/assets/icon/%E9%80%89%E6%8B%A9.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,line:new URL("/assets/icon/%E7%BA%BF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,arrow:new URL("/assets/icon/%E7%AE%AD%E5%A4%B4.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,rect:new URL("/assets/icon/%E7%9F%A9%E5%BD%A2.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,circle:new URL("/assets/icon/%E5%9C%86%E5%BD%A2.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,text:new URL("/assets/icon/%E6%96%87%E5%AD%97.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,cloudline:new URL("/assets/icon/%E4%BA%91%E7%BA%BF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href},CR=new URL("/assets/icon/%E6%B5%8B%E8%B7%9D.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,MR=new URL("/assets/icon/%E6%88%AA%E5%9B%BE.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,ER=new URL("/assets/icon/%E7%BA%BF%E5%AE%BD.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,IR=new URL("/assets/icon/%E5%AD%97%E5%8F%B7.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,TR=[{type:"distance",label:"距离"},{type:"clearDistance",label:"净距"},{type:"clearHeight",label:"净高"},{type:"elevation",label:"标高"},{type:"point",label:"坐标"},{type:"angle",label:"角度"},{type:"area",label:"面积"},{type:"slope",label:"坡度"}],DR={distance:new URL("/assets/icon/%E8%B7%9D%E7%A6%BB.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,clearDistance:new URL("/assets/icon/%E5%87%80%E8%B7%9D.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,clearHeight:new URL("/assets/icon/%E5%87%80%E9%AB%98.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,elevation:new URL("/assets/icon/%E6%A0%87%E9%AB%98.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,point:new URL("/assets/icon/%E5%9D%90%E6%A0%87.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,angle:new URL("/assets/icon/%E8%A7%92%E5%BA%A6.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,area:new URL("/assets/icon/%E9%9D%A2%E7%A7%AF.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href,slope:new URL("/assets/icon/%E5%9D%A1%E5%BA%A6.svg",typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ze&&ze.tagName.toUpperCase()==="SCRIPT"&&ze.src||new URL("bim-engine-sdk.umd.js",document.baseURI).href).href};class BR{constructor(e,t){this.handlers=e,this.root=document.createElement("div"),this.root.style.position="absolute",this.root.style.top="8px",this.root.style.left="50%",this.root.style.transform="translateX(-50%)",this.root.style.display="none",this.root.style.padding="6px",this.root.style.background="#ffffff",this.root.style.border="1px solid #d9d9d9",this.root.style.borderRadius="8px",this.root.style.pointerEvents="auto",this.root.style.userSelect="none",this.root.style.boxShadow="0 4px 14px rgba(0, 0, 0, 0.12)",this.root.style.zIndex="1300",this.root.style.overflow="visible",this.editPanel=document.createElement("div"),this.editPanel.style.display="flex",this.editPanel.style.flexDirection="column",this.editPanel.style.gap="6px",this.viewPanel=document.createElement("div"),this.viewPanel.style.display="none",this.viewPanel.style.alignItems="center",this.viewPanel.style.gap="6px";const i=document.createElement("div");i.style.display="flex",i.style.alignItems="center",i.style.gap="6px",i.style.flexWrap="wrap",[{type:"none",label:"选择"},{type:"line",label:"线"},{type:"arrow",label:"箭头"},{type:"rect",label:"矩形"},{type:"circle",label:"圆形"},{type:"text",label:"文字"},{type:"cloudline",label:"云线"}].forEach(d=>{const p=this.createIconButton(d.label,SR[d.type]);p.onclick=()=>this.handlers.onDrawTypeChange(d.type),this.drawButtons[d.type]=p,i.appendChild(p)});const r=document.createElement("div");r.style.position="relative",r.style.display="flex",r.style.alignItems="center",this.colorTrigger=document.createElement("button"),this.colorTrigger.type="button",this.colorTrigger.title="颜色",this.colorTrigger.style.width="32px",this.colorTrigger.style.height="24px",this.colorTrigger.style.padding="2px",this.colorTrigger.style.border="1px solid #d9d9d9",this.colorTrigger.style.borderRadius="4px",this.colorTrigger.style.background="#ffffff",this.colorTrigger.style.cursor="pointer",this.colorTrigger.style.display="flex",this.colorTrigger.style.alignItems="center",this.colorTrigger.style.justifyContent="center",this.colorTrigger.onclick=()=>this.setColorPresetVisible(!this.isColorPresetOpen);const o=document.createElement("span");o.style.display="block",o.style.width="100%",o.style.height="100%",o.style.borderRadius="2px",o.style.border="1px solid rgba(0, 0, 0, 0.12)",this.colorTrigger.appendChild(o),r.appendChild(this.colorTrigger),this.colorInput=document.createElement("input"),this.colorInput.type="color",this.colorInput.value=t.stroke,this.colorInput.style.position="absolute",this.colorInput.style.width="1px",this.colorInput.style.height="1px",this.colorInput.style.opacity="0",this.colorInput.style.pointerEvents="none",this.colorInput.style.left="0",this.colorInput.style.top="0",this.colorInput.tabIndex=-1,this.colorInput.oninput=()=>{this.updateColorControl(this.colorInput.value),this.handlers.onColorChange(this.colorInput.value),this.setColorPresetVisible(!1)},r.appendChild(this.colorInput),this.colorPresetPanel=document.createElement("div"),this.colorPresetPanel.style.position="absolute",this.colorPresetPanel.style.top="30px",this.colorPresetPanel.style.left="0",this.colorPresetPanel.style.display="none",this.colorPresetPanel.style.padding="8px",this.colorPresetPanel.style.background="#ffffff",this.colorPresetPanel.style.border="1px solid #d9d9d9",this.colorPresetPanel.style.borderRadius="6px",this.colorPresetPanel.style.boxShadow="0 6px 18px rgba(0, 0, 0, 0.14)",this.colorPresetPanel.style.zIndex="20",this.colorPresetPanel.style.width="152px";const a=document.createElement("div");a.style.display="grid",a.style.gridTemplateColumns="repeat(5, 1fr)",a.style.gap="6px",wR.forEach(d=>{const p=document.createElement("button");p.type="button",p.title=d,p.style.width="22px",p.style.height="22px",p.style.padding="0",p.style.border="1px solid #d9d9d9",p.style.borderRadius="4px",p.style.background=d,p.style.cursor="pointer",p.onclick=()=>{this.updateColorControl(d),this.handlers.onColorChange(d),this.setColorPresetVisible(!1)},a.appendChild(p)}),this.colorPresetPanel.appendChild(a);const l=document.createElement("button");l.type="button",l.textContent="自定义",l.style.marginTop="8px",l.style.width="100%",l.style.height="26px",l.style.border="1px solid #d9d9d9",l.style.borderRadius="4px",l.style.background="#ffffff",l.style.color="#333333",l.style.cursor="pointer",l.onclick=()=>this.openNativeColorPicker(),this.colorPresetPanel.appendChild(l),r.appendChild(this.colorPresetPanel),this.updateColorControl(t.stroke),i.appendChild(this.createField("",r)),this.strokeWidthInput=document.createElement("input"),this.strokeWidthInput.type="number",this.strokeWidthInput.min="1",this.strokeWidthInput.max="20",this.strokeWidthInput.step="1",this.strokeWidthInput.value=String(t.strokeWidth),this.strokeWidthInput.style.width="46px",this.strokeWidthInput.oninput=()=>this.handlers.onStrokeWidthChange(this.strokeWidthInput.value),i.appendChild(this.createField("",this.strokeWidthInput,ER,"线宽")),this.fontSizeInput=document.createElement("input"),this.fontSizeInput.type="number",this.fontSizeInput.min="10",this.fontSizeInput.max="96",this.fontSizeInput.step="1",this.fontSizeInput.value=String(t.fontSize),this.fontSizeInput.style.width="46px",this.fontSizeInput.oninput=()=>this.handlers.onFontSizeChange(this.fontSizeInput.value),i.appendChild(this.createField("",this.fontSizeInput,IR,"字号")),this.distanceButton=this.createIconButton("测量",CR),this.distanceButton.onclick=()=>this.handlers.onMeasureToggle(),i.appendChild(this.distanceButton);const c=this.createIconButton("截图",MR);c.onclick=()=>this.handlers.onScreenshot(),i.appendChild(c);const h=this.createTextButton("×","取消");h.onclick=()=>this.handlers.onCancel(),h.style.background="#ff4d4f",h.style.borderColor="#ff4d4f",h.style.color="#ffffff",i.appendChild(h);const u=this.createTextButton("✔","确定");u.onclick=()=>this.handlers.onConfirm(),u.style.background="#52c41a",u.style.borderColor="#52c41a",u.style.color="#ffffff",i.appendChild(u),this.measureSubPanel=document.createElement("div"),this.measureSubPanel.style.display="none",this.measureSubPanel.style.alignItems="center",this.measureSubPanel.style.gap="6px",this.measureSubPanel.style.flexWrap="wrap",this.measureSubPanel.style.paddingTop="2px",TR.forEach(d=>{const p=this.createSmallIconButton(d.label,DR[d.type]);p.onclick=()=>this.handlers.onMeasureTypeChange(d.type),this.measureTypeButtons[d.type]=p,this.measureSubPanel.appendChild(p)}),this.editPanel.appendChild(i),this.editPanel.appendChild(this.measureSubPanel);const f=this.createTextButton("关闭","关闭");f.onclick=()=>this.handlers.onClose(),this.viewPanel.appendChild(f),this.root.appendChild(this.editPanel),this.root.appendChild(this.viewPanel),this.disabledMask=document.createElement("div"),this.disabledMask.style.position="absolute",this.disabledMask.style.inset="0",this.disabledMask.style.display="none",this.disabledMask.style.background="rgba(255, 255, 255, 0.55)",this.disabledMask.style.backdropFilter="blur(1px)",this.disabledMask.style.cursor="not-allowed",this.disabledMask.style.pointerEvents="auto",this.disabledMask.style.zIndex="10",this.root.appendChild(this.disabledMask),document.addEventListener("pointerdown",this.onDocumentPointerDown),this.setMode("edit")}root;disabledMask;drawButtons={};measureTypeButtons={};distanceButton;colorTrigger;colorInput;colorPresetPanel;strokeWidthInput;fontSizeInput;editPanel;viewPanel;measureSubPanel;mode="edit";isEditPanelMasked=!1;isColorPresetOpen=!1;onDocumentPointerDown=e=>{const t=e.target;t&&this.root.contains(t)||this.setColorPresetVisible(!1)};mount(e){e.appendChild(this.root)}show(){this.root.style.display="block"}hide(){this.root.style.display="none"}setMode(e){this.mode=e,this.editPanel.style.display=e==="edit"?"flex":"none",this.viewPanel.style.display=e==="view"?"flex":"none",e==="view"&&(this.setMeasurePanelVisible(!1),this.setColorPresetVisible(!1)),this.applyEditPanelMaskState()}setEditPanelMasked(e){this.isEditPanelMasked=e,this.applyEditPanelMaskState()}setDrawType(e){for(const t in this.drawButtons){const i=this.drawButtons[t];if(!i)continue;const s=t===e;i.style.background=s?"#eaf2ff":"#ffffff",i.style.borderColor=s?"#2f80ed":"#d9d9d9"}}setMeasurePanelVisible(e){if(this.mode!=="edit"){this.measureSubPanel.style.display="none";return}this.measureSubPanel.style.display=e?"flex":"none"}setMeasureState(e,t){this.distanceButton.style.background=e?"#eaf2ff":"#ffffff",this.distanceButton.style.borderColor=e?"#2f80ed":"#d9d9d9";for(const i in this.measureTypeButtons){const s=this.measureTypeButtons[i];if(!s)continue;const r=e&&t===i;s.style.background=r?"#eaf2ff":"#ffffff",s.style.borderColor=r?"#2f80ed":"#d9d9d9"}}setStyleValues(e){e.stroke&&this.updateColorControl(e.stroke),typeof e.strokeWidth=="number"&&(this.strokeWidthInput.value=String(e.strokeWidth)),typeof e.fontSize=="number"&&(this.fontSizeInput.value=String(e.fontSize))}dispose(){this.colorInput.oninput=null,this.strokeWidthInput.oninput=null,this.fontSizeInput.oninput=null,document.removeEventListener("pointerdown",this.onDocumentPointerDown),this.root.remove()}applyEditPanelMaskState(){const e=this.mode==="edit"&&this.isEditPanelMasked;this.disabledMask.style.display=e?"block":"none",e&&this.setColorPresetVisible(!1),this.editPanel.querySelectorAll("button, input").forEach(i=>{const s=i;s.disabled=e})}createField(e,t,i,s=""){const r=document.createElement("div");if(r.style.display="flex",r.style.alignItems="center",r.style.gap="4px",r.style.padding="0 2px",r.style.color="#333333",r.style.fontSize="12px",e){const o=document.createElement("span");o.textContent=e,r.appendChild(o)}if(i){const o=document.createElement("img");o.src=i,o.alt=s,o.style.width="14px",o.style.height="14px",o.style.display="block",r.appendChild(o)}return t instanceof HTMLInputElement&&(t.style.height="24px",t.style.border="1px solid #d9d9d9",t.style.borderRadius="4px",t.style.background="#ffffff",t.style.color="#333333",t.style.outline="none",t.style.padding="0 4px"),r.appendChild(t),r}updateColorControl(e){this.colorInput.value=e;const t=this.colorTrigger.firstElementChild;t&&(t.style.background=e)}setColorPresetVisible(e){this.isColorPresetOpen=e,this.colorPresetPanel.style.display=e?"block":"none",this.colorTrigger.style.borderColor=e?"#2f80ed":"#d9d9d9"}openNativeColorPicker(){const e=this.colorInput;if(typeof e.showPicker=="function"){e.showPicker();return}e.click()}createIconButton(e,t){const i=document.createElement("button");i.type="button",i.style.width="28px",i.style.height="28px",i.style.padding="0",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.cursor="pointer";const s=document.createElement("img");return s.src=t,s.alt=e,s.style.width="16px",s.style.height="16px",s.style.display="block",i.appendChild(s),i}createSmallIconButton(e,t){const i=document.createElement("button");i.type="button",i.style.width="26px",i.style.height="26px",i.style.padding="0",i.style.display="flex",i.style.alignItems="center",i.style.justifyContent="center",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.cursor="pointer";const s=document.createElement("img");return s.src=t,s.alt=e,s.style.width="14px",s.style.height="14px",s.style.display="block",i.appendChild(s),i}createTextButton(e,t){const i=document.createElement("button");return i.type="button",i.title=t,i.textContent=e,i.style.width="28px",i.style.height="28px",i.style.padding="0 10px",i.style.border="1px solid #d9d9d9",i.style.borderRadius="4px",i.style.background="#ffffff",i.style.color="#333333",i.style.fontSize="13px",i.style.lineHeight="1",i.style.cursor="pointer",i}}class PR{engine;wrapper;canvasEl;canvas;toolbar;isActive=!1;isVisible=!0;isViewLocked=!0;isDistanceMeasureMode=!1;isMeasurePanelExpanded=!1;drawType="none";mode="edit";currentMeasureType=null;sessionSnapshot=null;actionHandlers={};drawStyle={stroke:"#ff4d4f",strokeWidth:2,fill:"rgba(255, 77, 79, 0.08)",fontSize:16,text:"T",cloudRadius:10};startPoint=null;tempObject=null;cloudPoints=[];onMouseDown=e=>this.handleMouseDown(e);onMouseMove=e=>this.handleMouseMove(e);onMouseUp=e=>this.handleMouseUp(e);onMouseDblClick=e=>this.handleMouseDblClick(e);onSelectionChanged=()=>this.syncStyleFromSelection();onKeyDown=e=>this.handleKeyDown(e);constructor(e){this.engine=e;const t=this.engine.container;if(!t)throw new Error("FabricDraw: engine container not found.");this.wrapper=document.createElement("div"),this.wrapper.className="fabric-draw-layer",this.wrapper.style.position="absolute",this.wrapper.style.left="0",this.wrapper.style.top="0",this.wrapper.style.right="0",this.wrapper.style.bottom="0",this.wrapper.style.pointerEvents="none",this.canvasEl=document.createElement("canvas"),this.canvasEl.style.width="100%",this.canvasEl.style.height="100%",this.wrapper.appendChild(this.canvasEl),this.toolbar=new BR({onDrawTypeChange:s=>this.setDrawType(s),onMeasureToggle:()=>this.toggleMeasurePanel(),onMeasureTypeChange:s=>this.activateDistanceMeasure(s),onScreenshot:()=>{this.saveScreenshot(this.createScreenshotFileName())},onColorChange:s=>this.handleColorInputChange(s),onStrokeWidthChange:s=>this.handleStrokeWidthInputChange(s),onFontSizeChange:s=>this.handleFontSizeInputChange(s),onCancel:()=>{this.handleCancelClick()},onConfirm:()=>this.handleConfirmClick(),onClose:()=>{this.handleCloseClick()}},{stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,fontSize:this.drawStyle.fontSize}),this.toolbar.mount(this.wrapper);const i=this.engine.renderer?.domElement;i?.nextSibling?t.insertBefore(this.wrapper,i.nextSibling):t.appendChild(this.wrapper),this.canvas=new Xp(this.canvasEl,{selection:!0,preserveObjectStacking:!0}),this.resize(),this.canvas.on("mouse:down",this.onMouseDown),this.canvas.on("mouse:move",this.onMouseMove),this.canvas.on("mouse:up",this.onMouseUp),this.canvas.on("mouse:dblclick",this.onMouseDblClick),this.canvas.on("selection:created",this.onSelectionChanged),this.canvas.on("selection:updated",this.onSelectionChanged),this.canvas.on("selection:cleared",this.onSelectionChanged),window.addEventListener("keydown",this.onKeyDown),this.refreshToolbarState()}active(e="edit"){this.isActive=!0,this.mode=e,this.isViewLocked=!0,this.drawType="none",this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.canvas.defaultCursor="default",this.sessionSnapshot=e==="edit"?this.cloneJson(this.getAllShapes()):null,this.toolbar.setMode(e),this.applyCanvasInteractive(e==="edit"),this.isVisible&&this.toolbar.show(),this.updateOverlayPointerEvents(),this.refreshToolbarState()}disActive(){this.isActive=!1,this.isViewLocked=!0,this.startPoint=null,this.cloudPoints=[],this.tempObject=null,this.drawType="none",this.mode="edit",this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.sessionSnapshot=null,this.stopDistanceMeasureMode(),this.canvas.defaultCursor="default",this.canvas.discardActiveObject(),this.applyCanvasInteractive(!0),this.canvas.requestRenderAll(),this.toolbar.setMode("edit"),this.toolbar.hide(),this.updateOverlayPointerEvents(),this.refreshToolbarState()}close(){this.disActive()}hide(){this.isVisible=!1,this.wrapper.style.display="none",this.toolbar.hide()}show(){this.isVisible=!0,this.wrapper.style.display="block",this.isActive&&this.toolbar.show(),this.resize()}isShown(){return this.isVisible}setDrawType(e,t){this.mode!=="view"&&(this.stopDistanceMeasureMode(),this.isMeasurePanelExpanded=!1,this.currentMeasureType=null,this.drawType=e,t&&(this.drawStyle={...this.drawStyle,...t}),this.canvas.defaultCursor=e==="none"?"default":"crosshair",this.updateOverlayPointerEvents(),this.refreshToolbarState())}getDrawType(){return this.drawType}setActionHandlers(e){this.actionHandlers={...e}}drawLine(e,t,i){const s=this.mergeStyle(i),r=this.createLineObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawArrow(e,t,i){const s=this.mergeStyle(i),r=this.createArrowObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawRect(e,t,i){const s=this.mergeStyle(i),r=this.createRectObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawCircle(e,t,i){const s=this.mergeStyle(i),r=this.createCircleObject(e,t,s,!0);return this.canvas.add(r),this.canvas.requestRenderAll(),r}drawText(e,t,i){const s=this.mergeStyle(i),r=new Pr(t??s.text,{left:e.x,top:e.y,...this.createTextStyle(s),selectable:!0,evented:!0,objectCaching:!1});return r.annotationType="text",this.canvas.add(r),this.canvas.requestRenderAll(),r}drawCloudLine(e,t){if(e.length<2)return null;const i=this.mergeStyle(t),s=this.createCloudObject(e,i,!0);return s?(this.canvas.add(s),this.canvas.requestRenderAll(),s):null}getAllShapes(){return this.canvas.toObject(["annotationType"])}clearAllShapes(){this.canvas.clear(),this.canvas.requestRenderAll()}async restoreAllShapes(e){await this.canvas.loadFromJSON(e),this.canvas.requestRenderAll()}saveScreenshot(e="bim-snapshot.png"){const t=this.canvas.lowerCanvasEl;return t?xR(this.engine,t,e):null}resize(e,t){const i=this.engine.container;if(!i)return;const s=e??i.clientWidth??1,r=t??i.clientHeight??1;this.canvas.setDimensions({width:s,height:r}),this.canvas.requestRenderAll()}dispose(){this.stopDistanceMeasureMode(),window.removeEventListener("keydown",this.onKeyDown),this.canvas.off("mouse:down",this.onMouseDown),this.canvas.off("mouse:move",this.onMouseMove),this.canvas.off("mouse:up",this.onMouseUp),this.canvas.off("mouse:dblclick",this.onMouseDblClick),this.canvas.off("selection:created",this.onSelectionChanged),this.canvas.off("selection:updated",this.onSelectionChanged),this.canvas.off("selection:cleared",this.onSelectionChanged),this.toolbar.dispose(),this.canvas.dispose(),this.wrapper.remove()}handleMouseDown(e){if(!this.isActive||this.mode==="view"||!this.isViewLocked||this.drawType==="none"||e?.target)return;const t=this.getPointFromEvent(e);if(this.drawType==="text"){const s=this.drawText(t);this.canvas.setActiveObject(s),this.canvas.requestRenderAll(),setTimeout(()=>{s.enterEditing(),s.hiddenTextarea?.focus(),s.selectAll()},0);return}this.startPoint=t,this.cloudPoints=[t],this.canvas.selection=!1,this.canvas.discardActiveObject();const i=this.createDraftObject(t,t);i&&(this.tempObject=i,this.canvas.add(i),this.canvas.requestRenderAll())}handleMouseMove(e){if(!this.isActive||this.mode==="view"||!this.isViewLocked||!this.startPoint||!this.tempObject)return;const t=this.getPointFromEvent(e),i=this.drawStyle;if(this.drawType==="cloudline"){if(this.shouldAppendCloudPoint(t)){this.cloudPoints.push(t),this.canvas.remove(this.tempObject);const s=this.createCloudObject(this.cloudPoints,i,!1);if(!s)return;this.tempObject=s,this.canvas.add(s),this.canvas.requestRenderAll()}return}if(this.drawType==="arrow"){this.canvas.remove(this.tempObject),this.tempObject=this.createArrowObject(this.startPoint,t,i,!1),this.canvas.add(this.tempObject),this.canvas.requestRenderAll();return}this.updateDraftObject(this.startPoint,t),this.canvas.requestRenderAll()}handleMouseUp(e){if(!this.isActive||this.mode==="view"||!this.isViewLocked||!this.startPoint)return;const t=this.getPointFromEvent(e);this.drawType==="cloudline"&&this.cloudPoints.length===1&&(this.cloudPoints.push(t),this.canvas.remove(this.tempObject),this.tempObject=this.createCloudObject(this.cloudPoints,this.drawStyle,!0),this.tempObject&&this.canvas.add(this.tempObject)),this.tempObject&&(this.tempObject.set({selectable:!0,evented:!0}),this.tempObject.setCoords?.(),this.canvas.requestRenderAll()),this.startPoint=null,this.tempObject=null,this.cloudPoints=[],this.canvas.selection=!0}handleMouseDblClick(e){const t=e?.target;this.isTextObject(t)&&(t.enterEditing(),t.hiddenTextarea?.focus(),t.selectAll?.())}handleKeyDown(e){if(!this.isActive)return;const t=this.canvas.getActiveObject();if(this.isTextObject(t)&&t?.isEditing||this.isInputElement(e.target))return;if(e.key==="Control"&&!e.repeat){this.toggleViewLock();return}if(e.key==="Escape"){e.preventDefault(),this.mode==="view"?this.handleCloseClick():this.handleCancelClick();return}if(e.key==="Enter"){this.mode==="edit"&&(e.preventDefault(),this.handleConfirmClick());return}if(e.key!=="Delete"&&e.key!=="Backspace"||!t)return;e.preventDefault(),this.canvas.getActiveObjects().forEach(r=>this.canvas.remove(r)),this.canvas.discardActiveObject(),this.canvas.requestRenderAll()}getPointFromEvent(e){if(e?.e){const i=this.canvas.getScenePoint(e.e);return{x:i.x,y:i.y}}const t=e?.scenePoint??e?.pointer??e?.absolutePointer;return t?{x:t.x,y:t.y}:{x:0,y:0}}shouldAppendCloudPoint(e){if(this.cloudPoints.length===0)return!0;const t=this.cloudPoints[this.cloudPoints.length-1],i=e.x-t.x,s=e.y-t.y;return Math.sqrt(i*i+s*s)>=6}createDraftObject(e,t){const i=this.drawStyle;switch(this.drawType){case"line":return this.createLineObject(e,t,i,!1);case"arrow":return this.createArrowObject(e,t,i,!1);case"rect":return this.createRectObject(e,t,i,!1);case"circle":return this.createCircleObject(e,t,i,!1);case"cloudline":return this.createCloudObject([e,t],i,!1);default:return null}}updateDraftObject(e,t){if(this.tempObject){if(this.drawType==="line"){this.tempObject.set({x2:t.x,y2:t.y});return}if(this.drawType==="rect"){const i=this.getBoxFromPoints(e,t);this.tempObject.set({left:i.left,top:i.top,width:i.width,height:i.height});return}if(this.drawType==="circle"){const i=this.getCircleFromPoints(e,t);this.tempObject.set({left:i.left,top:i.top,radius:i.radius})}}}mergeStyle(e){return{...this.drawStyle,...e??{}}}createObjectBase(e,t){return{stroke:e.stroke,strokeWidth:e.strokeWidth,fill:e.fill,selectable:t,evented:t,objectCaching:!1}}createLineObject(e,t,i,s){const r=new Qs([e.x,e.y,t.x,t.y],{...this.createObjectBase(i,s),fill:"",strokeLineCap:"round"});return r.annotationType="line",r}createRectObject(e,t,i,s){const r=this.getBoxFromPoints(e,t),o=new zs({...this.createObjectBase(i,s),left:r.left,top:r.top,width:r.width,height:r.height,originX:"left",originY:"top"});return o.annotationType="rect",o}createCircleObject(e,t,i,s){const r=this.getCircleFromPoints(e,t),o=new Br({...this.createObjectBase(i,s),left:r.left,top:r.top,radius:r.radius,originX:"left",originY:"top"});return o.annotationType="circle",o}createArrowObject(e,t,i,s){const r=t.x-e.x,o=t.y-e.y,a=Math.sqrt(r*r+o*o);if(a<1e-6){const B=new Qs([e.x,e.y,t.x,t.y],{stroke:i.stroke,strokeWidth:i.strokeWidth,fill:"",selectable:s,evented:s}),C=new Gs([B],{selectable:s,evented:s,objectCaching:!1});return C.annotationType="arrow",C}const l=r/a,c=o/a,h=-c,u=l,f=Math.max(10,i.strokeWidth*6),d=f*.72,p=t.x-l*f,g=t.y-c*f,m=p+h*(d*.5),A=g+u*(d*.5),x=p-h*(d*.5),b=g-u*(d*.5),y=new Qs([e.x,e.y,t.x,t.y],{stroke:i.stroke,strokeWidth:i.strokeWidth,fill:"",strokeLineCap:"round",selectable:!1,evented:!1}),_=`M ${t.x} ${t.y} L ${m} ${A} L ${x} ${b} Z`,E=new Dr(_,{fill:i.stroke,stroke:i.stroke,strokeWidth:1,selectable:!1,evented:!1,objectCaching:!1}),I=new Gs([y,E],{selectable:s,evented:s,objectCaching:!1});return I.annotationType="arrow",I}createCloudObject(e,t,i){const s=this.buildCloudPath(e,t.cloudRadius);if(!s)return null;const r=new Dr(s,{stroke:t.stroke,strokeWidth:t.strokeWidth,fill:"",strokeLineCap:"round",strokeLineJoin:"round",selectable:i,evented:i});return r.annotationType="cloudline",r}getBoxFromPoints(e,t){return{left:Math.min(e.x,t.x),top:Math.min(e.y,t.y),width:Math.abs(t.x-e.x),height:Math.abs(t.y-e.y)}}getCircleFromPoints(e,t){const i=t.x-e.x,s=t.y-e.y,r=Math.max(Math.abs(i),Math.abs(s)),o=i>=0?e.x:e.x-r,a=s>=0?e.y:e.y-r;return{left:o,top:a,radius:Math.max(r/2,1)}}buildCloudPath(e,t){if(e.length<2)return"";const i=Math.max(2,t),s=i*1.4;let r=`M ${e[0].x} ${e[0].y}`,o=1;for(let a=1;a<e.length;a++){const l=e[a-1],c=e[a],h=c.x-l.x,u=c.y-l.y,f=Math.sqrt(h*h+u*u);if(f<.1)continue;const d=-u/f,p=h/f,g=Math.max(1,Math.round(f/s));for(let m=1;m<=g;m++){const A=m/g,x=l.x+h*A,b=l.y+u*A,y=o%2===0?-1:1,_=x+d*i*y,E=b+p*i*y;r+=` Q ${_} ${E} ${x} ${b}`,o++}}return r}handleColorInputChange(e){this.drawStyle.stroke=e||this.drawStyle.stroke,this.drawStyle.fill=this.colorToAlpha(this.drawStyle.stroke,.08),this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}handleStrokeWidthInputChange(e){const t=this.parseNumber(e,this.drawStyle.strokeWidth,1,20);this.drawStyle.strokeWidth=t,this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}handleFontSizeInputChange(e){const t=this.parseNumber(e,this.drawStyle.fontSize,1,200);this.drawStyle.fontSize=t,this.applyCurrentStyleToSelection(),this.refreshToolbarStyleValues()}applyCurrentStyleToSelection(){const e=this.canvas.getActiveObjects();e.length!==0&&(e.forEach(t=>this.applyStyleToObject(t)),this.canvas.requestRenderAll())}applyStyleToObject(e){if(!e)return;if(e.annotationType==="arrow"&&Array.isArray(e._objects)){e._objects.forEach(i=>{if(i?.type==="triangle"||i?.type==="path"){i.set({fill:this.drawStyle.stroke,stroke:this.drawStyle.stroke,strokeWidth:1});return}i?.set({stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,strokeLineCap:"round"})}),e.set({dirty:!0}),e.setCoords?.();return}if(this.isTextObject(e)){e.set({...this.createTextStyle(this.drawStyle),fontSize:this.drawStyle.fontSize}),e.setCoords?.();return}const t={stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth};e?.type==="line"||e?.type==="path"?t.fill="":t.fill=this.drawStyle.fill,e.set(t),e.setCoords?.()}syncStyleFromSelection(){const e=this.canvas.getActiveObject();if(!e)return;const t=this.readStyleFromObject(e);t.stroke&&(this.drawStyle.stroke=t.stroke,this.drawStyle.fill=this.colorToAlpha(t.stroke,.08)),typeof t.strokeWidth=="number"&&(this.drawStyle.strokeWidth=t.strokeWidth),typeof t.fontSize=="number"&&(this.drawStyle.fontSize=t.fontSize),this.refreshToolbarStyleValues()}readStyleFromObject(e){if(!e)return{};if(e.annotationType==="arrow"&&Array.isArray(e._objects)){const t=e._objects.find(i=>i?.type==="line")??e._objects[0];return{stroke:t?.stroke,strokeWidth:t?.strokeWidth}}return this.isTextObject(e)?{stroke:e.fill??this.drawStyle.stroke,fontSize:e.fontSize??this.drawStyle.fontSize}:{stroke:e.stroke??this.drawStyle.stroke,strokeWidth:e.strokeWidth??this.drawStyle.strokeWidth}}isTextObject(e){return e?e.type==="i-text"||e.type==="textbox"||e.annotationType==="text":!1}createTextStyle(e){return{fontSize:e.fontSize,fill:e.stroke,stroke:this.getTextOutlineColor(e.stroke),strokeWidth:3,strokeLineJoin:"round",paintFirst:"stroke"}}getTextOutlineColor(e){return this.isWhiteTextColor(e)?"#000000":"#ffffff"}isWhiteTextColor(e){const t=e.trim().toLowerCase();if(t==="#fff"||t==="#ffffff"||t==="white")return!0;const i=t.match(/^rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})/);if(i){const[,s,r,o]=i;return Number(s)>=245&&Number(r)>=245&&Number(o)>=245}return!1}isInputElement(e){const t=e;if(!t||!t.tagName)return!1;const i=t.tagName.toLowerCase();return i==="input"||i==="textarea"||!!t.isContentEditable}applyCanvasInteractive(e){this.canvas.selection=e,this.canvas.getObjects().forEach(t=>{t.set({selectable:e,evented:e}),t.setCoords?.()}),this.canvas.discardActiveObject(),this.canvas.requestRenderAll()}parseNumber(e,t,i,s){const r=Number(e);return Number.isFinite(r)?Math.min(s,Math.max(i,r)):t}colorToAlpha(e,t){const i=e.trim(),s=/^#([0-9a-fA-F]{3})$/.exec(i);if(s){const o=s[1],a=parseInt(o[0]+o[0],16),l=parseInt(o[1]+o[1],16),c=parseInt(o[2]+o[2],16);return`rgba(${a}, ${l}, ${c}, ${t})`}const r=/^#([0-9a-fA-F]{6})$/.exec(i);if(r){const o=r[1],a=parseInt(o.slice(0,2),16),l=parseInt(o.slice(2,4),16),c=parseInt(o.slice(4,6),16);return`rgba(${a}, ${l}, ${c}, ${t})`}return this.drawStyle.fill}toggleMeasurePanel(){!this.isActive||this.mode!=="edit"||(this.isMeasurePanelExpanded=!this.isMeasurePanelExpanded,this.refreshToolbarState())}activateDistanceMeasure(e){if(!this.isActive||this.mode!=="edit")return;this.drawType="none",this.canvas.defaultCursor="default",this.isDistanceMeasureMode=!0,this.isMeasurePanelExpanded=!0,this.currentMeasureType=e,this.canvas.discardActiveObject(),this.canvas.requestRenderAll();const t=this.engine.measure;t?.active?.(),this.disActiveMeasureTools(t),this.activeMeasureTool(t,e),this.updateOverlayPointerEvents(),this.refreshToolbarState()}stopDistanceMeasureMode(){if(!this.isDistanceMeasureMode)return;const e=this.engine.measure;this.disActiveMeasureTools(e),this.isDistanceMeasureMode=!1,this.currentMeasureType=null,this.updateOverlayPointerEvents(),this.refreshToolbarState()}disActiveMeasureTools(e){e?.distanceMeasure?.disActive?.(),e?.faceDistanceMeasure?.disActive?.(),e?.clearHeightMeasure?.disActive?.(),e?.elevationMeasure?.disActive?.(),e?.pointMeasure?.disActive?.(),e?.angleMeasure?.disActive?.(),e?.areaMeasure?.disActive?.(),e?.slopeMeasure?.disActive?.()}activeMeasureTool(e,t){const s={distance:"distanceMeasure",clearDistance:"faceDistanceMeasure",clearHeight:"clearHeightMeasure",elevation:"elevationMeasure",point:"pointMeasure",angle:"angleMeasure",area:"areaMeasure",slope:"slopeMeasure"}[t];s&&e?.[s]?.active?.()}updateOverlayPointerEvents(){if(!this.isActive){this.wrapper.style.pointerEvents="none",this.canvasEl.style.pointerEvents="none";return}if(this.mode==="view"||this.isDistanceMeasureMode||!this.isViewLocked){this.wrapper.style.pointerEvents="none",this.canvasEl.style.pointerEvents="none",this.toolbar.root.style.pointerEvents="auto";return}this.wrapper.style.pointerEvents="auto",this.canvasEl.style.pointerEvents="auto",this.toolbar.root.style.pointerEvents="auto"}toggleViewLock(){!this.isActive||this.mode!=="edit"||this.isDistanceMeasureMode||(this.isViewLocked=!this.isViewLocked,this.isViewLocked?this.canvas.selection=!0:(this.startPoint=null,this.tempObject=null,this.cloudPoints=[],this.canvas.discardActiveObject(),this.canvas.selection=!1),this.canvas.requestRenderAll(),this.updateOverlayPointerEvents(),this.refreshToolbarState())}async handleCancelClick(){this.sessionSnapshot&&await this.restoreAllShapes(this.cloneJson(this.sessionSnapshot)),this.actionHandlers.onCancel?.(),this.disActive()}async handleCloseClick(){this.disActive()}handleConfirmClick(){const e=this.cloneJson(this.getAllShapes());this.actionHandlers.onConfirm?.(e),this.disActive()}refreshToolbarStyleValues(){this.toolbar.setStyleValues({stroke:this.drawStyle.stroke,strokeWidth:this.drawStyle.strokeWidth,fontSize:this.drawStyle.fontSize})}refreshToolbarState(){this.toolbar.setDrawType(this.drawType),this.toolbar.setMode(this.mode),this.toolbar.setMeasurePanelVisible(this.isMeasurePanelExpanded),this.toolbar.setMeasureState(this.isDistanceMeasureMode,this.currentMeasureType),this.toolbar.setEditPanelMasked(!this.isViewLocked),this.refreshToolbarStyleValues()}createScreenshotFileName(){const e=new Date,t=e.getFullYear(),i=String(e.getMonth()+1).padStart(2,"0"),s=String(e.getDate()).padStart(2,"0"),r=String(e.getHours()).padStart(2,"0"),o=String(e.getMinutes()).padStart(2,"0"),a=String(e.getSeconds()).padStart(2,"0");return`bim-snapshot-${t}${i}${s}-${r}${o}${a}.png`}cloneJson(e){return JSON.parse(JSON.stringify(e))}}class LR{engine;constructor(e){this.engine=e}get(){return{cameraPose:this.engine.cameraModule?.getCameraPose?.()??null,clipping:this.captureClippingState(),measureData:this.captureMeasureData(),annotationData:this.captureAnnotationData()}}async restore(e,t="view",i){if(!e){i?.(null);return}e.cameraPose&&this.engine.cameraModule?.restoreCameraPose?.(e.cameraPose),this.restoreClippingState(e.clipping),this.restoreMeasureData(e.measureData),await this.restoreAnnotationData(e.annotationData),this.applyAnnotationMode(t);const s=this.engine.fabricDraw;s&&s.setActionHandlers({onConfirm:r=>{const o=this.get();o.annotationData=this.serializeSnapshotValue(r),i&&i(o),this.clearAnnotation()},onCancel:()=>{this.clearAnnotation()}})}create(e){const t=this.engine.fabricDraw;if(!t){e?.(this.get());return}t.setActionHandlers({onConfirm:i=>{const s=this.get();s.annotationData=this.serializeSnapshotValue(i),e?.(s),this.clearAnnotation()},onCancel:()=>{this.clearAnnotation()}}),t.show?.(),t.active?.("edit"),t.setDrawType?.("none")}clearAnnotation(){this.engine.fabricDraw?.clearAllShapes?.(),this.engine.measure.disActive?.()}captureClippingState(){const e=this.engine.clipping,t=e?.sectionFace,i=e?.currentClippingMode??"",s={mode:i,fillCutFace:e?.getFillCutFace?.()??!0};if(i==="box"&&e?.sectionBox?.getboxXyz&&(s.box=e.sectionBox.getboxXyz()),i==="x"||i==="y"||i==="z"||i==="face"){const r=t?.normal;r&&(s.face={normal:{x:Number(r.x)||0,y:Number(r.y)||0,z:Number(r.z)||1},distance:Number(t?.distance)||0,direction:Number(t?.direction)===-1?-1:1})}return s}restoreClippingState(e){const t=this.engine.clipping;if(!t)return;typeof e?.fillCutFace=="boolean"&&t.setFillCutFace?.(e.fillCutFace);const i=e?.mode??"";if(!i){t.disActive?.();return}if(i==="box"){t.active?.("box"),e.box&&t.sectionBox?.setboxXyz?.(e.box);return}if(i==="x"||i==="y"||i==="z"){t.active?.(i),this.applyFaceState(e.face);return}if(i==="face"){this.restoreFaceMode(e.face);return}t.active?.(i)}restoreFaceMode(e){const t=this.engine.clipping,i=t?.sectionFace;!t||!i||(t.sectionBox?.disActive?.(),i.disActive?.(),i.active?.(),t.currentClippingMode="face",this.applyFaceState(e))}applyFaceState(e){if(!e)return;const t=this.engine.clipping?.sectionFace;if(!t)return;const i=new w.Vector3(e.normal.x,e.normal.y,e.normal.z).normalize();t.direction=e.direction===-1?-1:1,t.setFaceNormal?.(i,e.distance??0)}captureMeasureData(){const e=this.engine.measure?.annotationData;return e?this.serializeSnapshotValue(e):null}restoreMeasureData(e){const t=this.engine.measure;if(!t)return;try{t.clearAll?.()}catch{}if(!e)return;const i=this.deserializeSnapshotValue(e);(!t.annotationData||typeof t.annotationData!="object")&&(t.annotationData={}),Object.keys(t.annotationData).forEach(s=>{t.annotationData[s]=[]}),Object.keys(i).forEach(s=>{t.annotationData[s]=Array.isArray(i[s])?i[s]:[]}),t.tools?.drawNormalAnnotation?.()}captureAnnotationData(){const e=this.engine.fabricDraw;return e?.getAllShapes?this.serializeSnapshotValue(e.getAllShapes()):null}async restoreAnnotationData(e){const t=this.engine.fabricDraw;if(!t)return;if(!e){t.clearAllShapes?.();return}const i=this.deserializeSnapshotValue(e);await t.restoreAllShapes?.(i)}applyAnnotationMode(e){const t=this.engine.fabricDraw;t&&(t.setActionHandlers?.({}),t.show?.(),t.active?.(e),t.setDrawType?.("none"))}serializeSnapshotValue(e){if(e==null)return e;if(e instanceof w.Vector3)return{__type:"Vector3",x:e.x,y:e.y,z:e.z};if(Array.isArray(e))return e.map(t=>this.serializeSnapshotValue(t));if(typeof e=="object"){if(e instanceof HTMLElement||e instanceof SVGElement)return;const t={};return Object.keys(e).forEach(i=>{if(i==="container")return;const s=this.serializeSnapshotValue(e[i]);s!==void 0&&(t[i]=s)}),t}if(typeof e!="function")return e}deserializeSnapshotValue(e){if(e==null)return e;if(Array.isArray(e))return e.map(t=>this.deserializeSnapshotValue(t));if(typeof e=="object"){if(e.__type==="Vector3")return new w.Vector3(e.x,e.y,e.z);const t={};return Object.keys(e).forEach(i=>{t[i]=this.deserializeSnapshotValue(e[i])}),t}return e}}class RR{options;deviceType;animationId=null;isDisposed=!1;isRenderingPaused=!1;controlsEnabledBeforePause=!0;animate;onWindowResize;_fpsFrameCount=0;_fpsLastCheck=0;_fpsLastSwitch=0;_lowFpsCount=0;_highFpsCount=0;_fpsCheckInterval=100;_fpsSwitchCooldown=100;_fpsThreshold=30;_fpsUpgradeThreshold=60;_lowFpsRequired=5;_highFpsRequired=.1;isMouseDown=!1;isWheeling=!1;scene;camera;renderer;sceneModule;cameraModule;deviceModule;renderModule;controlModule;composerModule;loaderModule;engineStatus;events;lightModule;interactionModule;modelToolModule;worldToScreen;handelBehaved;octreeBox;controls;stats;catchSvg;engineModelModule;viewTree;merge2d;viewCube;rangeScale;setting;measure;clipping;modelTree;engineInfo;modelProperties;modelMapperBatch;modelEdge;ai;pathRoaming;hoverHighLight;minMap;grid;level;issueReport;text;hdr;ground;skyManager;linkElement2d3d;linkView2d3d;oneClickEncoding;fabricDraw;drawingPin;models=[];reactBoundingClientRect={left:0,top:0};version="3.7.14";versionEl=null;container;constructor(e){if(window.THREE=w,this.options=e,this.container=document.getElementById(e.containerId),!this.container)throw new Error(`Container ${e.containerId} not found`);if(this.engineModelModule=new R2(this),this.engineModelModule.init(),this.ai=new wP(this),this.deviceModule=new x_(this),this.deviceType=this.deviceModule.getDeviceType(),this.cameraModule=new wi(this),this.sceneModule=new A_(this),this.scene=this.sceneModule.scene,this.renderModule=new Y1(this),this.renderer=this.renderModule.createRenderer(),this.camera=this.cameraModule.orthographicCamera,this.scene.camera=this.camera,this.renderer){const r=this.renderer;r.interactionCullingEnabled=!0,r.interactionActive=!1,r.interactionRenderScene=this.scene,r.interactionFrameBudgetMs=this.options.interactionFrameBudgetMs??6,r.interactionSkipShadows=this.options.interactionSkipShadows??!0}this.controlModule=new nE(this),this.controlModule.switchDefaultMode(),this.controls=this.controlModule.orbitControls,this.clipping=new AP(this),this.clipping.init(),this.composerModule=new mE(this),this.composerModule.init(),this.events=new S2,this.engineStatus=new w2(this),this.engineStatus.init(),this.loaderModule=new _2(this),this.lightModule=new I2(this),this.lightModule.init(),this.viewCube=new Z2(this),this.viewCube.init(),this.options.showViewCube==!1&&this.viewCube.hide(),this.octreeBox=eD(this),this.rangeScale=new tD(this),this.rangeScale.init(),this.setting=new fD(this),this.engineModelModule.init(),this.handelBehaved=Rd(this),this.modelMapperBatch=new vP(this),this.measure=new wD(this),this.modelToolModule=new D2(this),this.modelProperties=new yP(this),this.interactionModule=new T2(this),this.interactionModule.init(),this.interactionModule.active(),this.hoverHighLight=new Ic(this),this.modelEdge=new uD(this),this.modelTree=new xP(this),this.viewTree=new PP(this),this.merge2d=new zP(this),this.engineInfo=new bP(this),this.pathRoaming=new SP(this),this.pathRoaming.init(),this.oneClickEncoding=new BP(this),this.minMap=new CP(this),this.linkElement2d3d=new IP(this),this.linkView2d3d=new TP(this),this.grid=new sD(this),this.level=new hD(this),this.issueReport=new MP(this),this.fabricDraw=new PR(this),this.drawingPin=new LR(this),this.text=new EP(this),this.hdr=new aD(this),this.ground=new mf(this),this.ground.init(),this.skyManager=new dD(this),this.setting.init(),this.worldToScreen=new rt(this.camera,this.renderer,this.scene),this.options.showStats&&(this.stats=new U2,this.stats.showPanel(0),this.stats.dom.style.position="absolute",this.stats.dom.style.top="0px",this.stats.dom.style.left="0px",this.stats.dom.style.zIndex="1000",this.container.appendChild(this.stats.dom));let t=document.createElement("div");t.className="versionText",this.versionEl=t,this.updateVersionDisplay(),this.container.appendChild(t);let i=document.createElementNS("http://www.w3.org/2000/svg","svg");i.style.position="absolute",i.style.zIndex="1000",i.style.left="0px",i.style.top="0px",i.style.pointerEvents="none",this.container.appendChild(i),this.catchSvg=i,this.onWindowResize=()=>{this.handleWindowResize()},window.addEventListener("resize",this.onWindowResize);let s=this;this.controls.addEventListener("start",()=>{s.renderer&&(s.renderer.interactionActive=!0),s.events.trigger(Ss.EngineBusy),s.container&&(s.container.style.cursor="none")}),this.controls.addEventListener("end",()=>{s.renderer&&(s.renderer.interactionActive=!1),s.events.trigger(Ss.EngineFree),s.container&&(s.container.style.cursor="default")}),this.controls.addEventListener("change",()=>{const r=new w.Vector3;s.camera.getWorldDirection(r);const o=Math.atan2(r.x,-r.z);let a=new CustomEvent("D3ViewUpdate",{detail:{position:s.camera.position,rotation:o,type:s.camera.type}});window.dispatchEvent(a)}),this.events.on(Ss.LoadingCompleted,r=>{s.modelEdge.active()}),this.animate=()=>{if(!this.isRenderingPaused)this.animationId=requestAnimationFrame(this.animate);else{this.animationId=null;return}this.stats&&this.stats.begin(),this.composerModule&&this.composerModule.composer.render(),this.viewCube&&this.viewCube.cubeTool.RenderScene(),this.measure.update(),this.ground.update(),this.skyManager.update(),this.hoverHighLight.update(),this.controlModule.update(),this.minMap.update(),this.grid.update(),this.level.update(),this.text&&this.text.update(),this.stats&&this.stats.end(),this._fpsFrameCount++;const r=performance.now();if(r-this._fpsLastCheck>=this._fpsCheckInterval){const o=r-this._fpsLastCheck,a=this._fpsFrameCount/o*1e3;this._fpsFrameCount=0,this._fpsLastCheck=r,a<this._fpsThreshold?(this._lowFpsCount++,this._highFpsCount=0,this._lowFpsCount>=this._lowFpsRequired&&r-this._fpsLastSwitch>this._fpsSwitchCooldown&&(this._adaptiveRenderingDowngrade(),this._fpsLastSwitch=r,this._lowFpsCount=0)):(this._lowFpsCount=0,this._highFpsCount=0)}if(this.scene){let o=this.scene?.dirLight;o&&this.camera&&this.updateLightPosition(this.camera,o)}},this.animate()}updateVersionDisplay(){if(!this.versionEl)return;const e={simple:"simple",balance:"balance",advanced:"advanced"},t=this.engineModelModule?.getCurrentMode()??"",i=e[t]??t;this.versionEl.innerHTML=`v${this.version} | ${i}`}updateLightPosition(e,t,i=!0){const s=new w.Vector3;e.getWorldDirection(s);const r=100,o=new w.Vector3().copy(s).multiplyScalar(-r),a=new w.Vector3(0,1,0),l=new w.Vector3().crossVectors(s,a).normalize();o.addScaledVector(a,r*.5),o.addScaledVector(l,r*.3),t.position.copy(e.position).add(o);const c=new w.Vector3().copy(e.position).add(s.multiplyScalar(20));t.target.position.copy(c),t.target.updateMatrixWorld()}_adaptiveRenderingDowngrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i>0){const s=e[i-1];console.log(`[AdaptiveRendering] FPS低于${this._fpsThreshold},自动降级: ${t} → ${s}`),this.engineModelModule.autoSwitch(s)}}_adaptiveRenderingUpgrade(){const e=["simple","balance","advanced"],t=this.engineModelModule.getCurrentMode(),i=e.indexOf(t);if(i<e.length-1){const s=e[i+1];console.log(`[AdaptiveRendering] FPS高于${this._fpsUpgradeThreshold},自动升级: ${t} → ${s}`),this.engineModelModule.autoSwitch(s)}}pauseRendering(){if(this.isRenderingPaused){console.warn("[BimEngine] Rendering is already paused");return}this.isRenderingPaused=!0,this.controls&&(this.controlsEnabledBeforePause=this.controls.enabled,this.controls.enabled=!1)}resumeRendering(){if(!this.isRenderingPaused){console.warn("[BimEngine] Rendering is not paused");return}this.isRenderingPaused=!1,this.controls&&(this.controls.enabled=this.controlsEnabledBeforePause),this.animationId===null&&this.animate()}isRenderingPausedState(){return this.isRenderingPaused}handleWindowResize(e,t){if(!this.container||!this.renderer||!this.camera)return;if(e===void 0||t===void 0){const c=this.deviceModule.getContainerSize();e=e??c.width,t=t??c.height}if(!e||!t)return;const i=this.camera.position.clone(),s=this.camera.quaternion.clone(),r=this.camera.up.clone(),o=this.controls?.target?.clone?.(),a=this.controlModule?.orbitControls?.origin?.clone?.();this.renderer.setPixelRatio(window.devicePixelRatio),this.renderer.setSize(e,t);const l=e/t;if(this.camera===this.cameraModule.perspectiveCamera)this.cameraModule.perspectiveCamera.aspect=l,this.cameraModule.perspectiveCamera.updateProjectionMatrix(),this.camera=this.cameraModule.perspectiveCamera;else if(this.camera===this.cameraModule.orthographicCamera){const c=this.cameraModule.orthographicCamera,h=this.cameraModule.getOrthographicVisibleHeight(c);this.cameraModule.setOrthographicVisibleHeight(h,c,l),c.updateProjectionMatrix()}if(this.composerModule&&(typeof this.composerModule.resize=="function"?this.composerModule.resize(e,t):this.composerModule.composer&&this.composerModule.composer.setSize(e,t)),this.catchSvg&&this.catchSvg.setAttribute("viewBox",`0 0 ${e} ${t}`),this.fabricDraw&&this.fabricDraw.resize(e,t),this.camera.position.copy(i),this.camera.quaternion.copy(s),this.camera.up.copy(r),this.camera.updateMatrix(),this.camera.updateMatrixWorld(!0),o&&this.controls?.target&&this.controls.target.copy(o),a&&this.controlModule?.orbitControls?.origin&&this.controlModule.orbitControls.origin.copy(a),this.controlModule?.orbitControls){const c=this.controlModule.orbitControls;c._lastPosition?.copy?.(this.camera.position),c._lastTarget?.copy?.(c.target),c._lastUp?.copy?.(this.camera.up),c._lastQuaternion?.copy?.(this.camera.quaternion),c._lastZoom=this.camera.zoom}this.controlModule?.firstPersonControls?.syncRotationStateFromCamera?.(),this.controlModule?.firstPersonControls?.syncSharedTargetFromCamera?.(),this.events&&this.events.trigger(Ss.ViewportResize,{width:e,height:t})}dispose(){if(this.isDisposed)return;this.isDisposed=!0,console.log("[BimEngine] Starting engine disposal..."),this.animationId!==null&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isRenderingPaused=!0,this.onWindowResize&&window.removeEventListener("resize",this.onWindowResize);try{this.invokeIfExists(this.rangeScale,"dispose"),this.invokeIfExists(this.measure,"dispose"),this.invokeIfExists(this.clipping,"disActive"),this.invokeIfExists(this.interactionModule,"dispose"),this.invokeIfExists(this.controlModule,"dispose"),this.invokeIfExists(this.pathRoaming,"dispose"),this.invokeIfExists(this.hoverHighLight,"dispose"),this.invokeIfExists(this.linkElement2d3d,"dispose"),this.invokeIfExists(this.linkView2d3d,"dispose"),this.invokeIfExists(this.skyManager,"close",!0),this.invokeIfExists(this.hdr,"dispose"),this.invokeIfExists(this.minMap,"dispose"),this.invokeIfExists(this.grid,"dispose"),this.invokeIfExists(this.level,"dispose"),this.invokeIfExists(this.ground,"dispose"),this.invokeIfExists(this.text,"dispose"),this.invokeIfExists(this.issueReport,"dispose"),this.invokeIfExists(this.fabricDraw,"dispose"),this.invokeIfExists(this.viewCube?.cubeTool,"dispose"),this.invokeIfExists(this.handelBehaved,"disActive")}catch(t){console.warn("[BimEngine] Error disposing managers:",t)}try{this.controlModule&&(this.controlModule.originDiv&&this.controlModule.originDiv.remove(),this.controlModule.orbitControls&&typeof this.controlModule.orbitControls.dispose=="function"&&this.controlModule.orbitControls.dispose(),this.controlModule.firstPersonControls&&typeof this.controlModule.firstPersonControls.dispose=="function"&&this.controlModule.firstPersonControls.dispose())}catch(t){console.warn("[BimEngine] Error disposing controls:",t)}this.scene&&(this.disposeSceneAttachments(this.scene),this.clearScene(this.scene));try{this.composerModule&&this.composerModule.composer&&(this.composerModule.composer.passes&&this.composerModule.composer.passes.forEach(t=>{t?.dispose?.()}),this.composerModule.composer.renderTarget1&&this.composerModule.composer.renderTarget1.dispose(),this.composerModule.composer.renderTarget2&&this.composerModule.composer.renderTarget2.dispose(),this.composerModule.composer.dispose?.(),this.composerModule.composer.passes=[])}catch(t){console.warn("[BimEngine] Error disposing composer:",t)}try{this.renderModule?.disposeRenderer?.(),this.renderer&&(this.renderer.renderLists?.dispose?.(),this.renderer.domElement&&this.renderer.domElement.parentElement&&this.renderer.domElement.parentElement.removeChild(this.renderer.domElement),this.renderer.dispose(),this.renderer.forceContextLoss())}catch(t){console.warn("[BimEngine] Error disposing renderer:",t)}try{this.stats?.dom?.parentElement&&this.stats.dom.parentElement.removeChild(this.stats.dom),this.catchSvg?.parentElement&&this.catchSvg.parentElement.removeChild(this.catchSvg),this.versionEl?.parentElement&&this.versionEl.parentElement.removeChild(this.versionEl)}catch(t){console.warn("[BimEngine] Error disposing DOM elements:",t)}try{this.events&&this.events.listeners&&this.events.listeners.clear()}catch(t){console.warn("[BimEngine] Error clearing event listeners:",t)}const e=this;e.scene=null,e.camera=null,e.renderer=null,e.controls=null,e.models=[],e.container=null,e.catchSvg=null,e.stats=null,e.versionEl=null,e.worldToScreen=null,e.measure=null,e.clipping=null,e.interactionModule=null,e.controlModule=null,e.sceneModule=null,e.cameraModule=null,e.deviceModule=null,e.renderModule=null,e.composerModule=null,e.loaderModule=null,e.lightModule=null,e.engineStatus=null,e.hoverHighLight=null,e.pathRoaming=null,e.hdr=null,e.skyManager=null,e.viewCube=null,e.grid=null,e.level=null,e.ground=null,e.minMap=null,e.fabricDraw=null,e.linkElement2d3d=null,e.linkView2d3d=null,e.rangeScale=null,e.text=null,e.issueReport=null,e.modelEdge=null,e.modelTree=null,e.modelProperties=null,e.modelMapperBatch=null,e.engineInfo=null,e.ai=null,e.oneClickEncoding=null,e.drawingPin=null,e.events=null,console.log("[BimEngine] Engine disposal completed")}clearScene(e){if(!e)return;[...e.children].forEach(i=>{this.clearScene(i)}),e.parent&&e.parent.remove(e),e instanceof w.Mesh&&!(e instanceof w.InstancedMesh)&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>this.disposeMaterial(i)):this.disposeMaterial(e.material))),e instanceof w.Line&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof w.Points&&(e.geometry&&e.geometry.dispose(),e.material&&this.disposeMaterial(e.material)),e instanceof w.InstancedMesh&&(e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach(i=>this.disposeMaterial(i)):this.disposeMaterial(e.material)),e.instanceMatrix&&(e.instanceMatrix=null),e.instanceColor&&(e.instanceColor=null)),e instanceof w.Sprite&&e.material&&this.disposeMaterial(e.material),e instanceof w.Light&&e.shadow?.dispose?.()}invokeIfExists(e,t,...i){const s=e?.[t];typeof s=="function"&&s.apply(e,i)}disposeSceneAttachments(e){new Set([e.background,e.environment,e.overrideMaterial]).forEach(i=>{this.disposeSceneAttachment(i)}),e.background=null,e.environment=null,e.overrideMaterial=null,e.dirLight=null,e.camera=null}disposeSceneAttachment(e){e&&(e instanceof w.Material||e instanceof w.Texture)&&e.dispose?.()}disposeMaterial(e){if(!e)return;["map","lightMap","bumpMap","normalMap","specularMap","envMap","alphaMap","aoMap","displacementMap","emissiveMap","gradientMap","metalnessMap","roughnessMap","clearcoatMap","clearcoatNormalMap","clearcoatRoughnessMap","transmissionMap","thicknessMap","sheenColorMap","sheenRoughnessMap","specularIntensityMap","specularColorMap","iridescenceMap","iridescenceThicknessMap"].forEach(i=>{const s=e[i];s&&s instanceof w.Texture&&s.dispose()}),e.dispose()}}const kR=`
6057
6057
  varying vec2 vWorldPos;
6058
6058
 
6059
6059
  void main() {