import{OrthographicCamera as e,Matrix4 as t,PerspectiveCamera as i,Float32BufferAttribute as n,Uint16BufferAttribute as s,Vector2 as r,Vector3 as a,BufferGeometry as o,Object3D as h,InstancedMesh as d,InstancedBufferAttribute as p,CylinderGeometry as l,MeshLambertMaterial as c,ConeGeometry as u,Color as g,ShaderChunk as f,UniformsLib as m,ShaderMaterial as w,ShaderLib as v,UniformsUtils as x,MultiplyOperation as y,NoBlending as M,DataTexture as b,RGBAFormat as E,Mesh as S,Group as T,AmbientLight as C,PointLight as _,Light as R,Scene as A,WebGLRenderTarget as P,FloatType as O,NormalBlending as L,WebGLMultipleRenderTargets as D,NearestFilter as z,ClampToEdgeWrapping as I,LinearEncoding as B,RedFormat as F,RawShaderMaterial as N,CustomBlending as U,OneMinusSrcAlphaFactor as G,OneFactor as H,AddEquation as k,LessDepth as j,ZeroFactor as V,Raycaster as W,DoubleSide as K,Triangle as Y,Quaternion as X,Box3 as q,Box2 as Z,MeshBasicMaterial as Q,Loader as $,LoaderUtils as J,Texture as ee,ImageLoader as te,Vector4 as ie,LineSegments as ne,LineBasicMaterial as se,Plane as re,NotEqualStencilFunc as ae,KeepStencilOp as oe,DepthTexture as he,DepthStencilFormat as de,UnsignedInt248Type as pe,AlwaysStencilFunc as le,BackSide as ce,IncrementWrapStencilOp as ue,FrontSide as ge,DecrementWrapStencilOp as fe,Material as me,Ray as we,Line as ve,EdgesGeometry as xe,Sprite as ye,SpriteMaterial as Me,CanvasTexture as be,SphereGeometry as Ee,Matrix3 as Se,Int32BufferAttribute as Te,DataArrayTexture as Ce,LinearFilter as _e,UnsignedByteType as Re,Uint32BufferAttribute as Ae,InstancedInterleavedBuffer as Pe,InterleavedBufferAttribute as Oe,PointsMaterial as Le,Points as De,MeshPhongMaterial as ze,Line3 as Ie,BoxGeometry as Be}from"three";import{v4 as Fe}from"uuid";import"polyfill-node16";import{Lut as Ne,LineMaterial as Ue,CopyShader as Ge,FullScreenQuad as He,Pass as ke,ShaderPass as je,FXAAShader as Ve,EffectComposer as We,PLYLoader as Ke,STLLoader as Ye,Stats as Xe,LineSegmentsGeometry as qe,LineSegments2 as Ze}from"supreium-threejs-examples";import Qe from"axios";import{toArrayBuffer as $e,adaptImage as Je,drawImage as et,createRenderer as tt}from"supreium-node-threejs";import{range as it}from"lodash-es";import nt from"number-precision";import{createCanvas as st}from"canvas";import{BidirectionMultipleValueMap as rt,BidirectionMap as at}from"bidirection-map";function ot(e){return void 0!==e.afterProjectionMatrix}class ht{handlers=[];add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter((t=>t!==e))}trigger(e){this.handlers.slice(0).forEach((t=>t(e)))}}const dt=1.732;class pt extends e{wrappedAfterProjectionMatrix=new t;wrappedOriginProjectMatrix=new t;cameraChangedEvent=new ht;constructor(e,t,i,n,s,r){super(e,t,i,n,s,r),this.updateProjectionMatrix()}get originProjectMatrix(){return this.wrappedOriginProjectMatrix}get afterProjectionMatrix(){return this.wrappedAfterProjectionMatrix}set afterProjectionMatrix(e){this.wrappedAfterProjectionMatrix.equals(e)||(this.wrappedAfterProjectionMatrix=e,this.updateProjectionMatrix())}raiseCameraChangeEvent(){this.cameraChangedEvent.trigger()}updateProjectionMatrix(){super.updateProjectionMatrix(),this.wrappedAfterProjectionMatrix&&(this.wrappedOriginProjectMatrix=this.projectionMatrix.clone(),this.projectionMatrix.copy(this.wrappedAfterProjectionMatrix.clone().multiply(this.projectionMatrix)),this.projectionMatrixInverse.copy(this.projectionMatrix).invert())}}class lt extends i{wrappedAfterProjectionMatrix=new t;wrappedOriginProjectMatrix=new t;cameraChangedEvent=new ht;constructor(e,t,i,n){super(e,t,i,n),this.updateProjectionMatrix()}get originProjectMatrix(){return this.wrappedOriginProjectMatrix}get afterProjectionMatrix(){return this.wrappedAfterProjectionMatrix}set afterProjectionMatrix(e){this.wrappedAfterProjectionMatrix.equals(e)||(this.wrappedAfterProjectionMatrix=e,this.updateProjectionMatrix())}raiseCameraChangeEvent(){this.cameraChangedEvent.trigger()}updateProjectionMatrix(){super.updateProjectionMatrix(),this.wrappedAfterProjectionMatrix&&(this.wrappedOriginProjectMatrix=this.projectionMatrix.clone(),this.projectionMatrix.copy(this.wrappedAfterProjectionMatrix.clone().multiply(this.projectionMatrix)),this.projectionMatrixInverse.copy(this.projectionMatrix).invert())}}const ct=[[0,0,0],[1,0,0],[0,1,0],[1,1,0],[0,0,1],[1,0,1],[0,1,1],[1,1,1]],ut=[[1,0,0],[0,1,0],[0,0,1],[-1,0,0],[0,-1,0],[0,0,-1]],gt=[[1,3,7],[1,7,5],[2,6,7],[2,7,3],[4,5,7],[4,7,6],[0,6,2],[0,4,6],[0,1,5],[0,5,4],[0,3,1],[0,2,3]],ft=[[3/4,1/3],[3/4,2/3],[.5,2/3],[3/4,1/3],[.5,2/3],[.5,1/3],[1/4,1],[1/4,2/3],[.5,2/3],[1/4,1],[.5,2/3],[.5,1],[1/4,1/3],[.5,1/3],[.5,2/3],[1/4,1/3],[.5,2/3],[1/4,2/3],[0,1/3],[1/4,2/3],[0,2/3],[0,1/3],[1/4,1/3],[1/4,2/3],[1/4,0],[.5,0],[.5,1/3],[1/4,0],[.5,1/3],[1/4,1/3],[1,1/3],[3/4,2/3],[3/4,1/3],[1,1/3],[1,2/3],[3/4,2/3]],mt=[[0,1],[2,3],[4,5],[6,7],[0,2],[1,3],[4,6],[5,7],[0,4],[2,6],[1,5],[3,7]],wt=[[5,7,10,11],[9,11,1,3],[2,3,7,6],[4,6,8,9],[8,10,0,2],[4,5,0,1]];function vt(e,t){if(0===e.length)throw Error("argument empty");const i=e.length*e[0].length;if(0===i)throw Error("argument empty");const s=new Array(i);let r=0;for(let t=0;t=0)t=[...gt[2*e],...gt[2*e+1]];else{t=new Array(36);for(let e=0;e<12;e+=1)[t[3*e],t[3*e+1],t[3*e+2]]=gt[e]}const i=new Array(3*t.length);for(let e=0;e=0?[e]:[0,1,2,3,4,5];const i=new Array(3*t.length*3*2);for(let e=0;e=0?[e]:[0,1,2,3,4,5];const i=new Array(3*t.length*2*2);for(let e=0;e=0){const t=wt[e],i=mt.filter(((e,i)=>t.indexOf(i)>=0));this.setIndex(xt(i,1))}}}class Ct extends h{constructor(){super(),this.type="AggregateObject"}}class _t extends d{beforeRaycast;afterRaycast;wrappedCount;constructor(e,t,i){super(e,t,i),this.wrappedCount=i,Object.defineProperty(this,"count",{get(){return this.wrappedCount},set(e){if(this.wrappedCount!==e){this.wrappedCount=e;const t=this.instanceMatrix;this.instanceMatrix=new p(new Float32Array(16*this.wrappedCount),16);for(let e=0;e{this.relocateArrow(t,e,o[t],h?h[t]:1,d?d[t]:1,p?p[t]:1,l?l[t]:1)}))}else{const o=e,h=t,d=i,p=n||i,l=s||i,c=r||n;this.heads.count=o.length/3,this.bodies.count=o.length/3;for(let e=0;e{this.bodies.setColorAt(t,e),this.heads.setColorAt(t,e)}));else for(let t=0;t{const{data:i,itemSize:n}=t,s=new Float32Array(e.length*n);for(let t=0;t{i[0]+=e.length>=2?2*(e.length-1):0}));const n=t=>{const{data:n,itemSize:s}=t,r=new Float32Array(i[0]*s),a=[0];if(e.forEach((e=>{if(e.length>=2)for(let t=1;te.order<=t));this.callbacks.splice(n+1,0,{fun:e,order:t,trait:i})}remove(e){const t=this.callbacks.findIndex((t=>t.fun===e));-1!==t&&this.callbacks.splice(t,1)}findTrait(e){const t=this.callbacks.findIndex((t=>t.trait?.src===e));if(-1!==t)return this.callbacks[t].trait}call=(e,t,i,n,s,r)=>{for(let a=0,o=this.callbacks.length;a{for(let a=this.callbacks.length-1;a>=0;a-=1)this.callbacks[a].fun(e,t,i,n,s,r,this.callbacks[a].trait)}}function It(e,t,i,n=0,s=void 0){const r=e;r.beforeRenderStack||(r.beforeRenderStack=new zt,r.originOnBeforeRender=e.onBeforeRender,r.beforeRenderStack.add(((e,t,i,n,s,a)=>{r.originOnBeforeRender?.(e,t,i,n,s,a)}),0),r.onBeforeRender=r.beforeRenderStack.call),r.afterRenderStack||(r.afterRenderStack=new zt,r.originOnAfterRender=e.onAfterRender,r.afterRenderStack.add(((e,t,i,n,s,a)=>{r.originOnAfterRender?.(e,t,i,n,s,a)}),0),r.onAfterRender=r.afterRenderStack.reverseCall),t&&r.beforeRenderStack.add(t,n,s),i&&r.afterRenderStack.add(i,n,s)}function Bt(e,t,i){const n=e;t&&n.beforeRenderStack?.remove(t),i&&n.afterRenderStack?.remove(i)}function Ft(e,t){const i=t;i.beforeRenderStack||(i.beforeRenderStack=new zt,i.beforeRenderStack.add(i.onBeforeRender,0),i.onBeforeRender=i.beforeRenderStack.call),i.afterRenderStack||(i.afterRenderStack=new zt,i.afterRenderStack.add(i.onAfterRender,0),i.onAfterRender=i.afterRenderStack.call);const n=e;n.beforeRenderStack&&(i.beforeRenderStack.callbacks.push(...n.beforeRenderStack.callbacks.slice(1)),n.beforeRenderStack.callbacks.splice(0,n.beforeRenderStack.callbacks.length)),n.afterRenderStack&&(i.afterRenderStack.callbacks.push(...n.afterRenderStack.callbacks.slice(1)),n.afterRenderStack.callbacks.splice(0,n.afterRenderStack.callbacks.length))}class Nt{obj;originAfterProjectMatrix=new t;anchorPoint=new a;bind(e){this.obj=e,It(e,this.onPreRendering,this.onPostRendering,5)}unbind(e){Bt(e,this.onPreRendering,this.onPostRendering),this.obj=void 0}onPreRendering=(e,i,n)=>{const s=n;if(s.afterProjectionMatrix&&this.obj){this.originAfterProjectMatrix=s.afterProjectionMatrix;const i=new a(this.anchorPoint.x,this.anchorPoint.y,this.anchorPoint.z).applyMatrix4(this.obj.modelViewMatrix),o=i.clone().applyMatrix4(s.originProjectMatrix),h=i.clone().applyMatrix4(n.projectionMatrix),d=new r(h.x-o.x,h.y-o.y),p=(new t).makeTranslation(d.x,d.y,0);s.afterProjectionMatrix=p,e.state.useProgram(null)}};onPostRendering=(e,t,i)=>{const n=i;n.afterProjectionMatrix&&this.obj&&(n.afterProjectionMatrix=this.originAfterProjectMatrix)}}var Ut;!function(e){e[e.Linear=0]="Linear",e[e.Nearest=1]="Nearest",e[e.NearestGreater=2]="NearestGreater"}(Ut||(Ut={}));class Gt{wrappedItems=[];wrappedMode=Ut.Linear;constructor(e){if(e instanceof Ne)this.wrappedItems=e.map.map((e=>{const t=e;return{color:new g(t[1]),anchorValue:t[0]}}));else{if(e.length<2)throw new Error("Color map must have at least 2 colors");this.wrappedItems=e.map(((t,i)=>t instanceof g?{color:t,anchorValue:i/(e.length-1)}:t))}}get mode(){return this.wrappedMode}set mode(e){this.wrappedMode=e}get items(){return this.wrappedItems}updateRange(e,t){const i=(t-e)/(this.wrappedItems.length-1);this.wrappedItems.forEach(((t,n)=>{t.anchorValue=e+i*n})),this.wrappedItems[this.wrappedItems.length-1].anchorValue=t}generateTable(e){switch(this.wrappedMode){case Ut.Linear:return this.generateLinearTable(e);case Ut.Nearest:return this.generateNearestTable(e);case Ut.NearestGreater:return this.generateNearestGreaterTable(e);default:throw new Error(`Unsupported lookup mode: ${this.wrappedMode}`)}}generateLinearTable(e){const t=this.wrappedItems[0].anchorValue,i=this.wrappedItems[this.wrappedItems.length-1].anchorValue-t,n=new Float32Array(4*e),s=1/(e-1)*i;let r=0;for(let e=0;e)([\s\S]*)/m,"\n#include \n","",void 0),t=Ht.patch(t,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0);let i=`#define USE_UV\n#define USE_MAP_ARRAY\n${v.basic.fragmentShader}`;i=Ht.patch(i,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),i=Ht.patch(i,/([\s\S]*)(vec4 diffuseColor = vec4\( diffuse, opacity \);)([\s\S]*)/m,"","","#include \n"),this.vertexShader=t,this.fragmentShader=i,this.uniforms=x.merge([v.basic.uniforms,m.mapArray]),kt(this,"opacity"),this.setValues(e),this.lights=!1}}var Vt;function Wt(){const e=f;e.color_map_pars_vertex||(e.color_map_pars_vertex="\n#define VERT_COLOR_MAP 1\n#define FRAG_COLOR_MAP 2\n#define DISCRETE_COLOR_MAP 3\n\n#if COLOR_MAP_MODE != 0\nattribute float value;\n#endif\n\n#if COLOR_MAP_MODE == VERT_COLOR_MAP\n\nuniform sampler2D colorMap;\nuniform float colorMapOffset;\nuniform float colorMapRatio;\n\nvarying vec4 frag_color;\n\n#elif COLOR_MAP_MODE == FRAG_COLOR_MAP || COLOR_MAP_MODE == DISCRETE_COLOR_MAP\n\nvarying float frag_value;\n\n#endif\n",e.color_map_line_segment_pars_vertex="\n#define VERT_COLOR_MAP 1\n#define FRAG_COLOR_MAP 2\n#define DISCRETE_COLOR_MAP 3\n\n#if COLOR_MAP_MODE != 0\nattribute float valueStart;\nattribute float valueEnd;\n#endif\n\n#if COLOR_MAP_MODE == VERT_COLOR_MAP\n\nuniform sampler2D colorMap;\nuniform float colorMapOffset;\nuniform float colorMapRatio;\n\nvarying vec4 frag_color;\n\n#elif COLOR_MAP_MODE == FRAG_COLOR_MAP || COLOR_MAP_MODE == DISCRETE_COLOR_MAP\n\nvarying float frag_value;\n\n#endif\n",e.line_segment_slice_pars_vertex="\n#ifdef ENABLE_SLICE\nattribute float lineIndex;\nattribute float lineLength;\nuniform float sliceRangeStart;\nuniform float sliceRangeEnd;\n#endif\n",e.color_map_vertex="\n#if COLOR_MAP_MODE == VERT_COLOR_MAP\n\tfrag_color = texture2D(colorMap,\n\t\t\tvec2((value + colorMapOffset) * colorMapRatio, 0.5));\n#elif COLOR_MAP_MODE == FRAG_COLOR_MAP || COLOR_MAP_MODE == DISCRETE_COLOR_MAP\n\tfrag_value = value;\n#endif\n",e.color_map_line_segment_vertex="\n\n#if COLOR_MAP_MODE != 0\nfloat value = ( position.y < 0.5 ) ? valueStart : valueEnd;\n#endif\n\n#if COLOR_MAP_MODE == VERT_COLOR_MAP\n\tfrag_color = texture2D(colorMap,\n\t\t\tvec2((value + colorMapOffset) * colorMapRatio, 0.5));\n#elif COLOR_MAP_MODE == FRAG_COLOR_MAP || COLOR_MAP_MODE == DISCRETE_COLOR_MAP\n\tfrag_value = value;\n#endif\n",e.line_segment_slice_vertex="\n#ifdef ENABLE_SLICE\n\tfloat left = sliceRangeStart < 0.0 ? lineLength + sliceRangeStart : sliceRangeStart;\n\tfloat right = sliceRangeEnd < 0.0 ? lineLength + sliceRangeEnd : sliceRangeEnd;\n\tfloat indexInRange = lineIndex - left;\n\tbool inRange = indexInRange >= 0.0 && indexInRange <= float(right - left);\n\tif(!inRange) {\n\t\treturn;\n\t}\n#endif\n",e.color_map_pars_fragment="\n#define VERT_COLOR_MAP 1\n#define FRAG_COLOR_MAP 2\n#define DISCRETE_COLOR_MAP 3\n\n#if COLOR_MAP_MODE == VERT_COLOR_MAP\nvarying vec4 frag_color;\n\n#elif COLOR_MAP_MODE == FRAG_COLOR_MAP || COLOR_MAP_MODE == DISCRETE_COLOR_MAP\nvarying float frag_value;\n\nuniform sampler2D colorMap;\nuniform float colorMapOffset;\nuniform float colorMapRatio;\n\n#endif\n",e.color_map_fragment="\n#if COLOR_MAP_MODE == 0\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n#elif COLOR_MAP_MODE== VERT_COLOR_MAP\n\tvec4 diffuseColor = frag_color;\n\tdiffuseColor.a = diffuseColor.a * opacity;\n#elif COLOR_MAP_MODE == FRAG_COLOR_MAP\n\tvec4 diffuseColor = texture2D(colorMap,\n\t\t\tvec2((frag_value + colorMapOffset) * colorMapRatio, 1.));\n\tdiffuseColor.a = opacity;\n#elif COLOR_MAP_MODE == DISCRETE_COLOR_MAP\n \tvec4 diffuseColor = texelFetch(colorMap, ivec2(frag_value, 0), 0);\n#endif\n",e.color_map_line_segment_fragment="\n#if COLOR_MAP_MODE == 0\n\tvec4 diffuseColor = vec4( diffuse, alpha );\n#elif COLOR_MAP_MODE== VERT_COLOR_MAP\n\tvec4 diffuseColor = frag_color;\n\tdiffuseColor.a = diffuseColor.a * alpha;\n#elif COLOR_MAP_MODE == FRAG_COLOR_MAP\n\tvec4 diffuseColor = texture2D(colorMap,\n\t\t\tvec2((frag_value + colorMapOffset) * colorMapRatio, 1.));\n\tdiffuseColor.a = alpha;\n#elif COLOR_MAP_MODE == DISCRETE_COLOR_MAP\n \tvec4 diffuseColor = texelFetch(colorMap, ivec2(frag_value, 0), 0);\n#endif\n");const t=m;t.colorMap||(t.colorMap={colorMap:{value:null},colorMapOffset:{value:0},colorMapRatio:{value:0}})}!function(e){e[e.None=0]="None",e[e.Vertex_Color_Map=1]="Vertex_Color_Map",e[e.Fragment_Color_Map=2]="Fragment_Color_Map",e[e.Discrete_Color_Map=3]="Discrete_Color_Map"}(Vt||(Vt={})),Wt();class Kt extends w{get colorMapMode(){return"COLOR_MAP_MODE"in this.defines?this.defines.COLOR_MAP_MODE:Vt.None}set colorMapMode(e){this.defines.COLOR_MAP_MODE=e,this.needsUpdate=!0}get colorMap(){return this.uniforms.colorMap.value}set colorMap(e){this.uniforms.colorMap.value=e}get colorMapOffset(){return this.uniforms.colorMapOffset.value}set colorMapOffset(e){this.uniforms.colorMapOffset.value=e}get colorMapRatio(){return this.uniforms.colorMapRatio.value}set colorMapRatio(e){this.uniforms.colorMapRatio.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}constructor(e){super(),this.type="ColorMapExLambertMaterial";let t=v.lambert.vertexShader;t=Ht.patch(t,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),t=Ht.patch(t,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0);let i=v.lambert.fragmentShader;i=Ht.patch(i,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),i=Ht.patch(i,/([\s\S]*)(vec4 diffuseColor = vec4\( diffuse, opacity \);)([\s\S]*)/m,"","","#include \n"),this.vertexShader=t,this.fragmentShader=i,this.lights=!0,this.clipping=!0,this.uniforms=x.merge([v.lambert.uniforms,m.colorMap]),kt(this,"opacity"),kt(this,"color","diffuse"),this.setValues(e)}copy(e){super.copy(e);const t=e;return this.colorMapMode=t.colorMapMode,this.colorMap=t.colorMap,this.colorMapOffset=t.colorMapOffset,this.colorMapRatio=t.colorMapRatio,this}}const Yt=new Set;function Xt(e){if(!e)throw Error("invalid shader material");const t={};return Object.entries(e).forEach((e=>{const[i,n]=e;if(!Yt.has(i))if(i.startsWith("wrapped")){const e=i[7].toLowerCase()+i.substring(8);t[e]={value:n}}else t[i]={value:n}})),t}Yt.add("uniforms"),Yt.add("vertexShader"),Yt.add("fragmentShader");var qt,Zt,Qt,$t;function Jt(){const e=f;e.stress_attr_pars_vertex||(e.stress_attr_pars_vertex="\n#define UX 1\n#define UY 2\n#define UZ 3\n#define MAG_U 4\n#define SIGMA 5\n\n#define SHRINK 1\n\n#if STRESS_SHRINK_MODE == SHRINK\n\nuniform vec3 shrinkPoint;\nuniform float shrinkDisplacementComponents[3];\nuniform float shrinkDisplacement;\nuniform float shrinkCoefficient;\n\n#endif\n\n#define TRANSFORMATION 1\n \n#if STRESS_TRANSFORMATION_MODE == TRANSFORMATION\n\nuniform vec3 oPosition;\nuniform float oDisplacement;\nuniform vec3 aPosition;\nuniform float aDisplacement;\nuniform vec3 bPosition;\nuniform float bDisplacement;\n\nmat3 transformationMat(vec3 oPos, float oDis, vec3 aPos, float aDis, vec3 bPos, float bDis) {\n vec3 oaVector = aPos - oPos;\n vec3 obVector = bPos - oPos;\n vec3 oabNormal = normalize(cross(oaVector,obVector));\n\n vec3 ooPosition = oPos + oDis;\n vec3 aoPosition = aPos + aDis;\n vec3 boPosition = bPos + bDis;\n\n vec3 oaOVector = aoPosition - ooPosition;\n vec3 obOVector = boPosition - ooPosition;\n vec3 oabONormal = normalize( cross(oaOVector,obOVector));\n \n vec3 axisRotate = normalize( cross(oabONormal,oabNormal));\n\n float cosTheta = dot(oabONormal,oabNormal);\n float sinTheta = sqrt(1.0 - pow(cosTheta,2.0));\n\n mat3 kMat = mat3(0.0, axisRotate.z, -axisRotate.y,\n -axisRotate.z,0.0,axisRotate.x,\n axisRotate.y, -axisRotate.x,0.0);\n\n return sinTheta * kMat + (1.0- cosTheta) * kMat * kMat;\n}\n\n#endif\n\n\n#if STRESS_ATTR_MODE == UX\n\nattribute float ux;\n\n#elif STRESS_ATTR_MODE == UY\n\nattribute float uy;\n\n#elif STRESS_ATTR_MODE == UZ\n\nattribute float uz;\n\n#elif STRESS_ATTR_MODE == MAG_U\n\nattribute float magu;\nattribute float ux;\nattribute float uy;\nattribute float uz;\n\n#elif STRESS_ATTR_MODE == SIGMA\n\nattribute float sigmaxx;\nattribute float sigmayy;\nattribute float sigmazz;\nattribute float sigmaxy;\nattribute float sigmaxz;\nattribute float sigmayz;\n\n#endif\n\n#define DISTANCE_DEFORMATION 1\n\n#if STRESS_DISTANCE_DEFORMATION == DISTANCE_DEFORMATION\n\nuniform float distanceScale; \n\n#endif\n\n",e.stress_attr_vertex="\n\n#if STRESS_ATTR_MODE == UX\n\n vGeneric = ux;\n\n #if STRESS_SHRINK_MODE == SHRINK\n\n vec3 newPosition = position - shrinkPoint;\n vGeneric -= shrinkDisplacement;\n vGeneric += shrinkCoefficient * newPosition.x;\n #endif\n\n #if STRESS_TRANSFORMATION_MODE == TRANSFORMATION\n \n mat3 rMat = transformationMat(oPosition, oDisplacement,aPosition, aDisplacement, bPosition, bDisplacement);\n vGeneric = vGeneric - oDisplacement + (rMat * (position - oPosition)).x;\n\n #endif\n\n #if STRESS_DISTANCE_DEFORMATION == DISTANCE_DEFORMATION\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position + vec3(vGeneric * distanceScale, 0.0, 0.0), 1.0);\n \n #endif \n#elif STRESS_ATTR_MODE == UY\n\n vGeneric = uy;\n\n #if STRESS_SHRINK_MODE == SHRINK\n\n vec3 newPosition = position - shrinkPoint; \n vGeneric -= shrinkDisplacement;\n vGeneric += shrinkCoefficient * newPosition.y;\n\n #endif\n\n #if STRESS_TRANSFORMATION_MODE == TRANSFORMATION\n \n mat3 rMat = transformationMat(oPosition, oDisplacement,aPosition, aDisplacement, bPosition, bDisplacement);\n vGeneric = vGeneric - oDisplacement + (rMat * (position - oPosition)).y;\n\n #endif\n\n #if STRESS_DISTANCE_DEFORMATION == DISTANCE_DEFORMATION\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position + vec3(0.0, vGeneric * distanceScale, 0.0), 1.0);\n \n #endif\n\n \n#elif STRESS_ATTR_MODE == UZ\n\n vGeneric = uz;\n \n #if STRESS_SHRINK_MODE == SHRINK\n\n vec3 newPosition = position - shrinkPoint;\n vGeneric -= shrinkDisplacement;\n vGeneric += shrinkCoefficient * newPosition.z; \n \n #endif\n\n #if STRESS_TRANSFORMATION_MODE == TRANSFORMATION\n \n mat3 rMat = transformationMat(oPosition, oDisplacement,aPosition, aDisplacement, bPosition, bDisplacement);\n vGeneric = vGeneric - oDisplacement + (rMat * (position - oPosition)).z;\n\n #endif\n\n #if STRESS_DISTANCE_DEFORMATION == DISTANCE_DEFORMATION\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position + vec3(0.0, 0.0, vGeneric * distanceScale), 1.0);\n \n #endif\n \n#elif STRESS_ATTR_MODE == MAG_U\n\n vGeneric = magu;\n\n #if STRESS_SHRINK_MODE == SHRINK\n vec3 newPosition = position - shrinkPoint;\n\n float uxValue = ux - shrinkDisplacementComponents[0] + shrinkCoefficient * newPosition.x;\n float uyValue = uy - shrinkDisplacementComponents[1] + shrinkCoefficient * newPosition.y;\n float uzValue = uz - shrinkDisplacementComponents[2] + shrinkCoefficient * newPosition.z;\n \n vGeneric = sqrt(pow(uxValue,2.0) + pow(uyValue,2.0) + pow(uzValue,2.0));\n\n #endif\n\n #if STRESS_TRANSFORMATION_MODE == TRANSFORMATION\n\n mat3 rMat = transformationMat(oPosition, oDisplacement,aPosition, aDisplacement, bPosition, bDisplacement);\n vGeneric = vGeneric - oDisplacement + length(rMat * (position - oPosition));\n \n #endif\n\n #if STRESS_DISTANCE_DEFORMATION == DISTANCE_DEFORMATION\n \n #if STRESS_SHRINK_MODE == SHRINK\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position + vec3(uxValue * distanceScale, uyValue * distanceScale, uzValue * distanceScale), 1.0);\n \n #else\n\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position + vec3(ux * distanceScale, uy * distanceScale, uz * distanceScale), 1.0);\n \n #endif\n\n #endif\n\n#elif STRESS_ATTR_MODE == SIGMA\n\n vGeneric = sqrt((pow(sigmaxx - sigmayy, 2.0) + pow(sigmayy - sigmazz, 2.0) + pow(sigmazz - sigmaxx, 2.0)) / 2.0 + 3.0 * (pow(sigmaxy, 2.0) + pow(sigmaxz, 2.0) + pow(sigmayz, 2.0)));\n\n#endif\n")}!function(e){e[e.None=0]="None",e[e.Ux=1]="Ux",e[e.Uy=2]="Uy",e[e.Uz=3]="Uz",e[e.MagU=4]="MagU",e[e.Sigma=5]="Sigma"}(qt||(qt={})),function(e){e[e.None=0]="None",e[e.Shrink=1]="Shrink"}(Zt||(Zt={})),function(e){e[e.None=0]="None",e[e.Transform=1]="Transform"}(Qt||(Qt={})),function(e){e[e.None=0]="None",e[e.Deformation=1]="Deformation"}($t||($t={})),Jt();class ei extends w{colorMapTexture;colorMapOffset;colorMapRatio;emissive;emissiveIntensity;emissiveMap;map;lightMap;lightMapIntensity;aoMap;aoMapIntensity;specularMap;alphaMap;envMap;combine;reflectivity;refractionRatio;colorInterpolatedVertex;stlIdTexture;stlIdLength;dataFilterOffset;dataFilterMin;dataFilterGroup;constructor(e,t,i,n){super(),this.map=null,this.reflectivity=1,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new g(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=y,this.reflectivity=1,this.refractionRatio=.98;const s=-e,r=1/(t-e);this.colorMapOffset=s,this.colorMapRatio=r,this.colorMapTexture=i,this.colorInterpolatedVertex=!1,this.stlIdTexture=null,this.stlIdLength=0,this.dataFilterOffset=0,this.dataFilterMin=0,this.dataFilterGroup=1,this.defines.STRESS_ATTR_MODE=qt.None,this.defines.STRESS_SHRINK_MODE=Zt.None,this.defines.STRESS_TRANSFORMATION_MODE=Qt.None,this.defines.STRESS_DISTANCE_DEFORMATION=$t.None,n&&this.setValues(n),this.updateUniforms()}get stressAttrMode(){return"STRESS_ATTR_MODE"in this.defines?this.defines.STRESS_ATTR_MODE:qt.None}set stressAttrMode(e){this.defines.STRESS_ATTR_MODE=e,this.needsUpdate=!0}updateStressShrinkMode(e,t){this.defines.STRESS_SHRINK_MODE=e,e===Zt.Shrink&&t&&(this.uniforms.shrinkPoint={value:t.point},this.uniforms.shrinkDisplacement={value:t.displacement},t.displacementComponents&&(this.uniforms.shrinkDisplacementComponents={value:t.displacementComponents}),this.uniforms.shrinkCoefficient={value:t.shrinkCoefficient}),this.needsUpdate=!0}updateStressTransformMode(e,t){this.defines.STRESS_TRANSFORMATION_MODE=e,e===Qt.Transform&&t&&(this.uniforms.oPosition={value:t.oPoint.position},this.uniforms.oDisplacement={value:t.oPoint.displacement},this.uniforms.aPosition={value:t.aPoint.position},this.uniforms.aDisplacement={value:t.aPoint.displacement},this.uniforms.bPosition={value:t.bPoint.position},this.uniforms.bDisplacement={value:t.bPoint.displacement},this.uniformsNeedUpdate=!0),this.needsUpdate=!0}updateStressDistanceDeformation(e,t){this.defines.STRESS_DISTANCE_DEFORMATION=e,e===$t.Deformation&&t&&(this.uniforms.distanceScale={value:t.distanceScale},this.uniformsNeedUpdate=!0),this.needsUpdate=!0}updateRange(e,t,i=0){const n=1/(t-e),s=-e+i;this.uniforms.colorMapOffset={value:s},this.uniforms.colorMapRatio={value:n}}updateTexture(e){this.colorMapTexture=e,this.uniforms.colorMapTexture.value=e,this.uniformsNeedUpdate=!0}updateStlIdTexture(e,t){this.stlIdTexture=e,this.stlIdLength=t,this.uniforms.stlIdTexture.value=e,this.uniforms.stlIdLength.value=t,this.uniformsNeedUpdate=!0}updateFilter(e,t,i=1){this.dataFilterOffset=t-e,this.dataFilterMin=e,this.dataFilterGroup=i,this.uniforms.dataFilterOffset={value:t-e},this.uniforms.dataFilterMin={value:e},this.uniforms.dataFilterGroup={value:i}}updateOpacity(e){this.uniforms.opacity.value=e,this.transparent=e<1}copy(e){super.copy(e);const t=e;if(!t)throw Error("invalid input");return this.map=t.map,this.lightMap=t.map,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive=t.emissive,this.emissiveIntensity=t.emissiveIntensity,this.emissiveMap=t.emissiveMap,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.colorMapTexture=t.colorMapTexture,this.colorMapOffset=t.colorMapOffset,this.colorMapRatio=t.colorMapRatio,this.colorInterpolatedVertex=t.colorInterpolatedVertex,this.stlIdTexture=t.stlIdTexture,this.stlIdLength=t.stlIdLength,this.dataFilterOffset=t.dataFilterOffset,this.dataFilterMin=t.dataFilterMin,this.dataFilterMin=t.dataFilterGroup,this.updateUniforms(),this}updateUniforms(){this.uniforms=x.merge([v.lambert.uniforms,Xt(this)]),this.vertexShader="\n#define LAMBERT\n\nvarying vec3 vViewPosition;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nattribute float generic;\nattribute float generic2; \n\nattribute float stl_id;\n\nuniform sampler2D colorMapTexture;\nuniform float colorMapOffset;\nuniform float colorMapRatio;\nuniform bool colorInterpolatedVertex;\n\nvarying float vGeneric;\nvarying float vGeneric2;\nvarying vec4 vColor;\nvarying float v_StlId;\n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\t#include \n\t\n\t#include \n\t\n\tif (colorInterpolatedVertex) {\n\t\tvColor = texture2D(colorMapTexture,\n\t\t\tvec2((generic + colorMapOffset) * colorMapRatio, 1.));\n\t} else {\n\t\tvGeneric = generic;\n\t};\n\tv_StlId = stl_id;\n\tvGeneric2 = generic2;\n\t#include \n}\n",this.fragmentShader="\n#define LAMBERT\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nuniform sampler2D colorMapTexture;\nuniform float colorMapOffset;\nuniform float colorMapRatio;\nuniform bool colorInterpolatedVertex;\nuniform sampler2D stlIdTexture;\nuniform float stlIdLength;\nuniform float dataFilterMin;\nuniform float dataFilterOffset;\nuniform float dataFilterGroup;\n\nvarying float vGeneric;\nvarying float vGeneric2;\nvarying vec4 vColor;\nvarying float v_StlId;\nfloat DataFilterPrivate(in float param, in float minNum, in float offset) {\n\tfloat filter_min = minNum;\n\tfloat filter_max = minNum + offset;\n\tif(param > filter_max || param < filter_min ) return 1.;\n\treturn 0.;\n}\n\n#define dataFilterPrivate DataFilterPrivate\n\nvoid main() {\n\n\t#include \n\n\tvec4 diffuseColor;\n\t\n\tbool stl_id = v_StlId > -1.;\n\tbool stl_id_length = bool(stlIdLength);\n\tif (stl_id && stl_id_length) {\n\t\tvec4 idFlag = texture2D(stlIdTexture,\n\t\t\tvec2(v_StlId / stlIdLength , 1.));\n\t\tbool visualForStlId = bool(idFlag.x);\n\t\tif (!visualForStlId) discard;\n\t};\n\n\tfloat genericForFilter = vGeneric;\n\tif(dataFilterGroup == 2.0) genericForFilter = vGeneric2;\n\tif(bool(dataFilterOffset)) {\n\t\tfloat boolFilter = dataFilterPrivate(genericForFilter, dataFilterMin, dataFilterOffset);\n\t\tif(bool(boolFilter)) discard;\n\t}\n\n\n\tif (colorInterpolatedVertex) {\n\t\tdiffuseColor = vec4( vec3(vColor), opacity );\n\t} else {\n\t\tvec4 color = texture2D(colorMapTexture,\n\t\t\tvec2((vGeneric + colorMapOffset) * colorMapRatio, 1.));\n\n\t\tdiffuseColor = vec4( vec3(color), opacity );\n\t};\n\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n}\n",this.needsUpdate=!0}}Wt();class ti extends w{get colorMapMode(){return"COLOR_MAP_MODE"in this.defines?this.defines.COLOR_MAP_MODE:Vt.None}set colorMapMode(e){this.defines.COLOR_MAP_MODE=e,this.needsUpdate=!0}get colorMap(){return this.uniforms.colorMap.value}set colorMap(e){this.uniforms.colorMap.value=e}get colorMapOffset(){return this.uniforms.colorMapOffset.value}set colorMapOffset(e){this.uniforms.colorMapOffset.value=e}get colorMapRatio(){return this.uniforms.colorMapRatio.value}set colorMapRatio(e){this.uniforms.colorMapRatio.value=e}get emissive(){return this.uniforms.emissive.value}set emissive(e){this.uniforms.emissive.value=e}get specular(){return this.uniforms.specular.value}set specular(e){this.uniforms.specular.value=e}get shininess(){return this.uniforms.shininess.value}set shininess(e){this.uniforms.shininess.value=e}constructor(e){super(),this.type="ColorMapPhongMaterial";let t=v.phong.vertexShader;t=Ht.patch(t,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),t=Ht.patch(t,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0);let i=v.phong.fragmentShader;i=Ht.patch(i,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),i=Ht.patch(i,/([\s\S]*)(vec4 diffuseColor = vec4\( diffuse, opacity \);)([\s\S]*)/m,"","","#include "),this.vertexShader=t,this.fragmentShader=i,this.lights=!0,this.clipping=!0,this.uniforms=x.merge([v.phong.uniforms,m.colorMap]),kt(this,"opacity"),kt(this,"color","diffuse"),this.setValues(e)}copy(e){super.copy(e);const t=e;return this.colorMapMode=t.colorMapMode,this.colorMap=t.colorMap,this.colorMapOffset=t.colorMapOffset,this.colorMapRatio=t.colorMapRatio,this}}class ii extends w{colorMapTexture;colorMapOffset;colorMapRatio;emissive;emissiveIntensity;emissiveMap;map;level=1;dagTex;attTex;lo;cellsize;newshape;res;dataInvalid;lightMap;lightMapIntensity;aoMap;aoMapIntensity;specularMap;alphaMap;envMap;combine;reflectivity;refractionRatio;clipMatrix;clipMatrixNorm;dataFilterOffset;dataFilterMin;dataFilterGroup;constructor(e,i,n,s,r,a,o,h,d,p,l){super(),this.map=null,this.reflectivity=1,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new g(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=y,this.reflectivity=1,this.refractionRatio=.98,this.level=n;const c=-e,u=1/(i-e);this.colorMapOffset=c,this.colorMapRatio=u,this.colorMapTexture=s,this.dataFilterOffset=0,this.dataFilterMin=0,this.dataFilterGroup=1,this.dagTex=r,this.attTex=a,this.lo=o,this.res=h,this.cellsize=d,this.newshape=p,this.dataInvalid=0,this.clipMatrix=new t,this.clipMatrixNorm=new t,l&&this.setValues(l),this.updateUniforms()}setDataInvalid(e){this.dataInvalid=e,this.uniforms.dataInvalid.value=e}updateRange(e,t,i=0){const n=1/(t-e),s=-e+i;this.uniforms.colorMapOffset={value:s},this.uniforms.colorMapRatio={value:n}}updateFilter(e,t,i=1){this.dataFilterOffset=t-e,this.dataFilterMin=e,this.dataFilterGroup=i,this.uniforms.dataFilterOffset={value:t-e},this.uniforms.dataFilterMin={value:e},this.uniforms.dataFilterGroup={value:i}}copy(e){super.copy(e);const t=e;if(!t)throw Error("invalid input");return this.map=t.map,this.lightMap=t.map,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive=t.emissive,this.emissiveIntensity=t.emissiveIntensity,this.emissiveMap=t.emissiveMap,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.colorMapTexture=t.colorMapTexture,this.colorMapOffset=t.colorMapOffset,this.colorMapRatio=t.colorMapRatio,this.clipMatrix=t.clipMatrix,this.clipMatrixNorm=t.clipMatrixNorm,this.dataFilterOffset=t.dataFilterOffset,this.dataFilterMin=t.dataFilterMin,this.dataFilterMin=t.dataFilterGroup,this.dagTex=t.dagTex,this.attTex=t.attTex,this.lo=t.lo,this.res=t.res,this.cellsize=t.cellsize,this.newshape=t.newshape,this.level=t.level,this.updateUniforms(),this}updateUniforms(){this.uniforms=x.merge([v.lambert.uniforms,Xt(this)]),this.vertexShader="\n#define LAMBERT\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\nvarying vec3 vViewPosition;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nuniform mat4 clipMatrix;\n\nvarying vec4 vWorldPos;\nvarying mat4 vMVPMatrix;\n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t\tvWorldPos = clipMatrix*vec4(transformed,1.0);\n vMVPMatrix = projectionMatrix * modelViewMatrix;\n\t\t\n\t#include \n\t#include \n\n\tvViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\t#include \n\t#include \n}\n",this.fragmentShader="\nprecision highp float;\nprecision mediump usampler3D;\nprecision mediump sampler3D;\nprecision mediump isampler3D;\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nuniform sampler2D colorMapTexture;\nuniform usampler3D dagTex;\nuniform isampler3D attTex;\nuniform vec3 lo;\nuniform vec3 newshape;\nuniform vec3 cellsize;\nuniform int res;\nuniform mat4 clipMatrix;\n\nuniform int dataInvalid;\n\n#define MAXITER 500\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint dagTexLen;\nint attTexLen;\n\nuniform float colorMapOffset;\nuniform float colorMapRatio;\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\nvarying vec4 vWorldPos;\nvarying mat4 vMVPMatrix;\n\nint GetIdx(vec3 idx);\nvoid initTextures();\nivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset);\nint sample_att(isampler3D aT, int aTLen, int offset);\nint MapToSurf (vec3 target,usampler3D dT, int dTLen, isampler3D aT, int aTLen, vec3 minPos, int resolution, vec3 space);\nvoid shade(out vec4 color);\n\nvoid main() {\n\n\t#include \n\tvec4 diffuseColor = vec4( vec3(1.0), 0.0 );\n\tinitTextures();\n\n\tshade(diffuseColor);\n\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// modulation\n\t#include \n\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvec4 ndc = (vMVPMatrix * (inverse(clipMatrix) * vWorldPos));\n\tgl_FragDepthEXT = diffuseColor.a > 0.0001 ? 0.5*ndc.z/ndc.w+0.5 : 1000.0;\n}\n\nvoid initTextures() {\n\tdagTexLen = textureSize(dagTex,0).y;\n\tattTexLen = textureSize(attTex,0).y;\n}\n\nint GetIdx(vec3 idx) {\n\treturn int(dot(idx*0.5+0.5,vec3(1.0,2.0,4.0)));\n}\n\nivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset) {\n\tint dTLenH = dTLen/2;\n\tint dTLenH2 = dTLenH * dTLenH;\n\tint z = dagPos / dTLenH2;\n\tint y = (dagPos - z * dTLenH2) / dTLenH;\n\tint x = dagPos - y * dTLenH - z * dTLenH2;\n\n\tint zz = offset / 4;\n\tint yy = (offset - zz * 4) / 2;\n\tint xx = offset - yy * 2 - zz * 4;\n\n\treturn ivec2(texture(dT, (vec3(2*x+xx, 2*y+yy, 2*z+zz)+0.5)/vec3(dTLen)).rg);\n}\n\nint sample_att(isampler3D aT, int aTLen, int offset) {\n\tint aTLen2 = aTLen*aTLen;\n\tint z = offset/aTLen2;\n\tint y = (offset - aTLen2*z)/aTLen;\n\tint x = offset - aTLen*y - aTLen2*z;\n\n\treturn int(texture(aT, (vec3(x,y,z)+0.5)/float(aTLen)).r);\n}\n\nint MapToSurf (\n\tvec3 target,\n\tusampler3D dT,\n\tint dTLen,\n\tisampler3D aT,\n\tint aTLen,\n\tvec3 minPos,\n\tint resolution,\n\tvec3 space) \n{\n\tvec3 size = float(resolution)*space;\n\tvec3 pos = minPos + size/2.0;\n\tint result = 0;\n\n\tint voxIdx = 0;\n\tint voxOffset = 0;\n\tint isLeaf = 1;\n\tivec2 nodeInfo;\n\n int maxIter = int(log2(float(res)));\n\n\tint iter = MAXITER;\n\twhile (iter --\x3e 0) {\n if (MAXITER - iter > maxIter+1) {\n \tbreak;\n }\n\t\tvec3 idx = vec3(-1.0) + 2.0*vec3(greaterThanEqual(target, pos));\n\t\tint idxOffset = GetIdx(idx);\n\t\tnodeInfo = sample_dag(dT, dTLen, voxIdx, idxOffset);\n\t\tisLeaf = nodeInfo.r;\n\t\tvoxOffset += isLeaf;\n\t\tresult = sample_att(aT, aTLen, voxOffset);\n\t\tsize *= 0.5;\n\t\tpos += 0.5 * size * idx;\n\t\tif (isLeaf==0) {\n\t\t\treturn result;\n\t\t}\n\t\tvoxIdx = nodeInfo.g;\n\t}\n\treturn result;\n}\n\nvoid shade(out vec4 color) {\n\tif (any(greaterThan(vWorldPos.xyz, vec3(lo+cellsize*float(res))))||any(lessThan(vWorldPos.xyz, vec3(lo)))) {\n\t\tcolor = vec4( vec3(1.0), 0.0 );\n\t\treturn;\n\t}\n\n\tint property = 0;\n\n\tproperty = MapToSurf(vWorldPos.xyz, dagTex, dagTexLen, attTex, attTexLen, lo, res, cellsize);\n\tvec4 sampledColormap = texture2D(colorMapTexture,\n\t\tvec2((float(property) + colorMapOffset) * colorMapRatio, 1.));\n\n\tfloat finalAlpha;\n\tif (int(property)==dataInvalid) {finalAlpha = 0.0;}\n\telse {finalAlpha = opacity;}\n\n\tcolor = vec4( sampledColormap.xyz, finalAlpha );\n}\n",this.uniforms.clipMatrix.value=this.clipMatrix,this.uniforms.dagTex.value=this.dagTex,this.uniforms.attTex.value=this.attTex}}class ni extends w{emissive;emissiveIntensity;emissiveMap;dagTex;attTex;lhTex;lightMap;lightMapIntensity;aoMap;aoMapIntensity;specularMap;alphaMap;envMap;combine;reflectivity;refractionRatio;clipMatrix;dataFilterOffset;dataFilterMin;dataFilterGroup;lo;cellsize;newshape;res;constructor(e,i,n,s,r,a,o,h){super(),this.reflectivity=1,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new g(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=y,this.reflectivity=1,this.refractionRatio=.98,this.dataFilterOffset=0,this.dataFilterMin=0,this.dataFilterGroup=1,this.dagTex=e,this.attTex=i,this.lhTex=n,this.lo=s,this.res=r,this.cellsize=a,this.newshape=o,this.clipMatrix=new t,h&&this.setValues(h),this.updateUniforms()}updateFilter(e,t,i=1){this.dataFilterOffset=t-e,this.dataFilterMin=e,this.dataFilterGroup=i,this.uniforms.dataFilterOffset={value:t-e},this.uniforms.dataFilterMin={value:e},this.uniforms.dataFilterGroup={value:i}}copy(e){super.copy(e);const t=e;if(!t)throw Error("invalid input");return this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive=t.emissive,this.emissiveIntensity=t.emissiveIntensity,this.emissiveMap=t.emissiveMap,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.clipMatrix=t.clipMatrix,this.dataFilterOffset=t.dataFilterOffset,this.dataFilterMin=t.dataFilterMin,this.dataFilterMin=t.dataFilterGroup,this.dagTex=t.dagTex,this.attTex=t.attTex,this.lhTex=t.lhTex,this.lo=t.lo,this.res=t.res,this.cellsize=t.cellsize,this.newshape=t.newshape,this.updateUniforms(),this}updateUniforms(){this.uniforms=x.merge([v.lambert.uniforms,Xt(this)]),this.vertexShader="\n#define LAMBERT\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\n\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nuniform mat4 clipMatrix;\nuniform mat4 clipMatrixNorm;\nuniform float linewidth;\nuniform vec2 resolution;\n\nvarying vec4 vWorldPos;\nvarying mat4 vMVPMatrix;\n\nvoid main() {\n\n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\n\t\tvWorldPos = clipMatrix*vec4(transformed,1.0);\n vMVPMatrix = projectionMatrix * modelViewMatrix;\n\t\t\n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n}\n",this.fragmentShader="\nprecision mediump sampler3D;\nprecision mediump usampler3D;\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nuniform usampler3D dagTex;\nuniform usampler3D attTex;\nuniform usampler3D lhTex;\nuniform vec3 lo;\nuniform vec3 newshape;\nuniform vec3 cellsize;\nuniform int res;\n\n#define MAXITER 500\n\nint dagTexLen;\nint attTexLen;\nint lhTexLen;\nuniform vec4 gridRes;\nvec3 worldPosNorm;\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\nvarying vec4 vWorldPos;\nvarying mat4 vMVPMatrix;\nuniform mat4 clipMatrix;\n\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n\tvarying vec3 vIndirectBack;\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint GetIdx(vec3 idx);\nivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset);\nint sample_att(usampler3D aT, int aTLen, int offset);\nbool sampleLH (in int idx, out vec3 lo, out vec3 hi);\nint MapToSurf (vec3 target, usampler3D dT, int dTLen, usampler3D aT, int aTLen, vec3 minPos, int resolution, vec3 space);\nvec3 standardToAlpha(in vec3 standard);\nvec3 Grid(in vec3 lo, in vec3 hi);\n\nvoid main() {\n\n\tdagTexLen = textureSize(dagTex,0).y;\n\tattTexLen = textureSize(attTex,0).y;\n\tlhTexLen = textureSize(lhTex,0).y;\n worldPosNorm = (vWorldPos.xyz-lo)/(newshape*cellsize);\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t// accumulation\n\n\t#include \n\n\t// modulation\n\n\t#include \n\t#include \n\n\tint idx = MapToSurf(vWorldPos.xyz, dagTex, dagTexLen, attTex, attTexLen, lo, res, cellsize);\n\tvec3 l;\n\tvec3 h;\n\tfloat a = 0.0;\n\tif (sampleLH(idx, l, h)) {\n\t\ta = dot(Grid(l, h),vec3(1.0));\n\t}\n\n\tgl_FragColor = vec4(vec3(0.6),a);\t\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n vec4 ndc = (vMVPMatrix * (inverse(clipMatrix) * vWorldPos));\n gl_FragDepthEXT = a > 0.0 ? 0.5*ndc.z/ndc.w+0.5 : 1000.0;\n}\n\nint GetIdx(vec3 idx) {\n\treturn int(dot(idx*0.5+0.5,vec3(1.0,2.0,4.0)));\n}\n\nivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset) {\n int dTLenH = dTLen/2;\n int dTLenH2 = dTLenH * dTLenH;\n int z = dagPos / dTLenH2;\n int y = (dagPos - z * dTLenH2) / dTLenH;\n int x = dagPos - y * dTLenH - z * dTLenH2;\n\n int zz = offset / 4;\n int yy = (offset - zz * 4) / 2;\n int xx = offset - yy * 2 - zz * 4;\n\t\n\treturn ivec2(texture(dT, (vec3(2*x+xx, 2*y+yy, 2*z+zz)+0.5)/vec3(dTLen)).rg);\n}\n\nint sample_att(usampler3D aT, int aTLen, int offset) {\n\tint aTLen2 = aTLen*aTLen;\n\tint z = offset/aTLen2;\n\tint y = (offset - aTLen2*z)/aTLen;\n\tint x = offset - aTLen*y - aTLen2*z;\n\n\treturn int(texture(aT, (vec3(x,y,z)+0.5)/float(aTLen)).r);\n}\n\nbool sampleLH (in int idx, out vec3 lo, out vec3 hi) {\n\tif (idx == 0) {return false;}\n\tint newIdx = idx-1;\n\tlo.x = float(sample_att(lhTex, lhTexLen, 6*newIdx));\n\tlo.y = float(sample_att(lhTex, lhTexLen, 6*newIdx+1));\n\tlo.z = float(sample_att(lhTex, lhTexLen, 6*newIdx+2));\n\thi.x = float(sample_att(lhTex, lhTexLen, 6*newIdx+3));\n\thi.y = float(sample_att(lhTex, lhTexLen, 6*newIdx+4));\n\thi.z = float(sample_att(lhTex, lhTexLen, 6*newIdx+5));\n\treturn true;\n}\n\nint MapToSurf (\n\tvec3 target,\n\tusampler3D dT,\n\tint dTLen,\n\tusampler3D aT,\n\tint aTLen,\n\tvec3 minPos,\n\tint resolution,\n\tvec3 space) \n{\n\tvec3 size = float(resolution)*space;\n\tvec3 pos = minPos + size/2.0;\n\tint result = 0;\n\n\tint voxIdx = 0;\n\tint voxOffset = 0;\n\tint isLeaf = 1;\n\tivec2 nodeInfo;\n\n int maxIter = int(log2(float(res)));\n\n\tint iter = MAXITER;\n\twhile (iter --\x3e 0) {\n if (MAXITER - iter > maxIter+1) {\n break;\n }\n\t\tvec3 idx = vec3(-1.0) + 2.0*vec3(greaterThanEqual(target, pos));\n\t\tint idxOffset = GetIdx(idx);\n\t\tnodeInfo = sample_dag(dT, dTLen, voxIdx, idxOffset);\n\t\tisLeaf = nodeInfo.r;\n\t\tvoxOffset += isLeaf;\n\t\tresult = sample_att(aT, aTLen, voxOffset);\n\t\tsize *= 0.5;\n\t\tpos += 0.5 * size * idx;\n\t\tif (isLeaf==0) {\n\t\t\treturn result;\n\t\t}\n\t\tvoxIdx = nodeInfo.g;\n\t}\n\treturn result;\n}\n\n\nvec3 standardToAlpha(in vec3 standard) {\n\tvec3 ep0 = standard + fwidth(worldPosNorm)*1.5;\n\tvec3 ep1 = standard - fwidth(worldPosNorm)*1.5;\n\tvec3 epMin = min(ep0, ep1);\n\tvec3 epMax = max(ep0, ep1);\n\tvec3 center = (epMin + epMax) / 2.0;\n\treturn smoothstep(epMin, center, worldPosNorm)*smoothstep(-epMax, -center, -worldPosNorm);\n}\n\nvec3 Grid(in vec3 l, in vec3 h) {\n\tvec3 resPhysics = newshape*worldPosNorm;\n\tvec3 idx = vec3(int(resPhysics.x), int(resPhysics.y), int(resPhysics.z));\n\n\tbool outofbox = (any(lessThan(idx, l))||any(greaterThan(idx, h)));\n\tbool outofbound = any(greaterThan(worldPosNorm, vec3(1)))||any(lessThan(worldPosNorm, vec3(0)));\n\tif (outofbox||outofbound) {return vec3(0);}\n\tvec3 res0 = standardToAlpha( idx/newshape );\n\tvec3 res1 = standardToAlpha( (idx+1.0)/newshape );\n\n\treturn res0+res1;\n}\n",this.uniforms.clipMatrix.value=this.clipMatrix}}class si extends w{colorMapTexture;colorMapOffset;colorMapRatio;emissive;emissiveIntensity;emissiveMap;map;dagTex;attTex;vofdagTex;vofattTex;lo;res;cellsize;newShape;lightMap;lightMapIntensity;aoMap;aoMapIntensity;specularMap;alphaMap;envMap;combine;reflectivity;refractionRatio;dataFilterOffset;dataFilterMin;dataFilterGroup;threshold;rangeMatrix;constructor(e,i,n,s,a,o,h,d){super(),this.map=null,this.reflectivity=1,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new g(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=y,this.reflectivity=1,this.refractionRatio=.98;const p=-e,l=1/(i-e);this.colorMapOffset=p,this.colorMapRatio=l,this.colorMapTexture=n,this.dataFilterOffset=0,this.dataFilterMin=0,this.dataFilterGroup=1,this.attTex=null,this.dagTex=null,this.vofattTex=null,this.vofdagTex=null,this.lo=s,this.res=a,this.newShape=o,this.cellsize=h,this.rangeMatrix=new t,this.threshold=[new r(0,0)],d&&(this.setValues(d),d.dagTex&&(this.dagTex=d.dagTex),d.attTex&&(this.attTex=d.attTex),d.vofdagTex&&(this.vofdagTex=d.vofdagTex),d.vofattTex&&(this.vofattTex=d.vofattTex),d.threshold&&(this.threshold=d.threshold)),this.updateUniforms()}updateRange(e,t,i=0){const n=1/(t-e),s=-e+i;this.uniforms.colorMapOffset={value:s},this.uniforms.colorMapRatio={value:n}}updateFilter(e,t,i=1){this.dataFilterOffset=t-e,this.dataFilterMin=e,this.dataFilterGroup=i,this.uniforms.dataFilterOffset={value:t-e},this.uniforms.dataFilterMin={value:e},this.uniforms.dataFilterGroup={value:i}}copy(e){super.copy(e);const t=e;if(!t)throw Error("invalid input");return this.map=t.map,this.lightMap=t.map,this.lightMapIntensity=t.lightMapIntensity,this.aoMap=t.aoMap,this.aoMapIntensity=t.aoMapIntensity,this.emissive=t.emissive,this.emissiveIntensity=t.emissiveIntensity,this.emissiveMap=t.emissiveMap,this.specularMap=t.specularMap,this.alphaMap=t.alphaMap,this.envMap=t.envMap,this.combine=t.combine,this.reflectivity=t.reflectivity,this.refractionRatio=t.refractionRatio,this.colorMapTexture=t.colorMapTexture,this.colorMapOffset=t.colorMapOffset,this.colorMapRatio=t.colorMapRatio,this.dataFilterOffset=t.dataFilterOffset,this.dataFilterMin=t.dataFilterMin,this.dataFilterMin=t.dataFilterGroup,this.dagTex=t.dagTex,this.attTex=t.attTex,this.vofdagTex=t.vofdagTex,this.vofattTex=t.vofattTex,this.newShape=t.newShape,this.cellsize=t.cellsize,this.lo=t.lo,this.res=t.res,this.threshold=t.threshold,this.updateUniforms(),this}updateColorMode(e){let t=e;return null===this.dagTex&&(t=t.replace("#define COLORONATTS true","#define COLORONATTS false")),t}replaceThresholdNum(e){let t=e;return t=t.replace(/NUM_THRESHOLD_INTERVALS/g,this.threshold.length.toString()),t}updateUniforms(){this.uniforms=x.merge([v.lambert.uniforms,Xt(this)]);let e=this.updateColorMode("\n#define LAMBERT\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\nvarying vec3 vViewPosition;\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nuniform mat4 rangeMatrix;\nuniform vec3 lo;\nuniform vec3 newShape;\nuniform vec3 cellsize;\nuniform int res;\n\nvarying highp vec3 vOrigin;\nvarying highp vec3 vDirection;\nvarying mat3 vNormalMatrix;\nvarying mat4 vMVPMatrix;\nvarying mat4 vMVMatrix;\n\nvoid main() {\n\n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n bool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tvec3 worldPos = (modelMatrix * vec4(transformed, 1.0)).xyz;\n\n vOrigin = isPerspective ? \n ( rangeMatrix * inverse(modelMatrix) * vec4(cameraPosition, 1.0) ).xyz : \n ( rangeMatrix * inverse(modelMatrix) * vec4(worldPos.x, worldPos.y, cameraPosition.z, 1.0) ).xyz;\n vDirection = ((rangeMatrix * vec4(transformed, 1.0)).xyz - vOrigin) + 0.000001;\n\n\t\tvNormalMatrix = normalMatrix;\n vMVPMatrix = projectionMatrix * modelViewMatrix;\n vMVMatrix = modelViewMatrix;\n\t\t\n\t#include \n\t#include \n\n\t vViewPosition = - mvPosition.xyz;\n\n\t#include \n\t#include \n\t#include \n\t#include \n}\n");e=this.replaceThresholdNum(e),this.vertexShader=e;let t=this.updateColorMode("\n#define COLORONATTS true\nprecision highp float;\nprecision highp usampler3D;\nprecision highp sampler3D;\nprecision highp isampler3D;\n\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nuniform sampler2D colorMapTexture;\n\nuniform usampler3D dagTex;\nuniform usampler3D attTex;\nuniform usampler3D vofdagTex;\nuniform isampler3D vofattTex;\nuniform vec3 lo;\nuniform vec3 newShape;\nuniform vec3 cellsize;\nuniform int res;\n#if NUM_THRESHOLD_INTERVALS > 0\n uniform vec2 threshold[NUM_THRESHOLD_INTERVALS];\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nint dagTexLen;\nint attTexLen;\nint vofdagTexLen;\nint vofattTexLen;\n\nuniform float colorMapOffset;\nuniform float colorMapRatio;\nuniform mat4 rangeMatrix;\n\nvarying vec3 vLightFront;\nvarying vec3 vIndirectFront;\nvarying highp vec3 vOrigin;\nvarying highp vec3 vDirection;\nvarying mat3 vNormalMatrix;\nvarying mat4 vMVPMatrix;\nvarying mat4 vMVMatrix;\n\nint GetIdx(vec3 idx);\nvec2 isect(in vec3 pos, in vec3 size, in vec3 ro, in vec3 rd, out vec3 tmid, out vec3 tmax);\nvec3 maxIndex(vec3 inputVec);\nivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset);\nint sample_att_u (usampler3D aT, int aTLen, int offset);\nint sample_att_i (isampler3D aT, int aTLen, int offset);\nfloat MapToPos (usampler3D dT, int dTLen, usampler3D aT, int aTLen, vec3 target);\nfloat MapToPosI (usampler3D dT, int dTLen, isampler3D aT, int aTLen, vec3 target);\nbool calHitPt(in vec3 ro, in vec3 rd, in float t, in vec3 pos, out vec3 norm, out vec3 hitPoint);\nbool trace(in vec3 ro, in vec3 rd, in usampler3D dT, in int dTLen, in isampler3D aT,\n in int aTLen, out vec2 t, out vec3 pos, out int iter, out vec3 size, out int idebug,\n out vec3 norm, out bool isinbound, out vec3 hitPoint, out bool normalSuccess);\n\nvoid main() {\n // #include \n #include \n #include \n #include \n #include \n #include \n #include \n #include \n\n vec4 diffuseColor = vec4( vec3(1.0), 1.0 );\n \n if (COLORONATTS) {\n dagTexLen = textureSize(dagTex, 0).y;\n attTexLen = textureSize(attTex, 0).y;\n }\n\n vofdagTexLen = textureSize(vofdagTex, 0).y;\n vofattTexLen = textureSize(vofattTex, 0).y;\n\n highp vec3 rayDir = normalize( vDirection );\n vec2 t;\n vec3 pos;\n int iter;\n vec3 size;\n int idebug;\n vec3 norm;\n bool isinbound;\n vec3 hitPoint;\n bool normalSuccess = false;\n bool hit = trace(vOrigin, rayDir, vofdagTex, vofdagTexLen, vofattTex, vofattTexLen, t, pos, iter, size, idebug, norm, isinbound, hitPoint, normalSuccess);\n float property;\n\n if (COLORONATTS) {\n property = MapToPos(dagTex, dagTexLen, attTex, attTexLen, hitPoint);\n } else {\n property = float(idebug);\n }\n\n vec4 sampledColormap = texture2D(colorMapTexture,\n vec2((float(property) + colorMapOffset) * colorMapRatio, 1.));\n\n diffuseColor = hit ? vec4(sampledColormap.rgb, 1.0) : vec4(0.0);\n\n ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n vec3 totalEmissiveRadiance = emissive;\n\n normal = normalize( vNormalMatrix * norm );\n\n #include \n #include \n\n // accumulation\n #include \n #include \n #include \n #include \n\n // modulation\n #include \n\n vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n #include \n #include \n #include \n #include \n #include \n #include \n #include \n\n vec4 ndc = (vMVPMatrix * (inverse(rangeMatrix) * vec4((hitPoint),1.0)));\n gl_FragDepthEXT = hit ? 0.5*ndc.z/ndc.w+0.5 : 1000.0;\n}\n\nvec3 maxIndex(vec3 inputVec) {\n return vec3(inputVec.x >= inputVec.y && inputVec.x >= inputVec.z,\n inputVec.y >= inputVec.x && inputVec.y >= inputVec.z,\n inputVec.z >= inputVec.y && inputVec.z >= inputVec.x);\n}\n\nint GetIdx(vec3 idx) {\n\treturn int(dot(idx*0.5+0.5,vec3(1.0,2.0,4.0)));\n}\n\nvec2 isect(in vec3 pos, in vec3 size, in vec3 ro, in vec3 rd, out vec3 tmid, out vec3 tmax) {\n vec3 mn = pos - 0.5 * size;\n vec3 mx = mn + size;\n vec3 t1 = (mn-ro) / rd;\n vec3 t2 = (mx-ro) / rd;\n vec3 tmin = min(t1, t2);\n tmax = max(t1, t2);\n tmid = (t1 + t2) * 0.5;\n return vec2(max(tmin.x, max(tmin.y, tmin.z)), min(tmax.x, min(tmax.y, tmax.z)));\n}\n\nivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset) {\n int dTLenH = dTLen/2;\n int dTLenH2 = dTLenH * dTLenH;\n int z = dagPos / dTLenH2;\n\tint y = (dagPos - z * dTLenH2) / dTLenH;\n int x = dagPos - y * dTLenH - z * dTLenH2;\n\n int zz = offset / 4;\n int yy = (offset - zz * 4) / 2;\n int xx = offset - yy * 2 - zz * 4;\n\t\n\treturn ivec2(texture(dT, (vec3(2*x+xx, 2*y+yy, 2*z+zz)+0.5)/vec3(dTLen)).rg);\n}\n\nint sample_att_u (usampler3D aT, int aTLen, int offset) {\n\tint aTLen2 = aTLen*aTLen;\n\tint z = offset/aTLen2;\n\tint y = (offset - aTLen2*z)/aTLen;\n\tint x = offset - aTLen*y - aTLen2*z;\n\n\treturn int(texture(aT, (vec3(x,y,z)+0.5)/float(aTLen)).r);\n}\n\nint sample_att_i (isampler3D aT, int aTLen, int offset) {\n\tint aTLen2 = aTLen*aTLen;\n\tint z = offset/aTLen2;\n\tint y = (offset - aTLen2*z)/aTLen;\n\tint x = offset - aTLen*y - aTLen2*z;\n\n\treturn int(texture(aT, (vec3(x,y,z)+0.5)/float(aTLen)).r);\n}\n\nfloat MapToPos (usampler3D dT, int dTLen, usampler3D aT, int aTLen, vec3 target) {\n\tvec3 size = float(res)*cellsize;\n\tvec3 pos = lo + size/2.0;\n\tint result = 0;\n\n\tint voxIdx = 0;\n\tint voxOffset = 0;\n ivec2 nodeInfo;\n\tint isLeaf = 1;\n\n\tint iter = 20;\n\twhile (iter --\x3e 0) {\n\t\tvec3 idx = vec3(-1.0) + 2.0*vec3(greaterThanEqual(target, pos));\n\t\tint idxOffset = GetIdx(idx);\n nodeInfo = sample_dag(dT, dTLen, voxIdx, idxOffset);\n isLeaf = nodeInfo.r;\n\t\tvoxOffset += nodeInfo.r;\n\t\tresult = sample_att_u(aT, aTLen, voxOffset);\n\t\tsize *= 0.5;\n\t\tpos += 0.5 * size * idx;\n\t\tif (isLeaf==0) {\n\t\t\treturn float(result);\n\t\t}\n\t\tvoxIdx = nodeInfo.g;\n\t}\n\treturn 0.0;\n}\n\nfloat MapToPosI (usampler3D dT, int dTLen, isampler3D aT, int aTLen, vec3 target) {\n\tvec3 size = float(res)*cellsize;\n\tvec3 pos = lo + size/2.0;\n\tint result = 0;\n\n\tint voxIdx = 0;\n\tint voxOffset = 0;\n ivec2 nodeInfo;\n\tint isLeaf = 1;\n\n\tint iter = 20;\n\twhile (iter --\x3e 0) {\n\t\tvec3 idx = vec3(-1.0) + 2.0*vec3(greaterThanEqual(target, pos));\n\t\tint idxOffset = GetIdx(idx);\n nodeInfo = sample_dag(dT, dTLen, voxIdx, idxOffset);\n isLeaf = nodeInfo.r;\n\t\tvoxOffset += nodeInfo.r;\n\t\tresult = sample_att_i(aT, aTLen, voxOffset);\n\t\tsize *= 0.5;\n\t\tpos += 0.5 * size * idx;\n\t\tif (isLeaf==0) {\n\t\t\treturn float(result);\n\t\t}\n\t\tvoxIdx = nodeInfo.g;\n\t}\n\treturn 0.0;\n}\n\nbool calHitPt(\n in vec3 ro,\n in vec3 rd,\n in float t,\n in vec3 pos,\n out vec3 norm,\n out vec3 hitPoint)\n{\n hitPoint = ro + t*rd;\n vec3 norm1 = hitPoint - pos;\n vec3 absNorm1 = abs(norm1);\n\n vec3 maxPos = maxIndex(absNorm1);\n float maxVal = dot(absNorm1, maxPos);\n\n norm = maxPos*(sign(norm1));\n vec3 diff = abs(absNorm1 - maxVal);\n float standardBar = 0.000001;\n bool success = (diff.x + diff.y) > standardBar && (diff.z + diff.y) > standardBar && (diff.x + diff.z) > standardBar;\n return success;\n}\n\nbool trace(\n in vec3 ro, \n in vec3 rd, \n in usampler3D dT,\n in int dTLen,\n in isampler3D aT,\n in int aTLen,\n out vec2 t, \n out vec3 pos, \n out int iter, \n out vec3 size,\n out int idebug,\n out vec3 norm,\n out bool isinbound,\n out vec3 hitPoint,\n out bool normalSuccess)\n{\n struct ST {\n vec3 pos;\n int scale;\n vec3 idx;\n int ptr;\n float h;\n int offset;\n };\n ST stack[30];\n int stack_ptr = 0; // Next open index\n\n // Initialize\n vec3 initsize = float(res)*cellsize;\n size = initsize;\n vec3 root_pos = lo + size/2.0;\n pos = root_pos;\n vec3 tmid;\n vec3 tmax;\n bool can_push = true;\n float d;\n t = isect(pos, size, ro, rd, tmid, tmax);\n float h = t.y;\n \n // Initial push\n vec3 idx = mix(-sign(rd), sign(rd), lessThanEqual(tmid, vec3(t.x)));\n int stackIdx = 0;\n int curIdx = 0;\n int scale = 1;\n size *= 0.5;\n pos += 0.5 * size * idx;\n int curOffset = 0;\n int stackOffset = 0;\n int isLeaf = 1;\n ivec2 nodeInfo;\n\n idebug = 0;\n\n iter = 1000;\n while (iter --\x3e 0) {\n t = isect(pos, size, ro, rd, tmid, tmax);\n int idxOffset = GetIdx(idx);\n nodeInfo = sample_dag(dT, dTLen, stackIdx, idxOffset);\n curIdx = nodeInfo.g;\n curOffset = stackOffset+nodeInfo.r;\n isLeaf = nodeInfo.r;\n int att = (sample_att_i(aT, aTLen, curOffset));\n bool insideThreshold = false;\n bool clipped = false;\n \n for (int thresh = 0; thresh < NUM_THRESHOLD_INTERVALS; thresh++) {\n insideThreshold = insideThreshold || (float(att) >= threshold[thresh].x && float(att) <= threshold[thresh].y);\n }\n\n #if NUM_CLIPPING_PLANES > 0\n for (int cp = 0; cp < NUM_CLIPPING_PLANES; cp++) {\n vec4 p = clippingPlanes[cp];\n vec4 mvHitPt = - (vMVMatrix * inverse(rangeMatrix) * vec4((ro+t.x*rd), 1.0));\n float criteria = dot( mvHitPt.xyz, p.xyz );\n clipped = clipped || criteria > p.w;\n }\n #endif\n if (!(isLeaf==0 && (!insideThreshold || clipped))) {\n if (isLeaf==0) {\n idebug = att; \n normalSuccess = calHitPt(ro, rd, t.x, pos, norm, hitPoint);\n return true;\n }\n if (can_push) {\n if (t.y < h) {\n stack[stack_ptr++] = ST(pos, scale, idx, stackIdx, h, stackOffset);\n }\n h = t.y;\n scale++;\n size *= 0.5;\n idx = mix(-sign(rd), sign(rd), step(tmid, vec3(t.x)));\n stackIdx = curIdx;\n stackOffset = curOffset;\n pos += 0.5 * size * idx;\n continue;\n }\n }\n\n // Advance\n\n vec3 old = idx;\n idx = mix(idx, sign(rd), equal(tmax, vec3(t.y)));\n pos += mix(vec3(0.), sign(rd), notEqual(old, idx)) * size;\n if (idx == old) {\n //-- POP --//\n \n if (stack_ptr == 0 || scale == 0) {\n return false;\n } //exist Whole Octree;\n \n ST s = stack[--stack_ptr];//Back to parent Stack\n pos = s.pos;\n scale = s.scale;\n size = initsize * exp2(float(-scale));\n idx = s.idx;\n stackIdx = s.ptr;\n h = s.h;\n stackOffset = s.offset;\n \n can_push = false; //*once stack pop out,get rid out pushing in again\n } else {can_push = true;}\n }\n return false;\n}\n");t=this.replaceThresholdNum(t),this.fragmentShader=t,this.uniforms.dagTex.value=this.dagTex,this.uniforms.attTex.value=this.attTex}}var ri;!function(e){e[e.DETECT_BY_STATIC_VALUE=0]="DETECT_BY_STATIC_VALUE",e[e.DETECT_BY_ATTRIBUTE=1]="DETECT_BY_ATTRIBUTE"}(ri||(ri={}));class ai extends w{constructor(e){super(),this.type="DetectMaterial",this.vertexShader="\n#include \n#include \n\n#define DETECT_BY_ATTRIBUTE 1\n\n#if DETECT_MODE == DETECT_BY_ATTRIBUTE\nattribute float value;\n#else\nuniform float value;\n#endif\nvarying vec4 vColor;\n\nuniform mat4 objectTransform;\n\nvoid main() {\n\t#include \n\n\tvColor = vec4(transformed, 1.0);\n\tvColor = objectTransform * vColor;\n\tvColor.w = value;\n\n\t#include \n\t\n\t#include \n\t#include \n}\n",this.fragmentShader="\n#include \n#include \n\nvarying vec4 vColor;\n\nvoid main() {\n\n\t#include \n\n\tgl_FragColor = vColor;\n\n}\n",this.blending=M,ai.extendShader(),this.uniforms=x.merge([v.basic.uniforms,m.detect]),e&&this.setValues(e)}get detectMode(){return"DETECT_MODE"in this.defines?this.defines.DETECT_MODE:ri.DETECT_BY_STATIC_VALUE}set detectMode(e){this.defines.DETECT_MODE=e,this.needsUpdate=!0}get value(){return this.uniforms.value.value}set value(e){this.uniforms.value.value=e}get objectTransform(){return this.uniforms.objectTransform.value}set objectTransform(e){this.uniforms.objectTransform.value=e}copy(e){super.copy(e);const t=e;return this.detectMode=t.detectMode,this.objectTransform=t.objectTransform,this.value=t.value,this}static extendShader(){const e=m;e.detect||(e.detect={objectTransform:{value:new t},value:{value:0}})}}Wt();class oi extends Ue{get colorMapMode(){return"COLOR_MAP_MODE"in this.defines?this.defines.COLOR_MAP_MODE:Vt.None}set colorMapMode(e){this.defines.COLOR_MAP_MODE=e,this.needsUpdate=!0}get colorMap(){return this.uniforms.colorMap.value}set colorMap(e){this.uniforms.colorMap.value=e}get colorMapOffset(){return this.uniforms.colorMapOffset.value}set colorMapOffset(e){this.uniforms.colorMapOffset.value=e}get colorMapRatio(){return this.uniforms.colorMapRatio.value}set colorMapRatio(e){this.uniforms.colorMapRatio.value=e}get enableSlice(){return"ENABLE_SLICE"in this.defines&&this.defines.SLICE_RANGE}set enableSlice(e){e?this.defines.ENABLE_SLICE=e:delete this.defines.ENABLE_SLICE,this.needsUpdate=!0}get sliceRange(){return[this.uniforms.sliceRangeStart.value,this.uniforms.sliceRangeEnd.value]}set sliceRange(e){const[t,i]=e;this.uniforms.sliceRangeStart.value=t,this.uniforms.sliceRangeEnd.value=void 0===i?1/0:i}constructor(e){super(),this.type="ColorMapLineMaterial";let t=this.vertexShader;t=Ht.patch(t,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),t=Ht.patch(t,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),t=Ht.patch(t,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),t=Ht.patch(t,/([\s\S]*)(void main\(\) {)([\s\S]*)/m,"\n#include \n","",void 0);let i=this.fragmentShader;i=Ht.patch(i,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),i=Ht.patch(i,/([\s\S]*)(vec4 diffuseColor = vec4\( diffuse, alpha \);)([\s\S]*)/m,"","","#include "),this.vertexShader=t,this.fragmentShader=i,this.uniforms=x.merge([this.uniforms,m.colorMap,{sliceRangeStart:{value:0}},{sliceRangeEnd:{value:1/0}}]),this.setValues(e)}copy(e){super.copy(e);const t=e;return this.colorMapMode=t.colorMapMode,this.colorMap=t.colorMap,this.colorMapOffset=t.colorMapOffset,this.colorMapRatio=t.colorMapRatio,this.enableSlice=t.enableSlice,this.sliceRange=t.sliceRange,this}}!function(){const e=f;e.weight_z_pars_fragment||(e.weight_z_pars_fragment="\n#ifdef ENABLE_WEIGHT_Z\n\nlayout(location=1) out float accumAlpha;\n\nfloat weight(float z, float a) {\n return clamp(pow(min(1.0, a * 10.0) + 0.01, 3.0) * 1e8 * pow(1.0 - z * 0.9, 3.0), 1e-2, 3e3);\n}\n\n#endif\n",e.weight_z_fragment="\n\n#ifdef ENABLE_WEIGHT_Z\n\n#ifndef OPAQUE\n \n diffuseColor = gl_FragColor;\n float w = weight(gl_FragCoord.z, diffuseColor.a);\n gl_FragColor = vec4(diffuseColor.rgb * w, diffuseColor.a);\n accumAlpha = diffuseColor.a * w;\n\n#endif\n\n#endif\n\n")}();let hi=!1;function di(){if(hi)return;let e=v.lambert.fragmentShader;e=Ht.patch(e,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),e=Ht.patch(e,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",""),f.meshlambert_frag=e,v.lambert.fragmentShader=e,hi=!0}let pi=!1;function li(){if(pi)return;let e=v.phong.fragmentShader;e=Ht.patch(e,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),e=Ht.patch(e,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",""),f.meshphong_frag=e,v.phong.fragmentShader=e,pi=!0}let ci=!1;function ui(){if(ci)return;let e=v.basic.fragmentShader;e=Ht.patch(e,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),e=Ht.patch(e,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",""),f.meshbasic_frag=e,v.basic.fragmentShader=e,ci=!0}let gi=!1;function fi(){if(gi)return;let e=v.points.fragmentShader;e=Ht.patch(e,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",void 0),e=Ht.patch(e,/([\s\S]*)(#include )([\s\S]*)/m,"\n#include \n","",""),f.points_frag=e,v.points.fragmentShader=e,gi=!0}function mi(e){Object.prototype.hasOwnProperty.call(e.prototype,"enableWeightZ")||Object.defineProperty(e.prototype,"enableWeightZ",{get(){return void 0!==this.defines&&"ENABLE_WEIGHT_Z"in this.defines&&this.defines.ENABLE_WEIGHT_Z},set(e){void 0===this.defines&&(this.defines={}),"ENABLE_WEIGHT_Z"in this.defines&&e===this.defines.ENABLE_WEIGHT_Z||(this.defines.ENABLE_WEIGHT_Z=e,this.needsUpdate=!0)},configurable:!0})}function wi(e){if(!Object.prototype.hasOwnProperty.call(e.prototype,"enableWeightZ"))return;delete e.prototype.enableWeightZ}class vi extends w{emissive;emissiveIntensity;emissiveMap;map;lightMap;lightMapIntensity;aoMap;aoMapIntensity;specularMap;alphaMap;envMap;combine;reflectivity;refractionRatio;constructor(e){super(),this.map=null,this.reflectivity=1,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new g(0),this.emissiveIntensity=1,this.emissiveMap=null,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.combine=y,this.reflectivity=1,this.refractionRatio=.98,e&&this.setValues(e),this.lights=!0,this.updateUniforms()}updateUniforms(){this.uniforms=x.merge([v.lambert.uniforms,Xt(this)]),this.needsUpdate=!0,this.vertexShader="\n\t#define LAMBERT\n\n\tprecision highp float;\n\n\tvarying vec3 vLightFront;\n\tvarying vec3 vIndirectFront;\n\tvarying vec3 vViewPosition;\n\n\tvarying mat4 vMVPMatrix;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tvarying vec3 meshPos;\n\n\tvoid main() {\n\t\t#include \n\t\t#include \n\t\t#include \n\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t\t\n\t\tmeshPos = position;\n\t\tvMVPMatrix = projectionMatrix * modelViewMatrix;\n\n\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t#include \n\t\t#include \n\n\t\tvViewPosition = - mvPosition.xyz;\n\t\t\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t}\n",this.fragmentShader="\n\tprecision highp float;\n\tprecision highp int;\n\n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\t#include \n\n\tlayout(location = 1) out vec4 gIllum;\n\n\tvarying vec3 meshPos;\n\tvarying mat4 vMVPMatrix;\n\n\tuniform vec3 diffuse;\n\tuniform vec3 emissive;\n\tuniform float opacity;\n\n\tvoid main() {\n\t\t#include \n\n\t\tvec4 diffuseColor = vec4( vec3(1.0), 1.0 );\n\t\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t\tvec3 totalEmissiveRadiance = emissive;\n\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\n\t\t// accumulation\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\n\t\t// modulation\n\t\t#include \n\n\t\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\t\t#include \n\n\t\tgIllum = vec4(gl_FragColor.rgb, 1.0);\n\n\t\tgl_FragColor = vec4(meshPos, 1.0);\n\n\t\tif (length(normal.xyz) > 0.0) {\n\t\t\tgl_FragColor.a = 2.0;\n\t\t}\n\t}\n"}}const xi={uniforms:{tPos:{value:null},tDepth:{value:null},opacity:{value:1},clipMatrix:{value:null},newShape:{value:null},cellSize:{value:null},lo:{value:null},res:{value:null},dagTex:{value:null},attTex:{value:null},minVal:{value:null},maxVal:{value:null},start:{value:null},codeMax:{value:null}},vertexShader:"\n\n varying vec2 vUv;\n\n void main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n }",fragmentShader:"\n\n precision highp float;\n precision highp int;\n precision mediump usampler3D;\n\n uniform float opacity;\n\t\tuniform sampler2D tPos;\n uniform sampler2D tDepth;\n\n\t\tuniform mat4 clipMatrix;\n\n uniform vec3 newShape;\n uniform vec3 cellSize;\n uniform int res;\n uniform usampler3D dagTex;\n uniform usampler3D attTex;\n uniform vec3 lo;\n\n uniform float minVal;\n uniform float maxVal;\n\n uniform int start;\n uniform float codeMax;\n\n int dagTexLen;\n int attTexLen;\n\n\t\tvarying vec2 vUv;\n\n int GetIdx(vec3 idx);\n float Decode(int code);\n ivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset);\n int sample_att(usampler3D aT, int aTLen, int offset);\n float MapToSurf(usampler3D dT, int dTLen, usampler3D aT, int aTLen, vec3 target);\n\n\t\tvoid main() {\n\n\t\t\tvec4 pos = texture2D( tPos, vUv );\n\n if (pos.a <= 1.0) {\n discard;\n }\n\n vec4 meshPos = clipMatrix * vec4(pos.xyz, 1.0);\n\n if (any(lessThan(meshPos.rgb, lo)) || any(greaterThan(meshPos.rgb, lo + cellSize*newShape))) {\n gl_FragColor.a = 0.0;\n return;\n }\n \n dagTexLen = textureSize(dagTex,0).y;\n\t attTexLen = textureSize(attTex,0).y;\n\n float property = MapToSurf(dagTex, dagTexLen, attTex, attTexLen, meshPos.xyz);\n\n\t\t\tgl_FragColor.rgb = vec3(property);\n\t\t\tgl_FragColor.a = opacity;\n\n\t\t}\n\n int GetIdx(vec3 idx) {\n return int(dot(idx*0.5+0.5,vec3(1.0,2.0,4.0)));\n }\n \n float Decode(int code) {\n return (code == 0) ? 0.0 : (float(code) - 1.0) / (codeMax - 1.0) * (maxVal - minVal) + minVal;\n }\n\n ivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset) {\n int dTLenH = dTLen/2;\n int dTLenH2 = dTLenH * dTLenH;\n int z = dagPos / dTLenH2;\n int y = (dagPos - z * dTLenH2) / dTLenH;\n int x = dagPos - y * dTLenH - z * dTLenH2;\n \n int zz = offset / 4;\n int yy = (offset - zz * 4) / 2;\n int xx = offset - yy * 2 - zz * 4;\n \n return ivec2(texture(dT, (vec3(2*x+xx, 2*y+yy, 2*z+zz)+0.5)/vec3(dTLen)).rg);\n }\n \n int sample_att(usampler3D aT, int aTLen, int offset) {\n int aTLen2 = aTLen*aTLen;\n int z = offset/aTLen2;\n int y = (offset - aTLen2*z)/aTLen;\n int x = offset - aTLen*y - aTLen2*z;\n \n return int(texture(aT, (vec3(x,y,z)+0.5)/float(aTLen)).r);\n }\n \n float MapToSurf(usampler3D dT, int dTLen, usampler3D aT, int aTLen, vec3 target) {\n vec3 size = float(res) * cellSize;\n vec3 root_pos = lo + size / 2.0;\n vec3 pos = root_pos;\n int result = 0;\n \n int voxIdx = start;\n int voxOffset = 0;\n int isLeaf = 1;\n\n ivec2 nodeInfo;\n \n int iter = 20;\n while (iter --\x3e 0) {\n vec3 idx = vec3(-1.0);\n if (target.x>=pos.x){idx.x=1.0;}\n if (target.y>=pos.y){idx.y=1.0;}\n if (target.z>=pos.z){idx.z=1.0;}\n int idxOffset = GetIdx(idx);\n nodeInfo = sample_dag(dT, dTLen, voxIdx, idxOffset);\n isLeaf = nodeInfo.r;\n voxOffset += isLeaf;\n result = sample_att(aT, aTLen, voxOffset);\n size *= 0.5;\n pos += 0.5 * size * idx;\n if (isLeaf==0) {\n return Decode(result);\n }\n voxIdx = nodeInfo.g;\n }\n return 0.0;\n }\n "};class yi extends w{constructor(e){super(),this.uniformsNeedUpdate=!0,this.uniforms=x.clone(xi.uniforms),this.vertexShader=xi.vertexShader,this.fragmentShader=xi.fragmentShader,this.setValues(e)}setGBuffer(e){this.uniforms.tPos.value=e,this.uniforms.opacity.value=1}setClipMatrix(e){this.uniforms.clipMatrix.value=e}setDag(e,t,i,n){this.uniforms.dagTex.value=e,this.uniforms.attTex.value=t,this.uniforms.start.value=i,this.uniforms.codeMax.value=n}setGeom(e,t,i,n){this.uniforms.lo.value=e,this.uniforms.cellSize.value=t,this.uniforms.newShape.value=i,this.uniforms.res.value=n}setMinMax(e,t){this.uniforms.minVal.value=e,this.uniforms.maxVal.value=t}}const Mi={uniforms:{tProp:{value:null},tPos:{value:null},tDepth:{value:null},opacity:{value:1},clipMatrix:{value:null},newShape:{value:null},cellSize:{value:null},lo:{value:null},res:{value:null},dagTex:{value:null},attTex:{value:null},minVal:{value:null},maxVal:{value:null},start:{value:null},dwtLev:{value:null},codeMax:{value:null}},vertexShader:"\n\n varying vec2 vUv;\n\n void main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n }",fragmentShader:"\n\n precision highp float;\n precision highp int;\n precision mediump usampler3D;\n\n uniform float opacity;\n\t\tuniform sampler2D tPos;\n\t\tuniform sampler2D tProp;\n uniform sampler2D tDepth;\n\n\t\tuniform int dwtLev;\n\n\t\tuniform mat4 clipMatrix;\n\n uniform vec3 newShape;\n uniform vec3 cellSize;\n uniform int res;\n uniform usampler3D dagTex;\n uniform usampler3D attTex;\n uniform vec3 lo;\n\n uniform float minVal;\n uniform float maxVal;\n\n uniform int start;\n uniform float codeMax;\n\n int dagTexLen;\n int attTexLen;\n\n\t\tvarying vec2 vUv;\n\n int GetIdx(vec3 idx);\n float Decode(int code);\n ivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset);\n int sample_att(usampler3D aT, int aTLen, int offset);\n float MapToSurf(usampler3D dT, int dTLen, usampler3D aT, int aTLen, vec3 target);\n\t\tint F2INT(float num);\n\t\tivec3 F2INT(vec3 num);\n\t\tvoid IHaar(in ivec3 tarId, in vec3 tarP, in usampler3D dT, in int dTLen, \n\t\t\tin usampler3D aT, in int aTLen, in int scale, in float avr, out float value);\n\n\t\tvoid main() {\n\n\t\t\tvec4 pos = texture2D( tPos, vUv );\n\n if (pos.a <= 1.0) {\n discard;\n }\n\n vec4 meshPos = clipMatrix * vec4(pos.xyz, 1.0);\n\n if (any(lessThan(meshPos.rgb, lo)) || any(greaterThan(meshPos.rgb, lo + cellSize * newShape))) {\n gl_FragColor.a = 0.0;\n return;\n }\n \n dagTexLen = textureSize(dagTex,0).y;\n\t attTexLen = textureSize(attTex,0).y;\n\n\t\t\tfloat avr = texture2D( tProp, vUv ).r;\n\t\t\tfloat property;\n\n\t\t\tvec3 idx = (meshPos.xyz - lo) / cellSize;\n\t\t\tivec3 Idx = ivec3(F2INT(idx.x),F2INT(idx.y),F2INT(idx.z));\n\n\t\t\tIHaar(Idx, meshPos.xyz, dagTex, dagTexLen, attTex, attTexLen, dwtLev, avr, property);\n\n\t\t\tgl_FragColor.rgb = vec3(property);\n\t\t\tgl_FragColor.a = opacity;\n\n\t\t}\n\n int GetIdx(vec3 idx) {\n return int(dot(idx*0.5+0.5,vec3(1.0,2.0,4.0)));\n }\n \n float Decode(int code) {\n return (code == 0) ? 0.0 : (float(code) - 1.0) / (codeMax - 1.0) * (maxVal - minVal) + minVal;\n }\n\n ivec2 sample_dag(usampler3D dT, int dTLen, int dagPos, int offset) {\n int dTLenH = dTLen/2;\n int dTLenH2 = dTLenH * dTLenH;\n int z = dagPos / dTLenH2;\n int y = (dagPos - z * dTLenH2) / dTLenH;\n int x = dagPos - y * dTLenH - z * dTLenH2;\n \n int zz = offset / 4;\n int yy = (offset - zz * 4) / 2;\n int xx = offset - yy * 2 - zz * 4;\n \n return ivec2(texture(dT, (vec3(2*x+xx, 2*y+yy, 2*z+zz)+0.5)/vec3(dTLen)).rg);\n }\n \n int sample_att(usampler3D aT, int aTLen, int offset) {\n int aTLen2 = aTLen*aTLen;\n int z = offset/aTLen2;\n int y = (offset - aTLen2*z)/aTLen;\n int x = offset - aTLen*y - aTLen2*z;\n \n return int(texture(aT, (vec3(x,y,z)+0.5)/float(aTLen)).r);\n }\n \n float MapToSurf(usampler3D dT, int dTLen, usampler3D aT, int aTLen, vec3 target) {\n vec3 size = float(res) * cellSize;\n vec3 root_pos = lo + size / 2.0;\n vec3 pos = root_pos;\n int result = 0;\n \n int voxIdx = start;\n int voxOffset = 0;\n int isLeaf = 1;\n\n ivec2 nodeInfo;\n \n int iter = 20;\n while (iter --\x3e 0) {\n vec3 idx = vec3(-1.0);\n if (target.x>=pos.x){idx.x=1.0;}\n if (target.y>=pos.y){idx.y=1.0;}\n if (target.z>=pos.z){idx.z=1.0;}\n int idxOffset = GetIdx(idx);\n nodeInfo = sample_dag(dT, dTLen, voxIdx, idxOffset);\n isLeaf = nodeInfo.r;\n voxOffset += isLeaf;\n result = sample_att(aT, aTLen, voxOffset);\n size *= 0.5;\n pos += 0.5 * size * idx;\n if (isLeaf==0) {\n return Decode(result);\n }\n voxIdx = nodeInfo.g;\n }\n return 0.0;\n }\n\n\t\tint F2INT(float num) {\n\t\t\tint rNum = int(round(num));\n\t\t\tfloat err = num*1000.0-float(1000*rNum);\n\t\t\t\n\t\t\tif (abs(err)<1.0) {\n\t\t\t\treturn rNum;\n\t\t\t}else {\n\t\t\t\treturn int(floor(num));\n\t\t\t}\n\t\t}\n\t\t\n\t\tivec3 F2INT(vec3 num) {\n\t\t\treturn ivec3(F2INT(num.x), F2INT(num.y), F2INT(num.z));\n\t\t}\n\n\t\tvoid IHaar(in ivec3 tarId, \n\t\t\tin vec3 tarP, \n\t\t\tin usampler3D dT, \n\t\t\tin int dTLen, \n\t\t\tin usampler3D aT, \n\t\t\tin int aTLen, \n\t\t\tin int scale,\n\t\t\tin float avr,\n\t\t\tout float value) \n\t\t{\n\t\t\tvalue = avr;\n\t\t\tvec3 hfs = newShape / 2.0 * cellSize;\n\t\t\tvec3 wrapP = (tarP - lo) / 2.0 + lo;\n\t\t\tvec3 tgIdF = vec3(vec3(tarId)/pow(2.0, 2.0 - float(scale)));\n\t\t\tivec3 tgId = ivec3(F2INT(tgIdF.x), F2INT(tgIdF.y), F2INT(tgIdF.z));\n\t\t\tivec3 modId = tgId+1 - ((tgId+1)/2)*2;\n\t\t\n\t\t\tvec3 modidx = vec3(-1) + 2.0 * vec3(equal(modId, ivec3(0)));\n\t\t\t\n\t\t\tfloat hf100 = MapToSurf(dT, dTLen, aT, aTLen, wrapP+vec3(hfs.x,0,0));\n\t\t\tfloat hf010 = MapToSurf(dT, dTLen, aT, aTLen, wrapP+vec3(0,hfs.y,0));\n\t\t\tfloat hf001 = MapToSurf(dT, dTLen, aT, aTLen, wrapP+vec3(0,0,hfs.z));\n\t\t\tfloat hf011 = MapToSurf(dT, dTLen, aT, aTLen, wrapP+vec3(0,hfs.y,hfs.z));\n\t\t\tfloat hf101 = MapToSurf(dT, dTLen, aT, aTLen, wrapP+vec3(hfs.x,0,hfs.z));\n\t\t\tfloat hf110 = MapToSurf(dT, dTLen, aT, aTLen, wrapP+vec3(hfs.x,hfs.y,0));\n\t\t\tfloat hf111 = MapToSurf(dT, dTLen, aT, aTLen, wrapP+vec3(hfs.x,hfs.y,hfs.z));\n\t\t\n\t\t\tvalue += modidx.z*hf001;\n\t\t\thf100 += modidx.z*hf101;\n\t\t\thf010 += modidx.z*hf011;\n\t\t\thf110 += modidx.z*hf111;\n\t\t\tvalue += modidx.y*hf010;\n\t\t\thf100 += modidx.y*hf110;\n\t\t\tvalue += modidx.x*hf100;\n\t\t}\n "};class bi extends w{constructor(e){super(),this.uniformsNeedUpdate=!0,this.uniforms=x.clone(Mi.uniforms),this.vertexShader=Mi.vertexShader,this.fragmentShader=Mi.fragmentShader,this.setValues(e)}setGBuffer(e){this.uniforms.tPos.value=e}setInputBuffer(e){this.uniforms.tProp.value=e,this.uniforms.opacity.value=1}setClipMatrix(e){this.uniforms.clipMatrix.value=e}setDag(e,t,i,n,s){this.uniforms.dagTex.value=e,this.uniforms.attTex.value=t,this.uniforms.start.value=i,this.uniforms.dwtLev.value=n,this.uniforms.codeMax.value=s}setGeom(e,t,i,n){this.uniforms.lo.value=e,this.uniforms.cellSize.value=t,this.uniforms.newShape.value=i,this.uniforms.res.value=n}setMinMax(e,t){this.uniforms.minVal.value=e,this.uniforms.maxVal.value=t}}const Ei={uniforms:{tPos:{value:null},tIllum:{value:null},tProp:{value:null},tDepth:{value:null},opacity:{value:1},tColorBar:{value:null},omin:{value:0},omax:{value:1},cmapMin:{value:0},cmapMax:{value:1}},vertexShader:"\n\n varying vec2 vUv;\n\n void main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n }",fragmentShader:"\n\n precision highp float;\n precision highp int;\n precision mediump usampler3D;\n\n uniform float opacity;\n\n\t\tuniform sampler2D tIllum;\n\t\tuniform sampler2D tPos;\n\t\tuniform sampler2D tProp;\n\t\tuniform sampler2D tDepth;\n uniform sampler2D tColorBar;\n\n uniform float omin;\n uniform float omax;\n uniform float cmapMin;\n uniform float cmapMax;\n\n varying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvec4 pos = texture2D( tPos, vUv );\n\n if (pos.a <= 1.0) {\n discard;\n }\n\n vec4 propValue = texture2D( tProp, vUv ).rgba;\n\n float property = propValue.r;\n\n float realProp = property * (omax - omin) + omin;\n\n float cmapUV = (realProp - cmapMin) / (cmapMax - cmapMin);\n\n vec4 diffuse = texture2D( tColorBar, vec2(cmapUV) );\n\n\t\t\tgl_FragColor.rgb = diffuse.rgb * texture2D( tIllum, vUv ).rgb;\n\t\t\tgl_FragColor.a = property > 0.001 ? propValue.a : 0.0;\n\n gl_FragDepthEXT = propValue.a > 0.0 ? texture2D( tDepth, vUv ).r : 1000.0;\n\t\t}\n "};class Si{static generateTexture1d(e,t=!1){const i=t?e.length:1,n=t?1:e.length,s=e.length,r=new Uint8Array(4*s);for(let t=0;t{let a=s.children.find((t=>t.name===e));if(a){if(!Ri(a))throw Error("non-group object exists.")}else a=new T,a.name=e,t?.(a,[...r.slice(0,n),e]),s.add(a),i?.(a,[...r.slice(0,n),e]),s=a;s=a})),s}static addObject(e,t,i,n,...s){const r=this.ensurePath(e,i,n,...s);if(i?.(t,[...s,t.name]),Ri(t)){const e=t;Ai.forEach(e,!1,((t,...n)=>(i?.(t,[...s,e.name,...n]),!0)))}if(r.children.push(t),Ri(t)){const e=t;Ai.forEach(e,!1,((t,...i)=>(n?.(t,[...s,e.name,...i]),!0))),n?.(t,[...s,t.name])}}static removePath(e,t,i,n,...s){if(!e)throw Error("invalid root group");if(0===s.length)throw Error("empty path");const r=Ai.findOffspring(e,...s);let a=s;if(r){const o={targetObject:r};do{const t=o.targetObject.parent,h=t.children.indexOf(o.targetObject);if(i?.(r,a),Ri(o.targetObject)){o.targetObject.children.slice(0).forEach((t=>this.removePath(e,!1,i,n,...s,t.name)))}t.children.splice(h,1),n?.(r,a),o.targetObject=t,a=a.slice(0,a.length-1)}while(t&&0===o.targetObject.children.length&&o.targetObject!==e)}}static findOffspring(e,...t){if(0===t.length)return e;const i=t[0],n=t.slice(1),s=e.children.find((e=>e.name===i));if(s){if(0===n.length)return s;if(s.children.length>0)return Ai.findOffspring(s,...n)}}static forEach(e,t,i,...n){for(const s of e.children)if(s.children.length>0){if(t||i(s,...n,s.name),!Ai.forEach(s,t,i,...n,s.name))return!1}else i(s,...n,s.name);return!0}}function Pi(e,t){let i=e.next();for(;!i.done;){if(t(i.value))return i.value;i=e.next()}}function Oi(e,t){let i=e.next();for(;!i.done;)t(i.value),i=e.next()}function Li(e,t){let i=e.next();for(;!i.done;){if(!t(i.value))return!0;i=e.next()}return!1}function Di(e){const t=[];return Oi(e,(e=>t.push(e))),t}class zi{sceneItems=new Map;wrappedDefaultScene;wrappedDefaultRoot;wrappedLights=[];objectAdding=new ht;objectAdded=new ht;objectRemoving=new ht;objectRemoved=new ht;constructor(){const e=new C(5066061),t=new _(16777215,.7);t.position.set(1,1,1);const i=new _(16777215,.5);i.position.set(-1.5,-1.5,1.5),this.lights=[e,t,i],this.wrappedDefaultScene=this.addScene(Ot),this.wrappedDefaultRoot=this.getRootGroup(Ot)}get defaultScene(){return this.wrappedDefaultScene}get defaultRoot(){return this.wrappedDefaultRoot}get lights(){return this.wrappedLights}set lights(e){this.wrappedLights=e,this.sceneItems.forEach((t=>{const{scene:i}=t;i.children=i.children.filter((e=>!(e instanceof R))),i.add(...e)}))}addScene(e,t=void 0,i=void 0){const n=this.sceneItems.get(e);if(n)return n;const s=new A;s.name=e,s.add(...this.lights.map((e=>e.clone())));const r=new T;r.name=Lt,this.defaultRoot&&!1!==i&&(r.matrix=this.defaultRoot.matrix),r.matrixAutoUpdate=!1;const a=new T;a.name=Dt,r.add(a),s.add(r),this.objectAdding.trigger({sceneKey:e,paths:[],object:s});const o={scene:s,order:t};return this.sceneItems.set(e,o),this.objectAdded.trigger({sceneKey:e,paths:[],object:s}),o}hasObject(e,...t){const i=this.sceneItems.get(e);if(!i)return!1;const n=i.scene;return void 0!==Ai.findOffspring(n,...t)}findGroup(e,...t){const i=this.sceneItems.get(e);if(!i)throw Error("invalid key");const n=i.scene,s=Ai.findOffspring(n,...t);if(!s)throw Error("invalid path");if(!Ri(s))throw Error("invalid target group type");return s}addGroup(e,t,...i){const n=this.ensurePath(e,((t,i)=>this.objectAdding.trigger({sceneKey:e,paths:i,object:t})),((t,i)=>this.objectAdded.trigger({sceneKey:e,paths:i,object:t})),...i),s=n.children.find((e=>e.name===t));if(void 0!==s)return s;const r=new T;return r.name=t,this.objectAdding.trigger({sceneKey:e,paths:[...i,t],object:r}),n.add(r),this.objectAdded.trigger({sceneKey:e,paths:[...i,t],object:r}),r}addObject(e,t,...i){if(!t.name)throw Error("unnamed object");const n=this.ensurePath(e,((t,i)=>this.objectAdding.trigger({sceneKey:e,paths:i,object:t})),((t,i)=>this.objectAdded.trigger({sceneKey:e,paths:i,object:t})),...i);if(this.objectAdding.trigger({sceneKey:e,paths:[...i,t.name],object:t}),Ri(t)){const n=t;Ai.forEach(n,!1,((n,...s)=>(this.objectAdding.trigger({sceneKey:e,paths:[e,...i,t.name,...s],object:n}),!0)))}if(n.add(t),Ri(t)){const n=t;Ai.forEach(n,!1,((n,...s)=>(this.objectAdded.trigger({sceneKey:e,paths:[e,...i,t.name,...s],object:n}),!0)))}this.objectAdded.trigger({sceneKey:e,paths:[...i,t.name],object:t})}removeObject(e,...t){let i;if(0===t.length){if(i=this.sceneItems.get(e)?.scene,!i)throw Error("invalid scene");return this.objectRemoving.trigger({sceneKey:e,paths:[],object:i}),this.sceneItems.delete(e),this.objectRemoved.trigger({sceneKey:e,paths:[],object:i}),i}const n=t.slice(0,t.length-1),s=this.findGroup(e,...n),r=s.children.findIndex((e=>e.name===t[t.length-1]));if(!(r<0))return i=s.children[r],this.objectRemoving.trigger({sceneKey:e,paths:t,object:i}),s.children.splice(r,1),this.objectRemoved.trigger({sceneKey:e,paths:t,object:i}),i}getObject(e,...t){let i;if(0===t.length){if(i=this.sceneItems.get(e)?.scene,!i)throw Error("invalid scene");return i}const n=t.slice(0,t.length-1),s=this.findGroup(e,...n),r=s.children.findIndex((e=>e.name===t[t.length-1]));if(!(r<0))return s.children[r]}getSceneItem(e){const t=this.sceneItems.get(e);if(t)return t}getRootGroup(e){const t=this.getSceneItem(e);if(!t)throw Error("scene not found.");const i=t.scene.children.find((e=>e.name===Lt));if(!i)throw Error("root group not found.");return i}updateWorldMatrix(e){this.sceneItems.forEach((t=>{if(!1!==t.syncWorldMatrix){const i=t.scene.children.find((e=>e.name===Lt));i&&(i.matrix=e,i.matrixWorldNeedsUpdate=!0)}}))}forEachScene(e){this.sceneItems.forEach(((t,i)=>{e(i,t.scene)}))}forEachObject(e,t=!1){this.sceneItems.forEach((i=>{Ai.forEach(i.scene,t,e,i.scene.name)}))}render(e,t){const i=Di(this.sceneItems.values());i.sort(((e,t)=>(void 0===e.order?0:e.order)-(void 0===t.order?0:t.order))),i.forEach((i=>{e.render(i.scene,t)}))}dispose(){this.sceneItems.forEach((e=>{const t=Ai.findOffspring(e.scene,Lt,Dt);zi.disposeGroup(t),t.clear()}))}static disposeGroup(e){e.children.forEach((e=>{_i(e)&&this.disposeMesh(e),e.children.length>0&&this.disposeGroup(e)})),e.clear()}static disposeMesh(e){e.geometry.dispose(),Array.isArray(e.material)?e.material.forEach((e=>e.dispose())):e.material.dispose()}ensurePath(e,t,i,...n){const s=this.sceneItems.get(e);if(!s)throw Error("invalid scene");const r=s.scene;return Ai.ensurePath(r,t,i,...n)}}class Ii{factories=[];constructor(){this.registerFactory(new Ci)}registerFactory(e){-1===this.factories.indexOf(e)&&(this.factories.push(e),this.factories.sort(((e,t)=>e.order-t.order)))}unregisterFactory(e){const t=this.factories.indexOf(e);-1!==t&&this.factories.splice(t,1)}createPositionDetectMaterial(e,t,i){let n;for(let s=0;s{e.restore()}))}}const Bi=e=>{const i=new t;let n=e;for(;n&&n.name!==Lt;)n.matrixAutoUpdate&&n.updateMatrix(),i.premultiply(n.matrix),n=n.parent;return i};class Fi{objectTransformCallback=Bi;excludeCallback;detectMaterialFactoryHub=new Ii;createDetectScene(e){const t=Array();let i;if(e instanceof zi){const n=new zi;e.forEachScene(((e,i)=>{const s=this.createPositionDetectGroup(i,1,t);if(s&&s.children.length>0){n.addScene(e).scene.add(...s.children)}})),i=n}else if(Array.isArray(e)){const n=[];e.forEach((e=>{const i=this.createPositionDetectGroup(e,1,t);i&&i.children.length>0&&n.push(i)})),i=n}else i=this.createPositionDetectGroup(e,1,t);const n=new Map;return t.forEach((e=>{n.set(e.id,e.key)})),{scene:i,map:n}}createPositionDetectMesh(e,i){const n=e.geometry,s=e.material,r=void 0===this.objectTransformCallback?new t:this.objectTransformCallback(e);let a;if(s instanceof Array){a=new Array(s.length);for(let e=0;e{if(e instanceof T||e instanceof A){const t=this.createPositionDetectGroup(e,s,i);t&&t.children.length>0&&(t.matrix=e.matrix,t.matrixAutoUpdate=!1,n.add(t),0!==i.length&&(s=i[i.length-1].id+1))}else if(e instanceof S){const t=this.createPositionDetectMesh(e,s);i.push({id:s,key:e.name}),n.add(t),s=i[i.length-1].id+1}})),n}}class Ni{order=9999;toHitTestResult(e,t){const{object:i}=e;if("Mesh"===i.type)return{type:"Mesh",object:i,distance:e.distance,pos:e.point.applyMatrix4(t),normal:e.face?.normal,faceIndex:e.faceIndex,face:[e.face?.a,e.face?.b,e.face?.c]}}}class Ui{factories=[];constructor(){this.register(new Ni)}toHitTestResult(e,t){let i,n=0;for(;!i;)i=this.factories[n].toHitTestResult(e,t),n+=1;if(!i)throw new Error("No converter found for the intersection.");return i}register(e){this.factories.push(e),this.factories.sort(((e,t)=>e.order-t.order))}unregister(e){const t=this.factories.indexOf(e);t>=0&&this.factories.splice(t,1)}}const Gi={uniforms:{uAccumulate:{value:null},uAccumulateAlpha:{value:null}},vertexShader:"#version 300 es\n precision highp float;\n layout(location = 0) in vec3 position;\n\n\t\tvoid main() {\n\n\t\t\tgl_Position = vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"#version 300 es\n precision highp float;\n\n uniform sampler2D uAccumulate;\n uniform sampler2D uAccumulateAlpha;\n out vec4 fragColor;\n\n void main() {\n ivec2 fragCoord = ivec2(gl_FragCoord.xy);\n vec4 accum = texelFetch(uAccumulate, fragCoord, 0);\n float a = 1.0 - accum.a;\n accum.a = texelFetch(uAccumulateAlpha, fragCoord, 0).r;\n fragColor = vec4(a * accum.rgb / clamp(accum.a, 0.001, 50000.0), a);\n }\n"};class Hi{gl;extensions;state;properties;capabilities;supportsInvalidateFramebuffer;constructor(e,t,i,n,s){this.gl=e,this.extensions=t,this.state=i,this.properties=n,this.capabilities=s,this.supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent)}useMultisampledRTT(e){const t=this.properties.get(e);return this.capabilities.isWebGL2&&e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==t.__useRenderToTexture}updateMultisampleRenderTarget(e){if(this.capabilities.isWebGL2&&e.samples>0&&!1===this.useMultisampledRTT(e)){const t=e.isWebGLMultipleRenderTargets?e.texture:[e.texture],{width:i}=e,{height:n}=e;let s=this.gl.COLOR_BUFFER_BIT;const r=[],a=e.stencilBuffer?this.gl.DEPTH_STENCIL_ATTACHMENT:this.gl.DEPTH_ATTACHMENT,o=this.properties.get(e),h=!0===e.isWebGLMultipleRenderTargets;if(h)for(let e=0;e(_i(e)&&this.unbindObject(e),!0)),!0),e.forEachScene(((e,t)=>{this.unBindScene(t)})),e.objectAdded.remove(this.onObjectAdded),e.objectRemoving.remove(this.onObjectRemoving),this.unInit()}if(this.engine=e,this.engine){const e=this.engine.viewPortSize,{scenes:t}=this.engine;t.objectAdded.add(this.onObjectAdded),t.objectRemoving.add(this.onObjectRemoving),this.init(e.width,e.height),this.engine.sizeChangedEvent.add(this.onSizeChanged),t.forEachScene(((e,t)=>{this.bindScene(t)})),t.forEachObject((e=>(_i(e)&&this.bindObject(e),!0)),!0)}}}onSizeChanged=e=>{e&&(this.opaqueObjectRenderTarget?.setSize(e.width,e.height),this.opacityObjectRenderTarget?.setSize(e.width,e.height))};onObjectAdded=e=>{e&&(e.object instanceof A?this.bindScene(e.object):_i(e.object)&&this.bindObject(e.object))};onObjectRemoving=e=>{e&&(e.object instanceof A?this.unBindScene(e.object):_i(e.object)&&this.unbindObject(e.object))};init(e,t){this.opaqueObjectRenderTarget=new P(e,t,{samples:4,type:O,depthBuffer:!0,stencilBuffer:!0});const i=x.clone(Ge.uniforms);i.tDiffuse.value=this.opaqueObjectRenderTarget.texture,i.opacity.value=1,this.opaqueMaterial=new w({uniforms:i,vertexShader:Ge.vertexShader,fragmentShader:Ge.fragmentShader,blending:L,depthTest:!0,depthWrite:!0,transparent:!0}),this.opaqueQuad=new He(this.opaqueMaterial),this.opacityObjectRenderTarget=new D(e,t,2,{samples:4,minFilter:z,magFilter:z,wrapS:I,wrapT:I,type:O,encoding:B,depthBuffer:!0,stencilBuffer:!0}),this.opacityObjectRenderTarget.texture[0].format=E,this.opacityObjectRenderTarget.texture[0].name="uAccumulate",this.opacityObjectRenderTarget.texture[1].format=F,this.opacityObjectRenderTarget.texture[1].name="uAccumulateAlpha",this.opacityMaterial=new N({name:"WBOIT-post-processing",uniforms:{uAccumulate:{value:this.opacityObjectRenderTarget.texture[0]},uAccumulateAlpha:{value:this.opacityObjectRenderTarget.texture[1]}},vertexShader:Gi.vertexShader,fragmentShader:Gi.fragmentShader,blending:U,blendDst:G,blendSrc:H,blendEquation:k,depthTest:!1}),this.opacityQuad=new He(this.opacityMaterial)}unInit(){this.opaqueQuad?.dispose(),this.opaqueQuad=void 0,this.opaqueMaterial?.dispose(),this.opaqueMaterial=void 0,this.opaqueObjectRenderTarget?.dispose(),this.opaqueObjectRenderTarget=void 0,this.opacityQuad?.dispose(),this.opacityQuad=void 0,this.opacityMaterial?.dispose(),this.opacityMaterial=void 0,this.opacityObjectRenderTarget?.dispose(),this.opacityObjectRenderTarget=void 0}bindObject(e){It(e,this.onPreRenderingObject,this.onPostRenderingObject,10,{type:"DetectFirstTransparentActionsTrait",src:e,ref:this.ref,savedMaterialProperties:{depthTest:!1,depthFunc:j,depthWrite:!1,blendDstAlpha:G,blendDst:H,blendEquation:k,blendEquationAlpha:k,blendSrc:H,blendSrcAlpha:V}});(Array.isArray(e.material)?e.material:[e.material]).forEach((e=>{const t=e;void 0!==t.enableWeightZ&&(t.enableWeightZ=!0)}))}unbindObject(e){Bt(e,this.onPreRenderingObject,this.onPostRenderingObject);(Array.isArray(e.material)?e.material:[e.material]).forEach((e=>{const t=e;void 0!==t.enableWeightZ&&(t.enableWeightZ=!1)}))}bindScene(e){It(e,this.onPreRenderingScene,this.onPostRenderingScene,10)}unBindScene(e){Bt(e,this.onPreRenderingScene,this.onPostRenderingScene)}onPreRenderingObject=(e,t,i,n,s,r,a)=>{const o=a;if(o.ref.opaqueObjectsFound||s.transparent||!this.opaqueObjectRenderTarget||(o.ref.opaqueObjectsFound=!0,e.setRenderTarget(this.opaqueObjectRenderTarget),e.state.buffers.depth.setMask(!0),e.state.buffers.color.setMask(!0),e.setClearColor(new g(0,0,0),0),e.clear()),!o.ref.opacityObjectsFound&&s.transparent&&this.opacityObjectRenderTarget){o.ref.opacityObjectsFound=!0;new Hi(e.getContext(),e.extensions,e.state,e.properties,e.capabilities).updateMultisampleRenderTarget(this.opaqueObjectRenderTarget);const t=void 0!==e.properties.get(this.opacityObjectRenderTarget).__webglFramebuffer;if(e.setRenderTarget(this.opacityObjectRenderTarget),!t){const t=e.properties.get(this.opaqueObjectRenderTarget),i=e.properties.get(this.opacityObjectRenderTarget),{state:n}=e,s=e.getContext();n.bindFramebuffer(s.FRAMEBUFFER,i.__webglMultisampledFramebuffer),s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_STENCIL_ATTACHMENT,s.RENDERBUFFER,t.__webglDepthRenderbuffer)}o.ref.savedClearColor=e.getClearColor(o.ref.savedClearColor),o.ref.savedClearAlpha=e.getClearAlpha(),e.state.buffers.color.setMask(!0),e.setClearColor(new g(0,0,0),1),e.clearColor(),this.ref.opaqueObjectsFound||(e.state.buffers.depth.setMask(!0),e.clearDepth())}if(o.ref.opacityObjectsFound){const e=s;void 0!==e.enableWeightZ&&!1===e.enableWeightZ&&(e.enableWeightZ=!0),o.savedMaterialProperties.depthFunc=s.depthFunc,o.savedMaterialProperties.depthTest=s.depthTest,o.savedMaterialProperties.depthWrite=s.depthWrite,o.savedMaterialProperties.blendDst=s.blendDst,o.savedMaterialProperties.blendDstAlpha=s.blendDstAlpha,o.savedMaterialProperties.blendEquation=s.blendEquation,o.savedMaterialProperties.blendEquationAlpha=s.blendEquationAlpha,o.savedMaterialProperties.blending=s.blending,o.savedMaterialProperties.blendSrc=s.blendSrc,o.savedMaterialProperties.blendSrcAlpha=s.blendSrcAlpha,s.depthTest=!0,s.depthFunc=j,s.depthWrite=!1,s.blending=U,s.blendDstAlpha=G,s.blendDst=H,s.blendEquation=k,s.blendEquationAlpha=k,s.blendSrc=H,s.blendSrcAlpha=V}};onPostRenderingObject=(e,t,i,n,s,r,a)=>{const o=a;o.ref.opacityObjectsFound&&(s.depthFunc=o.savedMaterialProperties.depthFunc,s.depthTest=o.savedMaterialProperties.depthTest,s.depthWrite=o.savedMaterialProperties.depthWrite,s.blendDst=o.savedMaterialProperties.blendDst,s.blendDstAlpha=o.savedMaterialProperties.blendDstAlpha,s.blendEquation=o.savedMaterialProperties.blendEquation,s.blendEquationAlpha=o.savedMaterialProperties.blendEquationAlpha,s.blending=o.savedMaterialProperties.blending,s.blendSrc=o.savedMaterialProperties.blendSrc,s.blendSrcAlpha=o.savedMaterialProperties.blendSrcAlpha)};onPreRenderingScene=e=>{this.ref.opaqueObjectsFound=!1,this.ref.opacityObjectsFound=!1,this.savedTarget=e.getRenderTarget()};onPostRenderingScene=e=>{if(this.ref.opaqueObjectsFound){new Hi(e.getContext(),e.extensions,e.state,e.properties,e.capabilities).updateMultisampleRenderTarget(this.opaqueObjectRenderTarget),e.setRenderTarget(this.savedTarget),this.opaqueQuad?.render(e)}this.ref.opacityObjectsFound&&(e.setRenderTarget(this.savedTarget),this.opacityQuad?.render(e),e.setClearColor(this.ref.savedClearColor,this.ref.savedClearAlpha))}}class ji{static Rotate(e,i,n,s,r,a=void 0){const o=Date.now(),h={lastAngle:0},d=()=>{const p=Date.now()-o;let l;const c=()=>{if(0!==l){let s=(new t).makeRotationAxis(i,l);if(n){const i=n.clone();i.applyMatrix4(e.matrix),s=s.multiply((new t).makeTranslation(-i.x,-i.y,-i.z)),s=(new t).makeTranslation(i.x,i.y,i.z).multiply(s)}if(a){const e=a;e.matrix=s.multiply(e.matrix),e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!0}else e.rotationMatrix=s.multiply(e.rotationMatrix)}};if(p{const t=Date.now()-s;if(t{const d=Date.now()-r,p=i=>{const n=new t;n.makeTranslation(s.x,s.y,0),n.scale(new a(i,i,1)),n.multiply((new t).makeTranslation(-s.x,-s.y,0));const{camera:r}=e;r.afterProjectionMatrix=n.multiply(o),r.raiseCameraChangeEvent()};if(d{const i=Date.now()-v;let n,s;const a=()=>{let i=new t,a=r;a&&(a=a.clone(),a.applyMatrix4(e.matrix),i=i.makeTranslation(-a.x,-a.y,-a.z));const o=(new t).makeRotationAxis(c,n);m=m.applyMatrix4(o);if(i=(new t).makeRotationAxis(m,s).multiply(o).multiply(i),a&&(i=(new t).makeTranslation(a.x,a.y,a.z).multiply(i)),h){const e=h;e.matrix=i.multiply(e.matrix),e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!0}else e.rotationMatrix=i.multiply(e.rotationMatrix)};if(i{this.timeoutId=setTimeout((async()=>{try{if(i.signal.aborted)throw new Vi;const t=await e(i);n(t)}catch(e){e.isCancel?n(void 0):s(e)}finally{this.timeoutId=void 0,this.abortController===i&&(this.abortController=void 0)}}),t)}))}abort(){this.abortController&&this.abortController.abort()}}function Yi(e){return{type:"axios progress",lengthComputable:!0,loaded:e.loaded,total:e.total}}class Xi{static checkPointIn(e,t,i){let n=0;const s=e.clone();s.applyMatrix4(t.clone());const r=new W,o=new a(0,0,1).applyMatrix4(t.clone()).normalize();return r.set(s,o),i.filter((e=>e.visible)).forEach((t=>{if(t instanceof S){let i=0;if(t.geometry.boundingBox||t.geometry.computeBoundingBox(),t.geometry.boundingBox?.containsPoint(e)){const e=[],n=[];Array.isArray(t.material)?t.material.forEach((t=>e.push(t))):e.push(t.material),e.forEach((e=>{n.push(e.side),e.side=K}));i=r.intersectObject(t).length,e.forEach(((e,t)=>{e.side=n[t]}))}n+=i}})),!!n}static containsPoint(e,t,i,n,s){const r=new a,o=new a,h=new a;r.subVectors(n,t),o.subVectors(i,t),h.subVectors(e,t);const d=(new a).crossVectors(r,o).normalize().dot(h);if(Math.abs(d)>s)return;const p=r.dot(r),l=r.dot(o),c=r.dot(h),u=o.dot(o),g=o.dot(h),f=p*u-l*l;if(0===f)return;const m=1/f,w=(u*c-l*g)*m,v=(p*g-l*c)*m;return v>=0&&w>=0&&w+v<=1.000001?{u:w,v:v}:void 0}static checkSurfacePoint(e,t){const i=e.clone();return t.some((e=>e instanceof S&&Xi.pointInMesh(e,i)))}static getSurfaces(e,t){const i=e.clone();return t.filter((e=>!!(e instanceof S&&Xi.pointInMesh(e,i))))}static pointInMesh(e,t){const i=t.clone(),n=new Y,s=new a,r=new a,o=new a;if(e.geometry.boundingBox||e.geometry.computeBoundingBox(),!e.geometry.boundingBox)throw Error("error on calculate bounding box");const{x:h,y:d,z:p}=e.geometry.boundingBox.max,{x:l,y:c,z:u}=e.geometry.boundingBox.min,g=Math.max(h-l,d-c,p-u)/1e4;if(e.geometry.boundingBox.containsPoint(i))if(e.geometry.index){const{count:t,array:a}=e.geometry.index,{position:h}=e.geometry.attributes,{array:d,itemSize:p}=h;for(let e=0;ee===t[i])))}class Qi extends ke{engine;constructor(e){super(),this.engine=e}render(e,t){e.setRenderTarget(this.renderToScreen?null:t),e.clear(),this.engine.renderFrame()}}class $i{engine;fxaaPass;wrappedEnableFxaa=!0;get enableFxaa(){return this.wrappedEnableFxaa}set enableFxaa(e){this.wrappedEnableFxaa!==e&&this.wrappedEnableFxaa&&(this.fxaaPass=new je(Ve),this.engine&&(this.fxaaPass.material.uniforms.resolution.value=new r(1/this.engine.width,1/this.engine.height)))}bind(e){this.engine!==e&&(void 0!==this.engine&&(this.engine.sizeChangedEvent.remove(this.onSizeChanged),this.clearComposer()),this.engine=e,this.engine&&(this.engine.sizeChangedEvent.add(this.onSizeChanged),this.initRenderPasses(),this.enableFxaa&&this.engine.postComposer&&(this.fxaaPass=new je(Ve),this.fxaaPass.material.uniforms.resolution.value=new r(1/this.engine.width,1/this.engine.height),this.engine.postComposer.addPass(this.fxaaPass))))}onSizeChanged=()=>{this.engine&&this.fxaaPass&&(this.fxaaPass.material.uniforms.resolution.value=new r(1/this.engine.width,1/this.engine.height))};initRenderPasses(){if(!this.engine||!this.engine.renderer)throw new Error("Renderer is not initialized");let e=this.engine.postComposer;e||(e=new We(this.engine.renderer,new P(this.engine.width,this.engine.height,{depthBuffer:!0,stencilBuffer:!0})),e.renderTarget1.texture.name="EffectComposer.rt1",this.engine.postComposer=e);const t=new Qi(this.engine);e.addPass(t)}clearComposer(){this.engine&&this.engine.postComposer&&(this.engine.postComposer.dispose(),this.engine.postComposer=void 0)}}class Ji{YTable=new Array(64);UVTable=new Array(64);fdtbl_Y=new Array(64);fdtbl_UV=new Array(64);YDC_HT=[];UVDC_HT=[];YAC_HT=[];UVAC_HT=[];bitcode=new Array(65535);category=new Array(65535);outputfDCTQuant=new Array(64);DU=new Array(64);byteout=[];bytenew=0;bytepos=7;YDU=new Array(64);UDU=new Array(64);VDU=new Array(64);clt=new Array(256);RGB_YUV_TABLE=new Array(2048);currentQuality;static ZigZag=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63];static std_dc_luminance_nrcodes=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];static std_dc_luminance_values=[0,1,2,3,4,5,6,7,8,9,10,11];static std_ac_luminance_nrcodes=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125];static std_ac_luminance_values=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250];static std_dc_chrominance_nrcodes=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];static std_dc_chrominance_values=[0,1,2,3,4,5,6,7,8,9,10,11];static std_ac_chrominance_nrcodes=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119];static std_ac_chrominance_values=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];constructor(e){this.init(e)}initQuantTables(e){const t=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99];for(let i=0;i<64;i+=1){let n=Math.floor((t[i]*e+50)/100);n<1?n=1:n>255&&(n=255),this.YTable[Ji.ZigZag[i]]=n}const i=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99];for(let t=0;t<64;t+=1){let n=Math.floor((i[t]*e+50)/100);n<1?n=1:n>255&&(n=255),this.UVTable[Ji.ZigZag[t]]=n}const n=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379];let s=0;for(let e=0;e<8;e+=1)for(let t=0;t<8;t+=1)this.fdtbl_Y[s]=1/(this.YTable[Ji.ZigZag[s]]*n[e]*n[t]*8),this.fdtbl_UV[s]=1/(this.UVTable[Ji.ZigZag[s]]*n[e]*n[t]*8),s+=1}static computeHuffmanTbl(e,t){let i=0,n=0;const s=[];for(let r=1;r<=16;r+=1){for(let a=1;a<=e[r];a+=1)s[t[n]]=[],s[t[n]][0]=i,s[t[n]][1]=r,n+=1,i+=1;i*=2}return s}initHuffmanTbl(){this.YDC_HT=Ji.computeHuffmanTbl(Ji.std_dc_luminance_nrcodes,Ji.std_dc_luminance_values),this.UVDC_HT=Ji.computeHuffmanTbl(Ji.std_dc_chrominance_nrcodes,Ji.std_dc_chrominance_values),this.YAC_HT=Ji.computeHuffmanTbl(Ji.std_ac_luminance_nrcodes,Ji.std_ac_luminance_values),this.UVAC_HT=Ji.computeHuffmanTbl(Ji.std_ac_chrominance_nrcodes,Ji.std_ac_chrominance_values)}initCategoryNumber(){let e=1,t=2;for(let i=1;i<=15;i+=1){for(let n=e;n>0]=38470*e,this.RGB_YUV_TABLE[e+512>>0]=7471*e+32768,this.RGB_YUV_TABLE[e+768>>0]=-11059*e,this.RGB_YUV_TABLE[e+1024>>0]=-21709*e,this.RGB_YUV_TABLE[e+1280>>0]=32768*e+8421375,this.RGB_YUV_TABLE[e+1536>>0]=-27439*e,this.RGB_YUV_TABLE[e+1792>>0]=-5329*e}writeBits(e){const t=e[0];let i=e[1]-1;for(;i>=0;)t&1<>8&255),this.writeByte(255&e)}fDCTQuant(e,t){const i=e;let n,s,r,a,o,h,d,p,l=0;for(let e=0;e<8;e+=1){n=i[l],s=i[l+1],r=i[l+2],a=i[l+3],o=i[l+4],h=i[l+5],d=i[l+6],p=i[l+7];const e=n+p,t=n-p,c=s+d,u=s-d,g=r+h,f=r-h,m=a+o,w=a-o;let v=e+m;const x=e-m;let y=c+g,M=c-g;i[l]=v+y,i[l+4]=v-y;const b=.707106781*(M+x);i[l+2]=x+b,i[l+6]=x-b,v=w+f,y=f+u,M=u+t;const E=.382683433*(v-M),S=.5411961*v+E,T=1.306562965*M+E,C=.707106781*y,_=t+C,R=t-C;i[l+5]=R+S,i[l+3]=R-S,i[l+1]=_+T,i[l+7]=_-T,l+=8}l=0;for(let e=0;e<8;e+=1){n=i[l],s=i[l+8],r=i[l+16],a=i[l+24],o=i[l+32],h=i[l+40],d=i[l+48],p=i[l+56];const e=n+p,t=n-p,c=s+d,u=s-d,g=r+h,f=r-h,m=a+o,w=a-o;let v=e+m;const x=e-m;let y=c+g,M=c-g;i[l]=v+y,i[l+32]=v-y;const b=.707106781*(M+x);i[l+16]=x+b,i[l+48]=x-b,v=w+f,y=f+u,M=u+t;const E=.382683433*(v-M),S=.5411961*v+E,T=1.306562965*M+E,C=.707106781*y,_=t+C,R=t-C;i[l+40]=R+S,i[l+24]=R-S,i[l+8]=_+T,i[l+56]=_-T,l+=1}let c;for(let e=0;e<64;e+=1)c=i[e]*t[e],this.outputfDCTQuant[e]=c>0?c+.5|0:c-.5|0;return this.outputfDCTQuant}writeAPP0(){this.writeWord(65504),this.writeWord(16),this.writeByte(74),this.writeByte(70),this.writeByte(73),this.writeByte(70),this.writeByte(0),this.writeByte(1),this.writeByte(1),this.writeByte(0),this.writeWord(1),this.writeWord(1),this.writeByte(0),this.writeByte(0)}writeSOF0(e,t){this.writeWord(65472),this.writeWord(17),this.writeByte(8),this.writeWord(t),this.writeWord(e),this.writeByte(3),this.writeByte(1),this.writeByte(17),this.writeByte(0),this.writeByte(2),this.writeByte(17),this.writeByte(1),this.writeByte(3),this.writeByte(17),this.writeByte(1)}writeDQT(){this.writeWord(65499),this.writeWord(132),this.writeByte(0);for(let e=0;e<64;e+=1)this.writeByte(this.YTable[e]);this.writeByte(1);for(let e=0;e<64;e+=1)this.writeByte(this.UVTable[e])}writeDHT(){this.writeWord(65476),this.writeWord(418),this.writeByte(0);for(let e=0;e<16;e+=1)this.writeByte(Ji.std_dc_luminance_nrcodes[e+1]);for(let e=0;e<=11;e+=1)this.writeByte(Ji.std_dc_luminance_values[e]);this.writeByte(16);for(let e=0;e<16;e+=1)this.writeByte(Ji.std_ac_luminance_nrcodes[e+1]);for(let e=0;e<=161;e+=1)this.writeByte(Ji.std_ac_luminance_values[e]);this.writeByte(1);for(let e=0;e<16;e+=1)this.writeByte(Ji.std_dc_chrominance_nrcodes[e+1]);for(let e=0;e<=11;e+=1)this.writeByte(Ji.std_dc_chrominance_values[e]);this.writeByte(17);for(let e=0;e<16;e+=1)this.writeByte(Ji.std_ac_chrominance_nrcodes[e+1]);for(let e=0;e<=161;e+=1)this.writeByte(Ji.std_ac_chrominance_values[e])}writeSOS(){this.writeWord(65498),this.writeWord(12),this.writeByte(3),this.writeByte(1),this.writeByte(0),this.writeByte(2),this.writeByte(17),this.writeByte(3),this.writeByte(17),this.writeByte(0),this.writeByte(63),this.writeByte(0)}processDU(e,t,i,n,s){let r=i;const a=s[0],o=s[240];let h;const d=this.fDCTQuant(e,t);for(let e=0;e<64;e+=1)this.DU[Ji.ZigZag[e]]=d[e];const p=this.DU[0]-r;[r]=this.DU,0===p?this.writeBits(n[0]):(h=32767+p,this.writeBits(n[this.category[h]]),this.writeBits(this.bitcode[h]));let l=63;for(;l>0&&0===this.DU[l];l-=1);if(0===l)return this.writeBits(a),r;let c,u=1;for(;u<=l;){const e=u;for(;0===this.DU[u]&&u<=l;u+=1);let t=u-e;if(t>=16){c=t>>4;for(let e=1;e<=c;e+=1)this.writeBits(o);t&=15}h=32767+this.DU[u],this.writeBits(s[(t<<4)+this.category[h]]),this.writeBits(this.bitcode[h]),u+=1}return 63!==l&&this.writeBits(a),r}initCharLookupTable(){const e=String.fromCharCode;for(let t=0;t<256;t+=1)this.clt[t]=e(t)}static convert(e){if(e instanceof Uint8Array)return e;if(e instanceof Float32Array){const t=new Uint8Array(e.length);for(let i=0;i=1?255:255*n}return t}return e instanceof Uint8ClampedArray?new Uint8Array(e):e}encode(e,t){t&&this.setQuality(t),this.byteout=[],this.bytenew=0,this.bytepos=7,this.writeWord(65496),this.writeAPP0(),this.writeDQT(),this.writeSOF0(e.width,e.height),this.writeDHT(),this.writeSOS();let i=0,n=0,s=0;this.bytenew=0,this.bytepos=7;const r=Ji.convert(e.data),{width:a}=e,{height:o}=e,h=4*a;let d,p,l,c,u,g,f,m,w,v=0;for(;v>3,f=4*(7&w),g=u+m*h+f,v+m>=o&&(g-=h*(v+1+m-o)),d+f>=h&&(g-=d+f-h+4),p=r[g++],l=r[g++],c=r[g++],this.YDU[w]=(this.RGB_YUV_TABLE[p]+this.RGB_YUV_TABLE[l+256>>0]+this.RGB_YUV_TABLE[c+512>>0]>>16)-128,this.UDU[w]=(this.RGB_YUV_TABLE[p+768>>0]+this.RGB_YUV_TABLE[l+1024>>0]+this.RGB_YUV_TABLE[c+1280>>0]>>16)-128,this.VDU[w]=(this.RGB_YUV_TABLE[p+1280>>0]+this.RGB_YUV_TABLE[l+1536>>0]+this.RGB_YUV_TABLE[c+1792>>0]>>16)-128;i=this.processDU(this.YDU,this.fdtbl_Y,i,this.YDC_HT,this.YAC_HT),n=this.processDU(this.UDU,this.fdtbl_UV,n,this.UVDC_HT,this.UVAC_HT),s=this.processDU(this.VDU,this.fdtbl_UV,s,this.UVDC_HT,this.UVAC_HT),d+=32}v+=8}if(this.bytepos>=0){const e=[];e[1]=this.bytepos+1,e[0]=(1<100&&(t=100),this.currentQuality===t)return;let i=0;i=t<50?Math.floor(5e3/t):Math.floor(200-2*t),this.initQuantTables(i),this.currentQuality=t}init(e){this.initCharLookupTable(),this.initHuffmanTbl(),this.initCategoryNumber(),this.initRGBYUVTable(),this.setQuality(e)}}function en(e,t){return{data:new Ji(t).encode(e,t),width:e.width,height:e.height}}function tn(e){e._maxInstanceCount=void 0}function nn(e){e.geometry&&e.geometry.dispose(),e.material&&(Array.isArray(e.material)?e.material.forEach((e=>{e.dispose()})):e.material.dispose()),e.children&&e.children.length>0&&e.children.forEach((e=>{nn(e)}))}class sn{obj;engine;savedMatrix=new t;bind(e,t){this.obj=e,this.engine=t,It(e,this.onPreRendering,this.onPostRendering,3)}unbind(e){Bt(e,this.onPreRendering,this.onPostRendering),this.obj=void 0,this.engine=void 0}onPreRendering=(e,i,n)=>{if(this.obj&&this.engine){this.savedMatrix=this.obj.matrixWorld.clone();let e=this.obj.parent;for(;e&&e.name!==Lt;)e=e.parent;if(e){const{matrix:i}=e,s=i.clone().invert(),{adaptMatrix:r,rotationMatrix:o}=this.engine,h=new a,d=new a;r.decompose(h,new X,d),this.obj.matrixWorld.premultiply(s).premultiply((new t).makeTranslation(h.x,h.y,h.z)).premultiply(o),this.obj.modelViewMatrix.multiplyMatrices(n.matrixWorldInverse,this.obj.matrixWorld),this.obj.normalMatrix.getNormalMatrix(this.obj.modelViewMatrix)}}};onPostRendering=()=>{this.obj&&(this.obj.matrixWorld=this.savedMatrix)}}class rn{static worldToScreen(e,t){const{camera:i}=t,{viewPortSize:n}=t,s=e.clone().applyMatrix4(t.matrix);s.applyMatrix4(i.matrixWorldInverse),s.applyMatrix4(i.projectionMatrix);let a=new r(s.x,s.y);return a=a.multiplyScalar(.5),a=a.addVectors(a,new r(.5,.5)),a=a.multiply(n),a.y=n.y-a.y,a}static screenToWorld(e,t){const{camera:i,viewPortSize:n,matrix:s}=t;let o=e.clone();o.y=n.y-o.y,o=o.divide(n),o=o.multiplyScalar(2),o=o.sub(new r(1,1));let h=i.projectionMatrix.clone().multiply(i.matrixWorld).multiply(s);h=h.invert();const d=new a(o.x,o.y,1).applyMatrix4(h),p=new a(o.x,o.y,-1).applyMatrix4(h);return d.sub(p).normalize(),{near:p,dir:d}}static projectToScreen(e,t){const{camera:i}=t,{viewPortSize:n}=t,s=e.clone();s.applyMatrix4(i.projectionMatrix);let a=new r(s.x,s.y);return a=a.multiplyScalar(.5),a=a.addVectors(a,new r(.5,.5)),a=a.multiply(n),a.y=n.y-a.y,a}static screenUnProject(e,t){const{camera:i,viewPortSize:n}=t;let s=e.clone();s.y=n.y-s.y,s=s.divide(n),s=s.multiplyScalar(2),s=s.sub(new r(1,1));let o=i.projectionMatrix.clone();return o=o.invert(),new a(s.x,s.y,0).applyMatrix4(o)}static calculateBoxInCameraProjectionSpace(e,t){const i=[new a(e.min.x,e.min.y,e.min.z),new a(e.min.x,e.min.y,e.max.z),new a(e.min.x,e.max.y,e.min.z),new a(e.min.x,e.max.y,e.max.z),new a(e.max.x,e.min.y,e.min.z),new a(e.max.x,e.min.y,e.max.z),new a(e.max.x,e.max.y,e.min.z),new a(e.max.x,e.max.y,e.max.z)],n=t;i.forEach((e=>{e.applyMatrix4(t.matrixWorldInverse),e.applyMatrix4(n.originProjectMatrix)}));const s=new q;return s.setFromPoints(i),s}static calculateAfterProjectionMatrix(e,i=void 0){const n=void 0===i?new Z(new r(-.9,-.9),new r(.9,.9)):i,s=n.getCenter(new r),o=e.getCenter(new a).clone().sub(new a(s.x,s.y,0));o.z=0;const h=e.getSize(new a),d=n.getSize(new r),p=Math.min(d.x/h.x,d.y/h.y),l=(new t).scale(new a(p,p,1));return l.multiply((new t).makeTranslation(-o.x,-o.y,0)),l}static focusCamera(e,t,i=void 0){let n;if((Array.isArray(e)?e:[e]).forEach((e=>{const i=rn.calculateBoxInCameraProjectionSpace(e,t);n=void 0===n?i:n.union(i)})),n){const e=t;e.afterProjectionMatrix=rn.calculateAfterProjectionMatrix(n,i),e.raiseCameraChangeEvent()}}static calculateBoundingBox(e){const t=(e,t)=>{const i=rn.calculateBoundingBox(t);return void 0===e?i:i?.union(e)};if(Array.isArray(e))return e.reduce(t,void 0);if(e.children?.length>0){return e.children.reduce(t,void 0)}const i=e,{geometry:n}=i;return n.boundingBox||n.computeBoundingBox(),i.updateMatrixWorld(!0),n.boundingBox?.clone().applyMatrix4(i.matrixWorld)}}const an={uniforms:{tDiffuse:{value:null},tDepth:{value:null},outlineColor:{value:new g(16776960)},depthOffset:{value:-1e-4}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n uniform sampler2D tDiffuse;\n uniform sampler2D tDepth;\n uniform vec3 outlineColor;\n uniform float depthOffset;\n\n varying vec2 vUv;\n\n void main() {\n\n ivec2 texSize = textureSize(tDiffuse, 0);\n vec2 invSize = vec2(1.0) / vec2(texSize);\n vec4 uvOffset = vec4(1.0,0.0,0.0,1.0) * vec4(invSize, invSize);\n\n vec4 c1 = (texture2D( tDiffuse, vUv + uvOffset.xy));\n vec4 c2 = (texture2D( tDiffuse, vUv - uvOffset.xy));\n vec4 c3 = (texture2D( tDiffuse, vUv + uvOffset.yw));\n vec4 c4 = (texture2D( tDiffuse, vUv - uvOffset.yw));\n\n float diff1 = length((c1 - c2)*0.5);\n float diff2 = length((c3 - c4)*0.5);\n\n float d = length( vec2(diff1, diff2) );\n\n if (d>0.01) {\n gl_FragColor = vec4(outlineColor, 1.0);\n gl_FragColor.a = 1.0;\n vec4 depth1 = texture2D( tDepth, vUv + uvOffset.xy );\n vec4 depth2 = texture2D( tDepth, vUv - uvOffset.xy );\n vec4 depth3 = texture2D( tDepth, vUv + uvOffset.yw );\n vec4 depth4 = texture2D( tDepth, vUv - uvOffset.yw );\n gl_FragDepth = min(min(min(depth1.x, depth2.x), depth3.x), depth4.x) + depthOffset;\n }\n else {\n discard;\n }\n }\n"};class on{obj;outlineRenderTarget;outlineMeshMaterial=new Q({color:16711680,depthTest:!1});outlineQuad;outlineColor=new g(1,0,0);get color(){return this.outlineColor}set color(e){const t=this.outlineQuad?.material;t&&(this.outlineColor=e,t.uniforms.outlineColor.value=e)}constructor(e,t){this.outlineRenderTarget=e,this.outlineQuad=t,this.initOutlineMaterial()}initOutlineMaterial(){if(this.outlineRenderTarget&&this.outlineQuad){const e=x.clone(an.uniforms);e.tDiffuse.value=this.outlineRenderTarget.texture,e.outlineColor.value=this.outlineColor;const t=new w({uniforms:e,vertexShader:an.vertexShader,fragmentShader:an.fragmentShader,blending:M,depthTest:!0,depthWrite:!0,transparent:!1});this.outlineQuad.material=t}}bind(e){this.obj=e,It(e,this.onPreRendering,this.onPostRendering)}unbind(e){Bt(e,this.onPreRendering,this.onPostRendering),this.obj=void 0}onPreRendering=(e,t,i,n,s,r)=>{if(this.outlineRenderTarget){const s={target:null};s.target=e.getRenderTarget(),e.setRenderTarget(this.outlineRenderTarget),e.clear(),e.renderBufferDirect(i,t,n,this.outlineMeshMaterial,this.obj,r),e.setRenderTarget(s.target)}};onPostRendering=e=>{if(this.outlineQuad){const{autoClear:t}=e;e.autoClear=!1,this.outlineQuad.render(e),e.autoClear=t}}}class hn{order;constructor(e){this.order=e}toHitTestResult(e,t){const{object:i}=e;if(i instanceof _t)return{type:"InstancedMesh",object:i,distance:e.distance,pos:e.point.applyMatrix4(t),normal:e.face?.normal,faceIndex:e.faceIndex,face:[e.face?.a,e.face?.b,e.face?.c],axis:e.instanceId}}}var dn;!function(e){e[e.D1=0]="D1",e[e.D2=1]="D2",e[e.D3=2]="D3"}(dn||(dn={}));const pn="#topmost_scene#";class ln{bodies;heads;axis=new T;wrappedEngine;bodiesZoomPreventAction=new Nt;headsZoomPreventAction=new Nt;bodiesScaleRevertAction=new sn;headsScaleRevertAction=new sn;path;wrappedPosition=new a;wrappedQuaternion=new X;originRay={origin:new a,direction:new a};id=Fe();raycasterConverter=new hn(0);wrappedMode=dn.D3;bodyLength;headLength;constructor(e=.3,t=.005,i=.07,n=.01,s=dn.D3,r=[pn,Lt]){this.wrappedMode=s,this.bodyLength=e,this.headLength=i,this.path=r||[pn,Lt],this.axis.name=this.id,this.bodies=new _t(new l(t,t,e,16,1),new c,3),this.bodies.name=`${this.id}#bodies`,this.bodies.frustumCulled=!1,this.heads=new _t(new u(n,i,16,1),new c,3),this.heads.name=`${this.id}#heads`,this.heads.frustumCulled=!1,this.updateInstances(e,i),this.axis.add(this.bodies),this.axis.add(this.heads),this.bodies.beforeRaycast=this.beforeRaycast,this.bodies.afterRaycast=this.afterRaycast,this.heads.beforeRaycast=this.beforeRaycast,this.heads.afterRaycast=this.afterRaycast,this.headsZoomPreventAction.bind(this.heads),this.bodiesZoomPreventAction.bind(this.bodies),this.wrappedEngine&&(this.headsScaleRevertAction.bind(this.heads,this.wrappedEngine),this.bodiesScaleRevertAction.bind(this.bodies,this.wrappedEngine))}updateInstances(e,i){this.heads.setColorAt(0,new g(16711680)),this.bodies.setColorAt(0,new g(16711680)),this.mode>=dn.D2&&(this.heads.setColorAt(1,new g(65280)),this.bodies.setColorAt(1,new g(65280))),this.mode>=dn.D3&&(this.heads.setColorAt(2,new g(255)),this.bodies.setColorAt(2,new g(255)));const n=(new t).makeRotationZ(-Math.PI/2),s=(new t).makeRotationX(Math.PI/2),r=(new t).makeTranslation(0,e/2,0),a=(new t).makeTranslation(0,e+i/2,0);this.bodies.setMatrixAt(0,n.clone().multiply(r)),this.heads.setMatrixAt(0,n.clone().multiply(a)),this.mode>=dn.D2&&(this.bodies.setMatrixAt(1,r),this.heads.setMatrixAt(1,a)),this.mode>=dn.D3&&(this.bodies.setMatrixAt(2,s.clone().multiply(r)),this.heads.setMatrixAt(2,s.clone().multiply(a)))}get mode(){return this.wrappedMode}set mode(e){if(this.wrappedMode!==e){switch(this.wrappedMode=e,this.wrappedMode){case dn.D3:this.heads.count=3,this.bodies.count=3;break;case dn.D2:this.heads.count=2,this.bodies.count=2;break;case dn.D1:this.heads.count=1,this.bodies.count=1;break;default:throw new Error("Unknown axis mode")}this.updateInstances(this.bodyLength,this.headLength)}}get group(){return this.axis}get position(){return this.wrappedPosition}set position(e){this.wrappedPosition=e,this.updatePosition()}get quaternion(){return this.wrappedQuaternion}set quaternion(e){this.wrappedQuaternion=e,this.axis.quaternion.copy(e),this.axis.updateMatrix(),this.wrappedEngine?.invalidate()}get engine(){return this.wrappedEngine}set engine(e){if(this.wrappedEngine!==e&&(this.wrappedEngine&&(this.wrappedEngine.rayCastResultConvertHub.unregister(this.raycasterConverter),this.wrappedEngine.autoScaleFilterEvent.remove(this.autoScaleFilterEventHandler),this.wrappedEngine.scenes.removeObject(this.path[0],...this.path.slice(1),this.axis.name),this.headsScaleRevertAction.unbind(this.heads),this.bodiesScaleRevertAction.unbind(this.bodies)),this.wrappedEngine=e,this.wrappedEngine)){if(!this.wrappedEngine.scenes.getSceneItem(this.path[0])){It(this.wrappedEngine.scenes.addScene(this.path[0]).scene,(e=>{e.clearDepth()}))}this.wrappedEngine.autoScaleFilterEvent.add(this.autoScaleFilterEventHandler),this.wrappedEngine.scenes.addObject(this.path[0],this.axis,...this.path.slice(1)),this.headsScaleRevertAction.bind(this.heads,this.wrappedEngine),this.bodiesScaleRevertAction.bind(this.bodies,this.wrappedEngine),this.engine?.adaptRangeChangedEvent.add(this.updatePosition),this.wrappedEngine.rayCastResultConvertHub.register(this.raycasterConverter)}}isHitTestObject(e){return e===this.heads||e===this.bodies}autoScaleFilterEventHandler=e=>{if(e){if(e.path.length{if(this.engine){const{adaptMatrix:e}=this.engine,t=(new a).applyMatrix4(e),i=this.position.clone().applyMatrix4(e);i.sub(t),this.axis.position.copy(i),this.axis.updateMatrix(),this.engine.invalidate()}};beforeRaycast=(e,t)=>{if(this.engine&&t&&this.axis){const{renderer:i,camera:n}=this.engine,s=this.engine.scenes.getSceneItem(this.path[0])?.scene;if(s&&e.onBeforeRender(i,s,n,e.geometry,Array.isArray(e.material)?e.material[0]:e.material,this.axis),!t.coords)throw Error("use RaycasterEx and setFromCamera method.");this.originRay.origin=t.ray.origin.clone(),this.originRay.direction=t.ray.direction.clone(),t.setFromCamera(t.coords,n)}};afterRaycast=(e,t)=>{if(this.engine&&t&&this.axis){const{renderer:i,camera:n}=this.engine,s=this.engine.scenes.getSceneItem(this.path[0])?.scene;s&&e.onAfterRender(i,s,n,e.geometry,Array.isArray(e.material)?e.material[0]:e.material,this.axis);const r=t;r.ray.origin=this.originRay.origin,r.ray.direction=this.originRay.direction}}}class cn extends o{constructor(){super(),this.setAttribute("position",vt(ct,3)),this.setIndex(xt(mt,1))}}const un=0;class gn{static Seed=1;static newSeed(){return gn.Seed+=1,gn.Seed}}var fn,mn,wn;function vn(e){const t=e;return!(!t.beforeRaycast&&!t.afterRaycast)}!function(e){e[e.NONE=0]="NONE",e[e.HAND=1]="HAND",e[e.ARROW=2]="ARROW",e[e.CROSS=3]="CROSS"}(fn||(fn={})),function(e){e[e.Perspective=0]="Perspective",e[e.Orthographic=1]="Orthographic"}(mn||(mn={})),function(e){e[e.Undefined=-1]="Undefined",e[e.XPositive=0]="XPositive",e[e.YPositive=1]="YPositive",e[e.ZPositive=2]="ZPositive",e[e.XNegative=3]="XNegative",e[e.YNegative=4]="YNegative",e[e.ZNegative=5]="ZNegative",e[e.UserDefined=6]="UserDefined"}(wn||(wn={}));class xn extends o{constructor(e=!1){super(),this.setAttribute("position",yt(wn.Undefined)),this.setAttribute("normal",Mt(wn.Undefined)),e&&this.setAttribute("uv",bt(wn.Undefined))}}class yn extends o{constructor(e){super(),this.setAttribute("position",yt(e)),this.setAttribute("normal",Mt(e))}}class Mn extends ${propertyNameMapping={};data;customPropertiesMap={};async loadAsync(e,t,i){try{const n=t,s=e=>{n&&n(Yi(e))},r=await Qe(e,{responseType:"arraybuffer",onDownloadProgress:s,signal:i?.signal}),a=$e(r.data);if(i?.signal.aborted)throw new Vi;return this.data=a,a}catch(e){throw Qe.isCancel(e)?new Vi:new Error(`unexpected error ${e}`)}}generateGeometry(){const e=new Ke;return e.setPropertyNameMapping(this.propertyNameMapping),e.setCustomPropertyNameMapping(this.customPropertiesMap),e.parse(this.data)}getCustomProperties(){const e=this.parseHeader(),t=[],i=new Set(["x","y","z","px","py","pz","posx","posy","posz","nx","ny","nz","normalx","normaly","normalz","s","t","u","v","tx","ty","texture_u","texture_v","r","g","b","red","green","blue","diffuse_red","diffuse_green","diffuse_blue","diffuse_r","diffuse_g","diffuse_b"]),n=e.elements.find((e=>"vertex"===e.name));return n&&n.properties.forEach((e=>{e.name&&!i.has(e.name)&&t.push(e.name)})),t}static make_ply_element_property(e,t){const i={type:e[0]};return"list"===i.type?[,i.countType,i.itemType,i.name]=e:[,i.name]=e,i.name in t&&(i.name=t[i.name]),i}parseHeader(){if(!this.data)throw Error("data not load.");let e="",t=0;const i=/^ply([\s\S]*)end_header(\r\n|\r|\n)/.exec(J.decodeText(new Uint8Array(this.data)));null!==i&&([,e]=i,t=new Blob([i[0]]).size);const n={comments:[],elements:[],headerLength:t,objInfo:"",format:"",version:""},s=e.split(/\r\n|\r|\n/);let r;for(let e=0;e{n&&n(Yi(e))},r=await Qe(e,{responseType:"arraybuffer",onDownloadProgress:s,signal:i?.signal}),a=$e(r.data);if(i?.signal.aborted)throw new Vi;return(new Ye).parse(a)}catch(e){throw Qe.isCancel(e)?new Vi:new Error(`unexpected error ${e}`)}}}class En extends ${load(e,t){return new Promise(((i,n)=>{const s=new ee,r=new te(this.manager);r.setCrossOrigin(this.crossOrigin),r.setPath(this.path),r.load(e,(e=>{s.image=Je(e),s.format=E,s.needsUpdate=!0,i(s)}),t,(e=>{n(e)}))}))}}class Sn{isEnabled;priority;constructor(e=10,t=!0){this.priority=e,this.isEnabled=t}handleLeftButtonDown(e,t){return!1}handleLeftButtonUp(e,t){return!1}handleMouseMove(e,t){return!1}handleMouseWheel(e,t){return!1}handleKeyDown(e,t){return!1}handleKeyUp(e,t){return!1}handleMiddleButtonDown(e,t){return!1}handleMiddleButtonUp(e,t){return!1}handleRightButtonDown(e,t){return!1}handleRightButtonUp(e,t){return!1}handleWheel(e,t){return!1}}const Tn=gn.newSeed();class Cn extends Sn{previousPosition=new r;wrappedHoverOnDir=wn.Undefined;scene=new A;root=new T;detectBoxMesh;range=[1,1,1,0,0,0];hoverOnDirChangedEvent=new ht;edgePositionChangedEvent=new ht;constructor(){super(5),this.scene.add(this.root);const e=new xn,t=new Array(108);for(let e=0;e<6;e+=1)for(let i=0;i<6;i+=1){const n=3*(6*e+i);t[n]=e+1,t[n+1]=0,t[n+2]=0}e.setAttribute("color",new n(t,3)),this.detectBoxMesh=new S(e,new Q({vertexColors:!0})),this.root.add(this.detectBoxMesh)}get activeDir(){return this.wrappedHoverOnDir}handleLeftButtonDown(e,t){if(this.isEnabled){if(0===t.state)return this.wrappedHoverOnDir!==wn.Undefined&&(this.previousPosition=new r(e.offsetX,e.offsetY),!0)}return!1}handleLeftButtonUp(e,t){if(this.isEnabled){const e=t;if(e.state===Tn)return e.state=0,e.releasePointer(),e.cursorType=fn.NONE,this.wrappedHoverOnDir=wn.Undefined,this.edgePositionChangedEvent.trigger({draggingDone:!0}),!0}return!1}handleMouseMove(e,t){if(this.isEnabled){const i=t,n=new r(e.offsetX,e.offsetY);if(0===i.state){const t=this.TestReaction(e.offsetX,e.offsetY,i);if(this.wrappedHoverOnDir!==t&&(this.wrappedHoverOnDir=t,this.hoverOnDirChangedEvent.trigger({dir:t})),1!==e.buttons||this.wrappedHoverOnDir===wn.Undefined)return!1;i.capturePointer(e.pointerId),i.state=Tn,i.cursorType=fn.HAND}if(i.state===Tn){const e=n.clone().sub(this.previousPosition);return this.dragBoxSurface(e,t),this.previousPosition=n,!0}}return!1}TestReaction(e,i,n){const{range:s}=this,r=n,o=new t;o.scale(new a(s[0]-s[3],s[1]-s[4],s[2]-s[5])),o.setPosition(new a(s[3],s[4],s[5])),this.detectBoxMesh.matrix=o,this.detectBoxMesh.matrixAutoUpdate=!1,this.root.matrix=r.matrix,this.root.matrixAutoUpdate=!1;const h=r.renderTargetAndReadFloat(this.scene,e,i,1,1,void 0,void 0,void 0);return Math.round(h[0])-1}dragBoxSurface(e,t){const i=t,n=new a(e.x,e.y,0),s=i.camera;n.applyMatrix4(s.afterProjectionMatrix.clone().invert());const r=[new ie(1,0,0,1),new ie(0,1,0,1),new ie(0,0,1,1),new ie(-1,0,0,1),new ie(0,-1,0,1),new ie(0,0,-1,1)][this.wrappedHoverOnDir].clone(),o=i.viewPortSize,h=i.rotationMatrix.extractRotation(i.matrix);r.applyMatrix4(h);const d=new a(n.x,-n.y,0),p=new a(r.x,r.y,r.z),l=d.clone().dot(p);let c=0;const u=o.width/o.height>1?o.height/2:o.width/2;if(i.camera instanceof lt){const e=Math.tan(i.camera.fov/180*Math.PI/2)*(0-i.camera.position.z)/u;c=1===r.z?0:l*e/(1-r.z*r.z)/(2/i.maxDim)}else{if(!(i.camera instanceof pt))throw Error("not implemented.");{const e=-1.732/u;c=1===r.z?0:l*e/(1-r.z*r.z)/(2/i.maxDim)}}0!==c&&this.drag(c)}drag(e){if(void 0!==this.wrappedHoverOnDir&&this.wrappedHoverOnDir>wn.Undefined&&this.wrappedHoverOnDire.name===Rn));if(t>=0){this.boxBoundary.children[t].material.color=e}}setActivePlaneVisibility(e){const t=this.boxBoundary.children.findIndex((e=>e.name===Rn));if(t>=0){this.boxBoundary.children[t].visible=e}}updateActivePlane(e,t){const i=this.boxBoundary.children.findIndex((e=>e.name===Rn));if(i>=0){const n=this.boxBoundary.children[i];if(this.boxBoundary.children.splice(i,1),nn(n),this.boxBoundary.matrixAutoUpdate=!1,this.update(t),-1===e)return}e>=0&&(this.generateActivePlane(e),this.update(t))}}const Pn="#clipping-universal#",On="#clipping_trait#";class Ln{order=0;traits=[];createPositionDetectMaterial(){}createDetectMesh(e,t,i){const n=i;if(!n.beforeRenderStack)return;const s=n.beforeRenderStack.findTrait(i);if(!s||s.type!==On)return;this.traits.push(s),s.forceRenderClippingPlanes=!0,s.hideOutline=!0;const r=new S(e,t);return r.name=i.name,r.matrix=i.matrix,r.matrixAutoUpdate=!1,r.renderOrder=i.renderOrder,r.onBeforeRender=i.onBeforeRender,r.onAfterRender=i.onAfterRender,r.visible=i.visible,r}restore(){this.traits.forEach((e=>{e.forceRenderClippingPlanes=!1,e.hideOutline=!1})),this.traits=[]}}class Dn{factories=[];register(e){this.factories.push(e),this.factories.sort(((e,t)=>t.priority-e.priority))}unregister(e){const t=this.factories.indexOf(e);if(t<0)throw Error("No such factory.");this.factories.splice(t,1)}detectFactory(...e){const t=this.factories.values();let i=t.next();for(;!i.done;){if(i.value.detect(...e))return i.value;i=t.next()}}}var zn,In;!function(e){e[e.ResultMaterial=0]="ResultMaterial",e[e.ResultMesh=1]="ResultMesh",e[e.ResultNone=2]="ResultNone"}(zn||(zn={})),function(e){e[e.NothingReplaced=0]="NothingReplaced",e[e.MaterialReplaced=1]="MaterialReplaced",e[e.MeshReplaced=2]="MeshReplaced"}(In||(In={}));class Bn extends o{wrappedDir;constructor(e,t){super(),this.wrappedDir=e,t&&this.update(t)}get dir(){return this.wrappedDir}update(e,i){const s=[[e.min.x,e.max.x],[e.min.y,e.max.y],[e.min.z,e.max.z]];if(void 0!==i){const e=Math.floor(this.wrappedDir/3),t=this.wrappedDir%3;if(s[t][e?0:1]===i)return;s[t][e?0:1]=i}const r=(new t).scale(new a(s[0][1]-s[0][0],s[1][1]-s[1][0],s[2][1]-s[2][0])).setPosition(s[0][0],s[1][0],s[2][0]),o=[...gt[2*this.wrappedDir],...gt[2*this.wrappedDir+1]],h=new Array(3*o.length);for(let e=0;et===this.map.get(e)))}set(e,t){this.remove(e),this.map.set(e,t),this.array.push(t)}remove(e){const t=this.map.get(e);if(t){this.map.delete(e);const i=this.array.findIndex((e=>e===t));if(i>=0)return this.array.splice(i,1),this.map.delete(e),!0}return!1}get(e){return this.map.get(e)}has(e){return this.map.has(e)}clear(){this.map.clear(),this.array.splice(0,this.array.length)}keys(){return this.map.keys()}}const Nn={uniforms:{tDiffuse:{value:null},tDepth:{value:null},opacity:{value:1}},vertexShader:"\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n\t\t\tvUv = uv;\n\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t}",fragmentShader:"\n\n uniform float opacity;\n\t\tuniform sampler2D tDiffuse;\n uniform sampler2D tDepth;\n\n\t\tvarying vec2 vUv;\n\n\t\tvoid main() {\n\n vec4 depth = texture2D( tDepth, vUv );\n if(depth.x >= 1.0){\n discard;\n }\n else \n {\n gl_FragDepth = depth.x;\n gl_FragColor = texture2D( tDiffuse, vUv );\n gl_FragColor.a *= opacity; \n }\n\t\t}"},Un="#clipping-root#",Gn=500;class Hn{wrappedClipPositions=[0,0,0,0,0,0];static clipPositionMapRatio=[1,1,1,-1,-1,-1];clipped=[!1,!1,!1,!1,!1,!1];wrappedClippingRange;clipGroup=new T;universalClipGroup;wrappedLimitBox=[];minimalFragment=0;wrappedAutoMinimalFragmentRatio=.01;wrappedUserDefinedMinimalFragment;transformedPlanes=new Fn;planeGeometries=new Map;wrappedEngine;scenes;outlineRenderTarget;boundaryHelper=new An;clippingActionHandler=new Cn;meshGroups=new Map;fsQuad;outlineQuad;outlineMaterial;wrappedShowClippingEdge=!1;wrappedUseUniversalSealingSurface=!1;updateDebouncers=new Fn;universalClipDebouncers=new Fn;sealingSurfaceFactoryHub=new Dn;clippingChangedEvent=new ht;wrappedOutlineColor=new g(1,1,0);bindChangedEvent=new ht;constructor(){for(let e=0;e<6;e+=1)this.planeGeometries.set(e,new Bn(e,this.wrappedClippingRange));this.clipGroup.name=Un,this.clippingActionHandler.hoverOnDirChangedEvent.add(this.onHoverOnDirChanged),this.clippingActionHandler.edgePositionChangedEvent.add(this.onClippingChanged)}onHoverOnDirChanged=e=>{e&&this.boundaryHelper.updateActivePlane(e.dir,this.wrappedClipPositions)};onClippingChanged=e=>{e&&(e.draggingDone?this.clippingChangedEvent.trigger({dragging:!1}):void 0!==e.dir&&e.newPosition&&this.updateClip(e.dir,e.newPosition))};getSurfacePositionFromMouseEvent(e){if(this.engine){const i=this.engine.viewPortSize,{camera:n}=this.engine,s=new r(e.x/i.x*2-1,-e.y/i.y*2+1),{activeDir:o}=this.clippingActionHandler;if(o>=0&&this.clipped[o]){const e=this.transformedPlanes.get(o);if(e){const i=this.engine.matrix,r=(new t).copy(i).invert(),o=new W;o.setFromCamera(s,n);const h=new a,d=o.ray.intersectPlane(e,h);if(d){return d.clone().applyMatrix4(r)}}}}}get engine(){return this.wrappedEngine}get autoMinimalFragmentRatio(){return this.wrappedAutoMinimalFragmentRatio}set autoMinimalFragmentRatio(e){e!==this.wrappedAutoMinimalFragmentRatio&&(this.wrappedAutoMinimalFragmentRatio=e,this.wrappedEngine&&this.updateClippingRange(this.wrappedEngine.adaptRange))}get userDefinedMinimalFragment(){return this.wrappedUserDefinedMinimalFragment}set userDefinedMinimalFragment(e){e!==this.wrappedUserDefinedMinimalFragment&&(this.wrappedUserDefinedMinimalFragment=e,this.wrappedEngine&&this.updateClippingRange(this.wrappedEngine.adaptRange))}get useUniversalSealingSurface(){return this.wrappedUseUniversalSealingSurface}set useUniversalSealingSurface(e){this.wrappedUseUniversalSealingSurface!==e&&(this.wrappedUseUniversalSealingSurface=e,this.wrappedUseUniversalSealingSurface?this.applyUniversalClip():this.unApplyUniversalClip())}get clipPositions(){return this.wrappedClipPositions}set clipPositions(e){if(!Zi(this.wrappedClipPositions,e)){for(let t=0;t<3;t+=1)if(e[t]{e.hasObject(t,Lt,Un,t)&&e.removeObject(t,Lt,Un,t);const i=e.findGroup(t,Lt,Dt);Ai.forEach(i,!0,((e,...i)=>(this.applyClip(t,Lt,Dt,...i),!0)))}))}unApplyClipToAllObjects(){const{scenes:e}=this;e&&e.forEachScene((t=>{const i=e.findGroup(t,Lt,Dt);Ai.forEach(i,!0,((e,...i)=>(_i(e)&&this.unApplyClip(t,Lt,Dt,...i),!0)))}))}initOutlineResources(){if(this.wrappedEngine){this.outlineMaterial=new Q({color:16711680,stencilWrite:!0,stencilRef:0,stencilFunc:ae,stencilFail:oe,stencilZFail:oe,stencilZPass:oe}),this.outlineRenderTarget=new P(this.wrappedEngine.width,this.wrappedEngine.height,{type:O,depthBuffer:!0,stencilBuffer:!0}),this.outlineRenderTarget.depthTexture=new he(this.outlineRenderTarget.width,this.outlineRenderTarget.height),this.outlineRenderTarget.depthTexture.format=de,this.outlineRenderTarget.depthTexture.type=pe;const e=x.clone(Nn.uniforms);e.tDiffuse.value=this.outlineRenderTarget.texture,e.opacity.value=1,e.tDepth.value=this.outlineRenderTarget.depthTexture;const t=new w({uniforms:e,vertexShader:Nn.vertexShader,fragmentShader:Nn.fragmentShader,blending:M,depthTest:!0,depthWrite:!0,transparent:!1});this.fsQuad=new He(t);const i=x.clone(an.uniforms);i.tDepth.value=this.outlineRenderTarget.depthTexture,i.tDiffuse.value=this.outlineRenderTarget.texture,i.outlineColor.value=this.outlineColor;const n=new w({uniforms:i,vertexShader:an.vertexShader,fragmentShader:an.fragmentShader,blending:M,depthTest:!0,depthWrite:!0,transparent:!1});this.outlineQuad=new He(n)}}clearOutlineResources(){this.outlineMaterial=void 0,this.outlineRenderTarget=void 0,this.outlineQuad=void 0}updateSealingSurfaceVisible(e){Ai.forEach(this.clipGroup,!1,(t=>{const i=void 0===e?it(0,6):e,n=t;return i.forEach((e=>{n.name===e.toString()&&(n.visible=this.clipped[e])})),!0}))}bindEvents(){this.wrappedEngine&&(this.wrappedEngine.domainRangeChangedEvent.add(this.updateDomainRange),this.wrappedEngine.rotationChangedEvent.add(this.applyTransform),this.wrappedEngine.autoScaleFilterEvent.add(Hn.filterHandler),this.wrappedEngine.animationEvent.add(this.onAnimation),this.wrappedEngine.sizeChangedEvent.add(this.onSizeChanged)),this.scenes&&(this.scenes.objectAdded.add(this.onObjectAdd),this.scenes.objectRemoving.add(this.onObjectRemoving))}unbindEvents(){this.wrappedEngine&&(this.wrappedEngine.domainRangeChangedEvent.remove(this.updateDomainRange),this.wrappedEngine.rotationChangedEvent.remove(this.applyTransform),this.wrappedEngine.autoScaleFilterEvent.remove(Hn.filterHandler),this.wrappedEngine.animationEvent.remove(this.onAnimation),this.wrappedEngine.sizeChangedEvent.remove(this.onSizeChanged)),this.scenes&&(this.scenes.objectAdded.remove(this.onObjectAdd),this.scenes.objectRemoving.remove(this.onObjectRemoving))}onObjectAdd=e=>{if(!this.scenes)throw Error("not bind.");e&&_i(e.object)&&e.paths[0]===Lt&&e.paths[1]===Dt&&this.applyClip(e.sceneKey,...e.paths)};onObjectRemoving=e=>{if(!this.scenes)throw Error("not bind.");e&&_i(e.object)&&this.unApplyClip(e.sceneKey,...e.paths)};updateDomainRange=e=>{if(this.wrappedEngine&&(this.updateClippingRange(e),this.wrappedClippingRange)){const e=[this.wrappedClippingRange.max.x,this.wrappedClippingRange.max.y,this.wrappedClippingRange.max.z,this.wrappedClippingRange.min.x,this.wrappedClippingRange.min.y,this.wrappedClippingRange.min.z];for(let t=0;t<6;t+=1)this.planeGeometries.get(t).update(this.wrappedClippingRange,this.clipped[t]?this.clipPositions[t]:e[t])}};onSizeChanged=e=>{e&&this.outlineRenderTarget&&this.outlineRenderTarget.setSize(e.width,e.height)};onAnimation=()=>{if(this.wrappedEngine&&this.wrappedEngine.renderer&&this.outlineRenderTarget){const e=this.wrappedEngine.renderer.getRenderTarget();this.wrappedEngine.renderer.setRenderTarget(this.outlineRenderTarget),this.wrappedEngine.renderer.clear(),this.wrappedEngine.renderer.setRenderTarget(e)}};setVisible(e,t){const i=this.clipGroup.children.find((t=>t.name===e));i&&(i.visible=t)}set enableAction(e){this.clippingActionHandler.isEnabled=e,this.boundaryHelper.visible=e}get enableAction(){return this.clippingActionHandler.isEnabled}updateClip(e,t){const i=new Set;if(e<=wn.ZPositive){if(t===this.wrappedClipPositions[e])return;i.add(e);const n=e+3;if(t>this.limitBox[e])this.wrappedClipPositions[e]=this.limitBox[e];else if(tthis.wrappedClipPositions[n]-this.minimalFragment){let s=t+this.minimalFragment,r=t;s>this.limitBox[n]&&(s=this.limitBox[n],r=this.limitBox[n]-this.minimalFragment),this.wrappedClipPositions[n]=s,this.wrappedClipPositions[e]=r,i.add(n)}else this.wrappedClipPositions[e]=t}this.updateClipPosition(i,e)}updateClipPosition(e,t){for(let e=0;e<6;e+=1)this.clipped[e]=e<=2?this.wrappedClipPositions[e]this.limitBox[e];this.updateSealingSurfacePosition(e),this.updateUniversalSealingSurfacePosition(e),this.wrappedEngine&&this.updatePlaneTransformMatrix(this.wrappedEngine.matrix),this.boundaryHelper.update(this.wrappedClipPositions),this.clippingActionHandler.range=this.wrappedClipPositions,this.updateSealingSurfaceVisible(Array.from(e));const i=new Map;e.forEach((e=>{i.set(e,this.wrappedClipPositions[e])})),this.clippingChangedEvent.trigger({newPositions:i,draggingDir:t,dragging:void 0!==t}),this.wrappedEngine?.invalidate()}applyClip(e,...t){if(!this.scenes)return;const i=this.sealingSurfaceFactoryHub.detectFactory(e,...t);if(!i||!i.allowClip(e,...t))return;const n=this.scenes.getObject(e,...t);if(n){if(_i(n)){const s=n;this.clipObject(s),i&&this.createSealingSurfacesGroup(i,s,e,...t)}this.wrappedEngine?.invalidate()}}applyUniversalClip(){if(!this.wrappedUseUniversalSealingSurface)return;if(!this.scenes)return;const e=this.sealingSurfaceFactoryHub.detectFactory();if(!e)return;const t=new T;t.name=Pn;for(let i=0;i{this.wrappedEngine&&(Array.isArray(e)?e.forEach((e=>{n.add(e)})):e instanceof me?n.add(new S(this.planeGeometries.get(i),e)):n.add(e))};if(e.isAsyncCreate()){let t=this.universalClipDebouncers.get(i);t||(t=new Ki,this.updateDebouncers.set(i,t)),t.debounce((async()=>{const t=await e.getSurfaceMeshAsync(void 0,this,i);s(t)}),Gn)}else{const t=e.getSurfaceMesh(void 0,this,i);s(t)}}this.clipGroup.add(t),this.universalClipGroup=t}unApplyUniversalClip(){this.scenes?.removeObject(Ot,Lt,Un,Pn)}unApplyClip=(e,...t)=>{if(this.scenes){const{scenes:i}=this;Oi(this.meshGroups.entries(),(([n,s])=>{const r=s.groupItems.findIndex((e=>Zi(e.paths,t)));r>=0&&s.groupItems.splice(r,1),0===s.groupItems.length&&(this.meshGroups.delete(n),i.removeObject(Ot,Lt,Un,e,...t.slice(2,-1),n))})),0===this.meshGroups.size&&i.hasObject(Ot,Lt,Un,e,...t.slice(2))&&i.removeObject(Ot,Lt,Un,e,...t.slice(2)),this.wrappedEngine?.invalidate()}};clipObject(e){const{material:t}=e;if(t instanceof Array){t.forEach((e=>{e.clippingPlanes=this.transformedPlanes.array}))}else t.clippingPlanes=this.transformedPlanes.array}updateClippingRange(e){if(void 0!==e){const t=e.clone();if(void 0===this.wrappedUserDefinedMinimalFragment){const e=new a;t.getSize(e);const i=Math.max(e.x,Math.max(e.y,e.z));this.minimalFragment=i*this.wrappedAutoMinimalFragmentRatio}else this.minimalFragment=this.wrappedUserDefinedMinimalFragment;0!==this.minimalFragment&&t.expandByScalar(2*this.minimalFragment),this.wrappedLimitBox=[t.max.x,t.max.y,t.max.z,t.min.x,t.min.y,t.min.z];for(let e=0;e{this.wrappedEngine&&this.updatePlaneTransformMatrix(this.wrappedEngine.matrix)};updatePlaneTransformMatrix(e){if(this.wrappedClipPositions)for(let t=0;t{if(this.wrappedEngine){const i=this.createSealingSurface(s,r,h,t,e);a.set(h,[i[1],i[2]]);const n=i[0];n.name=t.name,d.add(n)}};if(e.isAsyncCreate(i,...o)){let n=this.updateDebouncers.get(h);n||(n=new Ki,this.updateDebouncers.set(h,n)),n.debounce((async()=>{const n=await e.getSurfaceMeshAsync(t,this,h,i,...o);p(n)}),Gn)}else{const n=e.getSurfaceMesh(t,this,h,i,...o);p(n)}n.add(d)}}createSealingSurface(e,t,i,n,s){let r;if(e!==zn.ResultMesh){const e=s||new Q({color:16711680}),t=this.planeGeometries.get(i);r=new S(t,e),r.frustumCulled=!1}else r=s;this.ApplyStencilMask(r,i);const[a,o]=Hn.createStencilMeshes(n,this.transformedPlanes.get(i));return[this.setOutlineRendering(t,n,[a,o],e,r,i),a,o]}setOutlineRendering(e,t,i,n,s,r){const a={target:null},o=Array.isArray(s)?s[0]:s;return It(o,((n,o,h,d,p,l,c)=>{const u=c;if(n){!this.outlineRenderTarget||u&&u.hideOutline||(a.target=n.getRenderTarget(),n.setRenderTarget(this.outlineRenderTarget),n.clear());const d=[];e?e.groupItems.forEach((e=>{d.push({targetMesh:e.targetMesh,meshes:e.stencilMeshes.get(r)})})):d.push({targetMesh:t,meshes:i}),d.forEach((e=>{const{meshes:i}=e;i.forEach((e=>{const i=e;i.matrixWorld=t.matrixWorld,i.modelViewMatrix.multiplyMatrices(h.matrixWorldInverse,t.matrixWorld),i.normalMatrix.getNormalMatrix(s.modelViewMatrix),n.renderBufferDirect(h,o,i.geometry,i.material,i,null)}))}))}}),((e,t,i,r,o,h,d)=>{const p=d;if(s&&Array.isArray(s)&&s.length>1)for(let n=1;n{const i=e.material;i.clippingPlanes=this.transformedPlanes.array.filter(((e,i)=>i!==this.transformedPlanes.indexOf(t))),i.stencilWrite=!0,i.stencilRef=0,i.stencilFunc=ae,i.stencilFail=oe,i.stencilZFail=oe,i.stencilZPass=oe}))}updateSealingSurface(e,t,i,n,s,r,a){if(!this.wrappedEngine)return;if(e.sealingSurfaceCreateMethod(n,t,...i)===zn.ResultNone)return;let o;if(s){const{groupId:e}=s;if(r.has(e))return;const t=this.meshGroups.get(e);t&&(o=t.clippingGroup),r.add(e)}else o=Ai.findOffspring(this.clipGroup,t,...i.slice(2));if(!o)throw Error("target group not found");const h=e.isAsyncUpdate(t,...i);a.forEach((s=>{const r=Ai.findOffspring(o,s.toString());if(r)if(h){let a=this.updateDebouncers.get(s);a||(a=new Ki,this.updateDebouncers.set(s,a)),a.debounce((async()=>{const a=r.children[0],o=await e.updateMeshAsync(n,this,r,s,t,...i);this.applyMeshUpdateResult(o,r,s,a)}),Gn)}else{const a=r.children[0],o=e.updateMesh(n,this,r,s,t,...i);this.applyMeshUpdateResult(o,r,s,a)}}))}applyMeshUpdateResult(e,t,i,n){if(e!==In.NothingReplaced){const s=t.children[0];this.ApplyStencilMask(s,i),e===In.MeshReplaced&&Ft(n,s)}}updateSealingSurfacePosition(e){if(this.wrappedEngine&&this.wrappedClippingRange){const t=this.wrappedClippingRange;e.forEach((e=>{"number"==typeof e&&this.planeGeometries.get(e).update(t,this.clipPositions[e])}));const i=new Set;this.enumAllTarget(((t,n,...s)=>{if(s.length<2||s[1]!==Dt)return;const r=this.sealingSurfaceFactoryHub.detectFactory(n,...s);if(r){if(!r.updateRequired(n,...s))return;const a=r.mapGroup(n,...s);this.updateSealingSurface(r,n,s,t,a,i,e)}}))}}updateUniversalSealingSurfacePosition(e){if(this.useUniversalSealingSurface){const t=this.sealingSurfaceFactoryHub.detectFactory();if(t&&t.updateRequired()){const i=t.isAsyncUpdate();e.forEach((e=>{if(i){let i=this.updateDebouncers.get(e);i||(i=new Ki,this.updateDebouncers.set(e,i)),i.debounce((async()=>{await t.updateMeshAsync(void 0,this,void 0,e)}),Gn)}else t.updateMesh(void 0,this,void 0,e)}))}}}enumAllTarget(e){this.scenes&&this.wrappedClippingRange&&this.scenes.forEachScene(((t,i)=>{Ai.forEach(i,!0,((i,...n)=>(_i(i)&&e(i,t,...n),!0)))}))}static createStencilMeshes(e,t){const{geometry:i,matrix:n}=e,s=new Q;s.depthWrite=!1,s.depthTest=!1,s.colorWrite=!1,s.stencilWrite=!0,s.stencilFunc=le;const r=s.clone();r.side=ce,r.clippingPlanes=[t],r.stencilFail=ue,r.stencilZFail=ue,r.stencilZPass=ue;const a=new S(i,r);a.matrix=n,a.matrixAutoUpdate=!1,a.matrixWorldAutoUpdate=!1;const o=s.clone();o.side=ge,o.clippingPlanes=[t],o.stencilFail=fe,o.stencilZFail=fe,o.stencilZPass=fe;const h=new S(i,o);return h.matrix=n,h.matrixAutoUpdate=!1,h.matrixWorldAutoUpdate=!1,[a,h]}clear(){this.wrappedClipPositions=[0,0,0,0,0,0],this.clipped=[!1,!1,!1,!1,!1,!1],this.updateSealingSurfaceVisible()}static filterHandler(e){if(e&&e.path[2]===Un&&e.path[0]===Ot&&e.path[1]===Lt){e.filtered=!0}}}const kn={opacity:.3,color:8355711,lineDefaultColor:new g(11184810),lineHighlightColor:new g(11141120)};function jn(...e){const t=new o,i=new n([-1,-1,0,1,-1,0,1,1,0,-1,-1,0,1,1,0,-1,1,0],3),s=new n([0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1],3);return t.setAttribute("position",i),t.setAttribute("normal",s),e&&e.forEach((e=>{const i=new n(e.customValues,e.elementNumber);t.setAttribute(e.customValueName,i)})),t}function Vn(){const e=new o,t=new n([-1,-1,0,1,-1,0,1,1,0,-1,1,0,-1,-1,0],3);return e.setAttribute("position",t),e}function Wn(e,i,n,s){const r=i/2,o=n.clone().normalize(),h=o.clone().multiplyScalar(s),d=e,p=o.clone().multiplyScalar(d.clone().dot(o.clone())),l=d.clone().sub(p);h.add(l);const c=new a(0,0,1),u=c.clone().cross(n).normalize(),g=Math.acos(c.dot(n.normalize())),f=(new t).makeRotationAxis(u,g);return(new t).makeTranslation(h.x,h.y,h.z).multiply(f.multiply((new t).makeScale(r,r,r)))}function Kn(e,i,n){const s=n,{camera:r,rotationCenter:o,viewPortSize:h}=s,d=h.x/h.y>1?h.y/2:h.x/2,p=Math.PI*e/d,l=Math.PI*i/d;if(o instanceof we){const e=p,i=o.origin.clone();i.applyMatrix4(s.matrix);const n=o.direction.clone().applyMatrix4((new t).extractRotation(s.rotationMatrix));let r=(new t).makeRotationAxis(n,e);return r=r.multiply((new t).makeTranslation(-i.x,-i.y,-i.z)),r=(new t).makeTranslation(i.x,i.y,i.z).multiply(r),r}let c=new t;if(0!==p||0!==l){if(0!==p){const e=new t;e.makeRotationAxis(r.up,p),c.multiply(e)}if(0!==l){const e=new a,i=new t;r.getWorldDirection(e);const n=e.cross(r.up);i.makeRotationAxis(n,l),c.multiply(i)}}if(o){const e=o.clone();e.applyMatrix4(s.matrix),c=c.multiply((new t).makeTranslation(-e.x,-e.y,-e.z)),c=(new t).makeTranslation(e.x,e.y,e.z).multiply(c)}return c}function Yn(e,t,i,n){const s=i,r=new a(e.x,e.y,0),o=s.camera;r.applyMatrix4(o.afterProjectionMatrix.clone().invert());const h=t.clone(),d=s.viewPortSize,p=s.rotationMatrix.clone();p.elements[12]=0,p.elements[13]=0,p.elements[14]=0,p.elements[15]=1,h.applyMatrix4(p);const l=new a(r.x,-r.y,0),c=new a(h.x,h.y,h.z),u=l.clone().dot(c);let g=0;const f=d.width/d.height>1?d.height/2:d.width/2;if(s.camera instanceof lt){const e=Math.tan(s.camera.fov/180*Math.PI/2)*(0-s.camera.position.z)/f;g=1===h.z?0:u*e/(1-h.z*h.z)/(2/s.maxDim)}else{if(!(s.camera instanceof pt))throw Error("not implemented.");{const e=-(n||1)/f;g=1===h.z?0:u*e/(1-h.z*h.z)/(2/s.maxDim)}}return g}const Xn=gn.newSeed(),qn=gn.newSeed();class Zn extends Sn{previousPosition=new r;wrappedFocusedSection;engine;scene=new A;root=new T;clipperMesh=new Map;idMap=new Map;source;seed=1;focusedSectionChangedEvent=new ht;sectionChangedEvent=new ht;constructor(e){super(5),this.source=e,this.source.sectionsUpdated.add(this.onSectionsChanged),this.root.name="section-hit-test",this.scene.add(this.root),e.sections.forEach((e=>{this.addNewSection(e)}))}get focusedSection(){return this.wrappedFocusedSection}set focusedSection(e){this.wrappedFocusedSection!==e&&(this.wrappedFocusedSection=e,this.focusedSectionChangedEvent.trigger({focusKey:this.wrappedFocusedSection}))}bind(e){this.engine&&this.engine.removeActionHandler(this),this.engine=e,this.engine&&(this.engine.addActionHandler(this),this.source.sections.forEach((e=>{this.updateSection(e)})))}addNewSection(e){const t=new S(jn(),new ai({detectMode:ri.DETECT_BY_STATIC_VALUE,value:this.seed,side:K}));this.idMap.set(this.seed,e.id),this.root.add(t),this.clipperMesh.set(e.id,t),this.seed+=1,t.matrix=this.calculateTransformMatrix(e),t.matrixAutoUpdate=!1,t.name=Fe().toString()}removeSection(e){const t=this.clipperMesh.get(e.id);t&&(this.clipperMesh.delete(e.id),this.root.remove(t))}updateSection(e){const t=this.clipperMesh.get(e.id);t&&(t.matrix=this.calculateTransformMatrix(e))}setVisible(e,t){const i=this.clipperMesh.get(e);i&&(i.visible=t)}calculateTransformMatrix(e){let t=2,i=new a(0,0,0);this.engine&&this.engine.domainRange&&(t=this.engine.domainRange.getSize(new a).length(),i=this.engine.domainRange.getCenter(new a));return Wn(i,t,e.dir,e.shift)}onSectionsChanged=e=>{e&&(e.remove&&e.remove.forEach((e=>{this.removeSection(e)})),e.add&&e.add.forEach((e=>{this.addNewSection(e)})),e.updated&&e.updated.forEach((e=>{this.updateSection(e)})))};handleLeftButtonDown(e,t){if(this.isEnabled){if(0===t.state&&void 0!==this.focusedSection)return this.previousPosition=new r(e.offsetX,e.offsetY),!0}return!1}handleLeftButtonUp(e,t){if(this.isEnabled){const e=t;if(e.state===Xn)return e.state=0,e.releasePointer(),e.cursorType=fn.NONE,!0}return!1}handleRightButtonDown(e,t){if(this.isEnabled){if(0===t.state&&void 0!==this.focusedSection){const t=this.source.sections.find((e=>e.id===this.focusedSection));if(void 0!==t&&t.allowRotate)return this.previousPosition=new r(e.offsetX,e.offsetY),!0}}return!1}handleRightButtonUp(e,t){if(this.isEnabled){const e=t;if(e.state===qn)return e.state=0,e.releasePointer(),e.cursorType=fn.NONE,!0}return!1}handleMouseMove(e,t){if(this.isEnabled){const i=t,n=new r(e.offsetX,e.offsetY);if(0===i.state){const t=this.testReaction(e.offsetX,e.offsetY,i);if(this.focusedSection=this.idMap.get(t),void 0===this.focusedSection)return!1;if(1===e.buttons)i.capturePointer(e.pointerId),i.state=Xn,i.cursorType=fn.HAND;else if(2===e.buttons){const t=this.source.sections.find((e=>e.id===this.focusedSection));t&&t.allowRotate&&(i.capturePointer(e.pointerId),i.state=qn,i.cursorType=fn.CROSS)}}if(i.state===Xn){const e=n.clone().sub(this.previousPosition),t=this.source.sections.find((e=>e.id===this.focusedSection));if(t){const n=Yn(e,t.dir,i);t.shift-=n,this.sectionChangedEvent.trigger({updated:t})}return this.previousPosition=n,!0}if(i.state===qn&&void 0!==i.adaptRange){const e=n.clone().sub(this.previousPosition);if(0===e.x&&0===e.y)return!0;const t=this.source.sections.find((e=>e.id===this.focusedSection));if(t){const n=Kn(e.x,e.y,i),s=i.adaptRange.getCenter(new a),r=t.dir.clone(),o=r.clone().applyMatrix4(n),h=r.clone().multiplyScalar(t.shift-s.dot(r.clone()));h.applyMatrix4(n);const d=s.clone().dot(o)+h.clone().dot(o);t.dir=o,t.shift=d,this.sectionChangedEvent.trigger({updated:t})}return this.previousPosition=n,!0}}return!1}testReaction(e,t,i){const n=i;this.root.matrix=n.matrix,this.root.matrixAutoUpdate=!1;const s=n.renderTargetAndReadFloat(this.scene,e,t,1,1,void 0,void 0,void 0);return Math.round(s[3])}}const Qn="#SectionRootGroup#";class $n{engine;scenes;sectionGroup=new T;mesh=new Map;source;surfaceSource;lineDefaultColor=new g(11184810);lineHighlightColor=new g(11141120);constructor(e){this.source=e,this.sectionGroup.name=Qn}set visible(e){this.sectionGroup.visible=e,this.engine?.invalidate()}get visible(){return this.sectionGroup.visible}get sectionLineDefaultColor(){return this.lineDefaultColor}set sectionLineDefaultColor(e){this.lineDefaultColor=e,this.updateSectionLineColor(e,!1)}get sectionLineHighlightColor(){return this.lineHighlightColor}set sectionLineHighlightColor(e){this.lineHighlightColor=e,this.updateSectionLineColor(e,!0)}setVisible(e,t){const i=this.mesh.get(e);i&&i.forEach((e=>{e.visible=t}))}get sectionSurf(){const e=new Array;return this.mesh.forEach((t=>{e.push(t[0])})),e}bind(e){this.engine!==e&&(this.scenes&&this.engine&&(this.scenes.removeObject(Ot,Lt,Qn),this.engine.autoScaleFilterEvent.remove($n.filterHandler)),this.engine=e,this.scenes=e?.scenes,this.scenes&&this.engine&&(this.engine.autoScaleFilterEvent.add($n.filterHandler),this.scenes.addObject(Ot,this.sectionGroup,Lt),this.updateSections(),this.engine.invalidate()))}static filterHandler(e){if(e&&e.path[2]===Qn&&e.path[0]===Ot&&e.path[1]===Lt){e.filtered=!0}}updateSections(){Oi(this.mesh.keys(),(e=>{if(this.source.sections.findIndex((t=>t.id===e))<0){const t=this.mesh.get(e);if(t){this.mesh.delete(e);const[i,n]=t;this.sectionGroup.remove(i),this.sectionGroup.remove(n),nn(i),nn(n)}}})),this.source.sections.forEach((e=>{let t=this.mesh.get(e.id);if(!t){let i;if(this.surfaceSource)i=this.surfaceSource.createSurface(e);else{const e=jn(),t=this.source.config,n={...{color:8355711,side:K,opacity:.3,transparent:!0,depthWrite:!1},color:t.color,opacity:t.opacity},s=new c(n);i=new S(e,s)}const n=Vn(),s=new ve(n,new se({color:this.lineDefaultColor}));t=[i,s],this.mesh.set(e.id,t),this.sectionGroup.add(i),this.sectionGroup.add(s)}if(t){const[i,n]=t;let s=2,r=new a(0,0,0);this.engine&&this.engine.domainRange&&(s=this.engine.domainRange.getSize(new a).length(),r=this.engine.domainRange.getCenter(new a));const o=Wn(r,s,e.dir,e.shift);if(this.surfaceSource){const t=[new a(-1,-1,0),new a(1,-1,0),new a(-1,1,0),new a(1,1,0)];t.map((e=>e.applyMatrix4(o))),this.surfaceSource.updateSurface(e,i,t)}else i.matrix=o,i.matrixAutoUpdate=!1;n.matrix=o,n.material.color=new g(e.id===this.source.focusedSection?this.lineHighlightColor:this.lineDefaultColor),n.matrixAutoUpdate=!1}})),this.engine?.invalidate()}updateSectionLineColor(e,t=!1){this.mesh.forEach(((i,n)=>{const s=i[1];t&&n===this.source.focusedSection?s.material.color=e:t||n===this.source.focusedSection||(s.material.color=e)}))}}class Jn{sections=[];sectionsUpdated=new ht;config=kn;engine;sectionView=new $n(this);actionHandler=new Zn(this);get focusedSection(){return this.actionHandler.focusedSection}get sectionSurface(){return this.sectionView.surfaceSource}set sectionSurface(e){this.sectionView.surfaceSource=e}set sectionActionEnable(e){this.actionHandler.isEnabled=e,this.sectionView.visible=e}setsSectionVisible(e,t){this.sectionView.setVisible(e,t),this.actionHandler.setVisible(e,t)}constructor(e){this.config={...kn,...e};const{lineDefaultColor:t,lineHighlightColor:i}=this.config;this.sectionView.sectionLineDefaultColor=t??this.sectionView.sectionLineDefaultColor,this.sectionView.sectionLineHighlightColor=i??this.sectionView.sectionLineHighlightColor,this.actionHandler.focusedSectionChangedEvent.add(this.onFocusChanged),this.actionHandler.sectionChangedEvent.add(this.onSectionChanged)}addSection(e){this.sections.push(e),this.sectionView.updateSections(),this.sectionsUpdated.trigger({add:[e]})}removeSection(e){const t=this.sections.findIndex((t=>t.id===e)),i=this.sections[t];this.sections.splice(t,1),this.sectionView.updateSections(),this.sectionsUpdated.trigger({remove:[i]})}updateSection(e,t,i){if(void 0===t&&void 0===i)return;const n=this.sections.find((t=>t.id===e));n&&(void 0!==t&&(n.dir=t),void 0!==i&&(n.shift=i),this.sectionView.updateSections(),this.sectionsUpdated.trigger({updated:[n]}))}bind(e){this.engine!==e&&(this.engine&&(this.sectionView.bind(void 0),this.actionHandler.bind(void 0)),this.engine=e,this.engine&&(this.sectionView.bind(this.engine),this.actionHandler.bind(this.engine)))}onFocusChanged=e=>{e&&this.sectionView.updateSections()};onSectionChanged=e=>{e&&(this.sectionView.updateSections(),this.sectionsUpdated.trigger({updated:[e.updated]}))}}class es extends o{initialVertices=new Float32Array([-1,-1,0,1,-1,0,1,1,0,-1,-1,0,1,1,0,-1,1,0]);initialNormals=new Float32Array([0,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,1]);constructor(){super(),this.createGeometry()}createGeometry(){this.setAttribute("position",new n(this.initialVertices,3)),this.setAttribute("normal",new n(this.initialNormals,3))}update(e,i,n,s){const r=this.getAttribute("position"),o=this.getAttribute("normal");r.array=this.initialVertices.slice(),o.array=this.initialNormals.slice(),this.attributes.position.needsUpdate=!0,this.attributes.normal.needsUpdate=!0,this.scale(e/2,e/2,e/2),this.rotateX(Math.PI);const h=new a(0,0,1),d=h.clone().cross(n.clone()).normalize(),p=Math.acos(h.dot(n.clone().normalize())),l=(new t).makeRotationAxis(d,p);this.applyMatrix4(l);const c=n.clone().multiplyScalar(i.clone().dot(n.clone())),u=i.clone().sub(c),g=n.clone().multiplyScalar(s);u.add(g),this.translate(u.x,u.y,u.z)}}class ts extends Hn{sectionManager;sectionPlanes=new Fn;sectionSealingSurfaces=new Map;wrappedEnableSection=!0;constructor(){super(),this.sectionManager=new Jn({opacity:0})}bind(e){this.engine!==e&&(this.engine&&this.sectionManager.bind(void 0),super.bind(e),this.engine&&this.wrappedEnableSection&&this.sectionManager.bind(this.engine))}get enableSection(){return this.wrappedEnableSection}set enableSection(e){this.wrappedEnableSection!==e&&(this.wrappedEnableSection=e,this.sectionManager.bind(this.wrappedEnableSection?this.engine:void 0))}set enableAction(e){super.enableAction=e,this.sectionManager.sectionActionEnable=e}get sections(){return this.sectionManager.sections}setSectionVisible(e,t){this.sectionManager.setsSectionVisible(e,t)}setAllSectionVisible(e){this.sectionManager.sections.forEach((t=>{const{id:i}=t;this.setSectionVisible(i,e)}))}getSectionClippingPlanes(){return this.sectionPlanes}onHoverBoxClippingChanged=()=>{this.sectionManager.focusedSection&&this.boundaryHelper.setActivePlaneVisibility(!1)};onHoverSectionClippingChanged=e=>{e&&"focusKey"in e&&(e.focusKey?this.boundaryHelper.setActivePlaneVisibility(!1):this.boundaryHelper.setActivePlaneVisibility(!0))};bindEvents(){super.bindEvents(),this.engine&&(this.sectionManager.bind(this.engine),this.sectionManager.sectionsUpdated.add(this.handleSectionChanged),this.clippingActionHandler.hoverOnDirChangedEvent.add(this.onHoverBoxClippingChanged),this.sectionManager.actionHandler.focusedSectionChangedEvent.add(this.onHoverSectionClippingChanged))}unbindEvents(){super.unbindEvents(),this.engine&&(this.sectionManager.sectionsUpdated.remove(this.handleSectionChanged),this.clippingActionHandler.hoverOnDirChangedEvent.remove(this.onHoverBoxClippingChanged),this.sectionManager.actionHandler.focusedSectionChangedEvent.remove(this.onHoverSectionClippingChanged))}addSection(e){if(this.engine){this.unApplyClipToAllObjects(),this.sectionManager.addSection(e);const{id:t,dir:i,shift:n}=e,s=new re(i,-n);this.sectionPlanes.set(t,s),this.applyClipToAllObjects(),this.applyTransform()}}removeSection(e){this.unApplyClipToAllObjects(),this.sectionManager.removeSection(e),this.sectionPlanes.remove(e),this.sectionSealingSurfaces=new Map(Array.from(this.sectionSealingSurfaces).filter((([,t])=>t.sectionId!==e))),this.applyClipToAllObjects()}clear(){super.clear();(this.sectionManager.sections||[]).map((e=>e.id)).forEach((e=>{this.removeSection(e)}))}clipObject(e){const t=this.sectionPlanes.array,{material:i}=e;if(i instanceof Array){i.forEach((e=>{e.clippingPlanes=this.transformedPlanes.array.concat(t)}))}else i.clippingPlanes=this.transformedPlanes.array.concat(t)}updatePlaneTransformMatrix(e){super.updatePlaneTransformMatrix(e),this.updateSectionPlaneTransformMatrix()}updateSection(e){const{id:t,dir:i,shift:n}=e;this.sectionManager.updateSection(t,i,n),this.updateSectionPlaneTransformMatrix(),this.sectionSealingSurfaces.forEach((e=>{if(e.sectionId===t){const s=this.sectionManager.sections.find((e=>e.id===t));if(s){const{dir:t,shift:r}=s;this.updateSectionSealingSurface(e.geometry,i||t,n||r)}}}))}handleSectionChanged=e=>{if(this.updateSectionPlaneTransformMatrix(),e&&e.updated){const{updated:t}=e;t.forEach((e=>{const{id:t,dir:i,shift:n}=e;this.sectionSealingSurfaces.forEach((e=>{e.sectionId===t&&this.updateSectionSealingSurface(e.geometry,i,n)}))}))}};addActionOnSectionChanged(e){this.sectionManager.sectionsUpdated.add(e)}removeActionOnSectionChanged(e){this.sectionManager.sectionsUpdated.remove(e)}updateSectionPlaneTransformMatrix(){if(this.engine){const{matrix:e}=this.engine;Oi(this.sectionPlanes.keys(),(t=>{const i=this.sectionManager.sections.find((e=>e.id===t));if(i){const{dir:n,shift:s}=i,r=this.sectionPlanes.get(t);r.normal=n.clone(),r.constant=-s,r.applyMatrix4(e)}}))}}updateSectionSealingSurface(e,t,i){if(this.engine&&this.engine.domainRange){const n=this.engine.domainRange.getSize(new a).length()||2,s=this.engine.domainRange.getCenter(new a)||new a(0,0,0);e.update(n,s,t,i)}}addSealingSurfaceToTargetGroup(e,t,i,n,s,r,a,...o){super.addSealingSurfaceToTargetGroup(e,t,i,n,s,r,a,...o),this.sectionManager.sections.forEach((h=>{const{id:d,dir:p,shift:l}=h,c=new T;c.name=d,c.visible=!0,n.add(c);const u=e=>{const i=new es;this.updateSectionSealingSurface(i,p,l);const n=e||new Q({color:16711680}),o=new S(i,n);o.name=t.name,this.ApplyStencilMask(o,d);const[h,u]=Hn.createStencilMeshes(t,this.sectionPlanes.get(d));a.set(d,[h,u]),this.setOutlineRendering(r,t,[h,u],s,o,d),c.add(o),this.sectionSealingSurfaces.set(`${d}-${t.name}`,{sectionId:d,geometry:i})};if(e.isAsyncCreate(i,...o)){let n=this.updateDebouncers.get(d);n||(n=new Ki,this.updateDebouncers.set(d,n)),n.debounce((async()=>{const n=await e.getSurfaceMeshAsync(t,this,d,i,...o);u(n)}),Gn)}else{const n=e.getSurfaceMesh(t,this,d,i,...o);u(n)}}))}ApplyStencilMask(e,t){const i=Array.isArray(e)?e:[e],n=this.transformedPlanes.array.filter(((e,i)=>i!==this.transformedPlanes.indexOf(t))),s=this.sectionPlanes.array.filter(((e,i)=>i!==this.sectionPlanes.indexOf(t)));i.forEach((e=>{const t=e.material;t.clippingPlanes=n.concat(s),t.stencilWrite=!0,t.stencilRef=0,t.stencilFunc=ae,t.stencilFail=oe,t.stencilZFail=oe,t.stencilZPass=oe}))}addSectionUniversalClip(e){const t=this.universalClipGroup;if(!t)return;const i=this.sealingSurfaceFactoryHub.detectFactory();if(!i)return;const{id:n,dir:s,shift:r}=e,a=new T;a.name=n,a.visible=!0,t.add(a);const o=e=>{const t=new es;this.updateSectionSealingSurface(t,s,r),this.engine&&(Array.isArray(e)?e.forEach((e=>{a.add(e)})):e instanceof me?a.add(new S(t,e)):a.add(e))};if(i.isAsyncCreate()){let e=this.universalClipDebouncers.get(n);e||(e=new Ki,this.updateDebouncers.set(n,e)),e.debounce((async()=>{const e=await i.getSurfaceMeshAsync(void 0,this,n);o(e)}),Gn)}else{const e=i.getSurfaceMesh(void 0,this,n);o(e)}}removeSectionUniversalClip(e){this.scenes?.removeObject(Ot,Lt,Un,Pn,e)}applyUniversalClip(){super.applyUniversalClip(),this.universalClipGroup&&this.sectionManager.sections.forEach((e=>{this.addSectionUniversalClip(e)}))}}class is{priority;constructor(e=0){this.priority=e}detect(){return!0}allowClip(){return!0}isAsyncUpdate(){return!1}isAsyncCreate(){return!1}updateRequired(){return!0}mapGroup(){}sealingSurfaceCreateMethod(e){return e?"Mesh"===e.type?zn.ResultMaterial:zn.ResultNone:zn.ResultMaterial}getSurfaceMesh(e,t,i,...n){if(!e)return new c({color:8355711});if("Mesh"===e.type){return(Array.isArray(e.material)?e.material[0]:e.material).clone()}throw Error("invalid surface create method.")}updateMesh(e,t,i,n,...s){if(i&&e){const t=Ai.findOffspring(i,e.name);if(t&&"Mesh"===t.type&&"Mesh"===e.type){const i=Array.isArray(e.material)?e.material[0]:e.material,n=t.material,s=i.clone();s.clippingPlanes=n.clippingPlanes,s.needsUpdate=!0,t.material=s,n.dispose()}}return In.MaterialReplaced}getSurfaceMeshAsync(e,t,i,...n){throw new Error("Method not implemented.")}updateMeshAsync(e,t,i,n,...s){throw new Error("Method not implemented.")}}var ns;!function(e){e[e.Gradient=0]="Gradient",e[e.Nearest=1]="Nearest",e[e.Discrete=2]="Discrete"}(ns||(ns={}));class ss{changedEvent=new ht;wrappedLocation=[0,0];wrappedSize=[1,1];wrappedLut=[];wrappedType=ns.Gradient;wrappedLabel="";wrappedLabelFontSize=void 0;wrappedTitle="";wrappedTitleFontSize=void 0;wrappedFont="Arial";wrappedColor="rgba(200, 0, 0, 1)";wrappedMinFontSize=16;wrappedMaxFontSize=22;wrappedFactor=1;//! 显示数据的系数因子,用于单位变换等需要改变数值显示的场景 get factor(){return this.wrappedFactor}set factor(e){this.factor!==e&&(this.wrappedFactor=e,this.changedEvent.trigger())}get location(){return this.wrappedLocation}set location(e){this.wrappedLocation=e,this.changedEvent.trigger()}get size(){return this.wrappedSize}set size(e){this.wrappedSize=e,this.changedEvent.trigger()}get lut(){return this.wrappedLut}set lut(e){this.wrappedLut=e,this.changedEvent.trigger()}get type(){return this.wrappedType}set type(e){this.wrappedType=e,this.changedEvent.trigger()}get label(){return this.wrappedLabel}set label(e){this.wrappedLabel=e,this.changedEvent.trigger()}get labelFontSize(){return this.wrappedLabelFontSize}set labelFontSize(e){this.wrappedLabelFontSize=e,this.changedEvent.trigger()}get title(){return this.wrappedTitle}set title(e){this.wrappedTitle=e,this.changedEvent.trigger()}get titleFontSize(){return this.wrappedTitleFontSize}set titleFontSize(e){this.wrappedTitleFontSize=e,this.changedEvent.trigger()}get font(){return this.wrappedFont}set font(e){this.wrappedFont=e,this.changedEvent.trigger()}get color(){return this.wrappedColor}set color(e){this.wrappedColor=e,this.changedEvent.trigger()}get minFontSize(){return this.wrappedMinFontSize}set minFontSize(e){this.wrappedMinFontSize=e,this.changedEvent.trigger()}get maxFontSize(){return this.wrappedMaxFontSize}set maxFontSize(e){this.wrappedMaxFontSize=e,this.changedEvent.trigger()}draw(e){const t=this.wrappedSize[0],i=this.wrappedSize[1],n=.5*i,s=.1*t,r=.8*i,a=.1*t,o=.1*a;e.font="Normal 32px Arial",e.fillStyle="rgba(200, 0, 0, 1)",e.strokeStyle=this.wrappedColor,e.lineWidth=.3,this.drawColorBar(e,s,n,a,r),this.drawMarks(e,s,n,a,r,o),this.drawLabels(e,s,n,a,r,o),this.drawTitle(e,s,n,r)}drawColorBar(e,t,i,n,s){switch(this.wrappedType){case ns.Discrete:this.drawDiscreteColorBar(e,t,i,n,s);break;case ns.Nearest:this.drawNearestColorBar(e,t,i,n,s);break;case ns.Gradient:this.drawGradientColorBar(e,t,i,n,s);break;default:throw Error("Unknown legend type")}}drawLabels(e,t,i,n,s,r){switch(this.wrappedType){case ns.Gradient:case ns.Nearest:this.drawGradientLabels(e,t,i,n,s,r);break;case ns.Discrete:this.drawDiscreteLabels(e,t,i,n,s,r)}}drawGradientLabels(e,t,i,n,s,r){const a=this.wrappedLut[0].value,o=this.wrappedLut[this.wrappedLut.length-1].value-a;let h=Number.MAX_VALUE;for(let e=0;ethis.wrappedMaxFontSize?d=this.wrappedMaxFontSize:void 0!==this.wrappedMinFontSize&&dthis.wrappedMaxFontSize?o=this.wrappedMaxFontSize:void 0!==this.wrappedMinFontSize&&o=0&&this.items.splice(t,1),e.changedEvent.remove(this.legendChanged)}draw(e){if(this.wrappedEngine){const t=this.wrappedEngine.viewPortSize.y/2;this.items.forEach((i=>{const n=i;n.size[0]=t,n.size[1]=t,n.draw(e)}))}}legendChanged=()=>{this.wrappedEngine&&this.wrappedEngine.invalidOverlap()}}class as extends Sn{isEnabled=!0;wrappedEngine;crossPoint;yAxisColor="#E587FC";xAxisColor="#83B9FB";lineWidth=1;majorMarkWidth=1;majorMarkLength=6;minorMarkWidth=1;minorMarkLength=3;textOffset=10;bindChangedEvent=new ht;get engine(){return this.wrappedEngine}bind(e){e!==this.wrappedEngine&&(this.wrappedEngine&&(this.wrappedEngine.invalidOverlap(),this.wrappedEngine.removeOverlayLayer(this),this.wrappedEngine.removeActionHandler(this),this.wrappedEngine.rotationChangedEvent.remove(this.updateOverlap),this.wrappedEngine.cameraChangeEvent.remove(this.updateOverlap),this.wrappedEngine.adaptRangeChangedEvent.remove(this.updateOverlap),this.wrappedEngine=void 0),this.wrappedEngine=e,this.wrappedEngine&&(this.wrappedEngine.addOverlayLayer(this),this.wrappedEngine.addActionHandler(this),this.wrappedEngine.rotationChangedEvent.add(this.updateOverlap),this.wrappedEngine.cameraChangeEvent.add(this.updateOverlap),this.wrappedEngine.adaptRangeChangedEvent.add(this.updateOverlap),this.updateOverlap()),this.bindChangedEvent.trigger({bound:void 0!==this.wrappedEngine}))}reset(){this.crossPoint=void 0,this.wrappedEngine?.invalidOverlap()}handleLeftButtonUp(e,t){if(this.isEnabled&&this.wrappedEngine){if(0===t.state){const t=new r(e.offsetX,e.offsetY);this.crossPoint=rn.screenUnProject(t,this.wrappedEngine),this.wrappedEngine.invalidOverlap()}}return!1}draw(e){if(!this.isEnabled||!this.wrappedEngine||!this.crossPoint)return;const{x:t,y:i}=rn.projectToScreen(this.crossPoint,this.wrappedEngine),{x:n,y:s}=this.wrappedEngine.viewPortSize;if(t<0||i<0||t>n||i>s)return;if(!(this.wrappedEngine&&this.wrappedEngine.camera instanceof pt))return;const{afterProjectionMatrix:r}=this.wrappedEngine.camera,o=new a;r.decompose(new a,new X,o);const h=o.x,{maxDim:d}=this.wrappedEngine,p=s/((this.wrappedEngine.camera.top-this.wrappedEngine.camera.bottom)/2)*h/d,l=function(e,t){if(!Number.isNaN(e)&&t){let i,n=e/t,s=0,r=0,a=1;if(n>=1){n=Math.floor(n);const e=n.toString();s=e.length,r=parseInt(e[0],10),a=10}else if(n<1&&n>0){for(a=.1,s=2;a**(s-1)>n;)s+=1;r=Math.floor(n/a**(s-1))}i=r>5?10:r>2?5:2;let o=i*a**(s-1);return o<1&&(o=Number(o.toFixed(s-1))),o<1e-9&&(o=1e-9),o}return 1}(s/5,p),c=l*p/5;e.save(),e.font="Normal 12px Arial",e.lineWidth=this.lineWidth,e.fillStyle=this.xAxisColor,e.strokeStyle=this.xAxisColor,e.strokeStyle=this.xAxisColor,e.beginPath(),e.moveTo(0,i),e.lineTo(n,i),e.stroke(),e.strokeStyle=this.yAxisColor,e.beginPath(),e.moveTo(t,0),e.lineTo(t,s),e.stroke();const u=-Math.floor(t/c),g=Math.floor((n-t)/c),f=-Math.floor((s-i)/c),m=Math.floor(i/c);let w=u-u%5;for(this.lineWidth=this.majorMarkWidth,e.strokeStyle=this.xAxisColor,e.fillStyle=this.xAxisColor,e.beginPath();w<=g;){const n=t+w*c;e.moveTo(n,i),e.lineTo(n,i-this.majorMarkLength),w+=5}for(e.stroke(),w=u-u%5;w<=g;){const n=t+w*c,s=String(nt.divide(nt.times(w,l),5));e.fillText(s,n+(0===w?this.textOffset:0),i-this.textOffset),w+=5}for(this.lineWidth=this.minorMarkWidth,w=u,e.beginPath();w<=g;){if(w%5!=0){const n=t+w*c;e.moveTo(n,i),e.lineTo(n,i-this.minorMarkLength)}w+=1}for(e.stroke(),e.strokeStyle=this.yAxisColor,e.fillStyle=this.yAxisColor,e.lineWidth=this.majorMarkWidth,w=f-f%5,e.beginPath();w<=m;){const n=i-w*c;e.moveTo(t,n),e.lineTo(t+this.majorMarkLength,n),w+=5}for(e.stroke(),w=f-f%5;w<=m;){if(0!==w){const n=i-w*c,s=String(nt.divide(nt.times(w,l),5));e.fillText(s,t+this.textOffset,n)}w+=5}for(e.lineWidth=this.minorMarkWidth,w=f,e.beginPath();w<=m;){if(w%5!=0){const n=i-w*c;e.moveTo(t,n),e.lineTo(t+this.minorMarkLength,n)}w+=1}e.stroke(),e.restore()}updateOverlap=()=>{this.wrappedEngine?.invalidOverlap()}}const os=[new a(1,0,0),new a(0,1,0),new a(0,0,1),new a(-1,0,0),new a(0,-1,0),new a(0,0,-1)],hs=500;class ds extends Sn{renderOrder=10;wrappedEngine;scene=new A;camera=new e(-1.4,1.4,1.4,-1.4,1,100);navigatorGroup;viewPort=new ie(10,10,150,150);arrowGroup=new T;detectScene=new A;detectGroup=new T;logoWidth=40;logoHeight=40;toRight;toLeft;toTop;toDown;toRightTop;toLeftTop;drawArr=[];ctx;drawActionGauges=!0;bindChangedEvent=new ht;constructor(){super(3),this.camera.position.set(0,0,10),this.prepareEnvironment()}get engine(){return this.wrappedEngine}async init(){if(this.navigatorGroup)return;this.navigatorGroup=new T;const e=new En;window.assetBaseUrl&&e.setPath(window.assetBaseUrl);const i=await e.load("/assets/toRight.svg"),n=await e.load("/assets/toTop.svg"),s=await e.load("/assets/toLeft.svg"),r=await e.load("/assets/toDown.svg"),a=await e.load("/assets/rightTop.png"),h=await e.load("/assets/leftTop.png");this.toRight=i.image,this.toTop=n.image,this.toLeft=s.image,this.toDown=r.image,this.toRightTop=a.image,this.toLeftTop=h.image;const d=new xn(!0),p=new c({color:"#fff",transparent:!0,opacity:.5}),l=new S(d,p),u=new xe(d),f=new ne(u,new se({color:"#ccc",linewidth:5,linecap:"square"}));f.position.set(-.5,-.5,-.5);const m=new xn(!0),w=[new Q({color:new g(1,0,0)}),new Q({color:new g(0,1,0)}),new Q({color:new g(0,0,1)}),new Q({color:new g(-1,0,0)}),new Q({color:new g(0,-1,0)}),new Q({color:new g(0,0,-1)})];for(let e=0;e<6;e+=1)m.addGroup(6*e,6,e);const v=new S(m,w);this.detectGroup.matrixAutoUpdate=!1,this.detectGroup.add(v),this.detectScene.add(this.detectGroup);const{position:x,normal:y}=St(.7,.2,.05,.1,10),M=new t;M.setPosition(-.5,-.5,-.5),l.matrix=M,l.matrixAutoUpdate=!1,v.matrix=M,v.matrixAutoUpdate=!1,this.navigatorGroup.add(l),this.navigatorGroup.add(f),this.navigatorGroup.add(this.arrowGroup);const b=new o,E=new ye(this.getSpriteMaterial(new g("#000"),"Y")),C=new ye(this.getSpriteMaterial(new g("#000"),"X")),_=new ye(this.getSpriteMaterial(new g("#000"),"Z"));this.arrowGroup.add(_),this.arrowGroup.add(C),this.arrowGroup.add(E),C.position.x=1,E.position.y=1,_.position.z=1,b.attributes.position=x,b.attributes.normal=y;const R=new S(b,new c({color:"red"}));R.rotateY(Math.PI/2),this.arrowGroup.add(R);const A=new o;A.attributes.position=x,A.attributes.normal=y;const P=new S(A,new c({color:"green"}));P.rotateX(-Math.PI/2),this.arrowGroup.add(P);const O=new o;O.attributes.position=x,O.attributes.normal=y;const L=new S(O,new c({color:"blue"}));this.arrowGroup.add(L),this.scene.add(this.navigatorGroup),this.drawArr=[{name:"right",img:this.toRight,x:this.logoWidth+110,y:e=>e-this.logoHeight-55,width:this.logoWidth/2,height:this.logoHeight/2},{name:"left",img:this.toLeft,x:this.logoWidth-40,y:e=>e-this.logoHeight-55,width:this.logoWidth/2,height:this.logoHeight/2},{name:"top",img:this.toTop,x:this.logoWidth+36,y:e=>e-this.logoHeight-130,width:this.logoWidth/2,height:this.logoHeight/2},{name:"bottom",img:this.toDown,x:this.logoWidth+36,y:e=>e-25,width:this.logoWidth/2,height:this.logoHeight/2},{name:"rightTop",img:this.toRightTop,x:this.logoWidth+75,y:e=>e-this.logoHeight-25,width:this.logoWidth/1.6,height:this.logoHeight/1.6},{name:"leftTop",img:this.toLeftTop,x:this.logoWidth-10,y:e=>e-this.logoHeight-25,width:this.logoWidth/1.6,height:this.logoHeight/1.6}],this.wrappedEngine&&(this.navigatorGroup.matrix=this.wrappedEngine.rotationMatrix,this.navigatorGroup.matrixAutoUpdate=!1,this.wrappedEngine.invalidOverlap())}bind(e){e!==this.wrappedEngine&&(this.wrappedEngine&&(this.unbindRotationButtonEvents(),this.wrappedEngine.removeActionHandler(this),this.wrappedEngine.removeRenderHandler(this),this.wrappedEngine.invalidOverlap(),this.wrappedEngine.removeOverlayLayer(this),this.wrappedEngine.rotationChangedEvent.remove(this.onTransformChanged),this.wrappedEngine=void 0),this.wrappedEngine=e,this.wrappedEngine&&(this.navigatorGroup&&(this.navigatorGroup.matrix=this.wrappedEngine.rotationMatrix,this.navigatorGroup.matrixAutoUpdate=!1),this.wrappedEngine.rotationChangedEvent.add(this.onTransformChanged),this.wrappedEngine.addActionHandler(this),this.wrappedEngine.addRenderHandler(this),this.wrappedEngine.addOverlayLayer(this),this.bindRotationButtonEvents()),this.bindChangedEvent.trigger({bound:void 0!==this.wrappedEngine}))}getEventPosition(e){let t=0,i=0;const n=e;return n.layerX||0===n.layerX?(t=n.layerX,i=n.layerY):(e.offsetX||0===e.offsetX)&&(t=e.offsetX,i=e.offsetY),{x:t,y:i}}render(e){if(!this.isEnabled)return;e.clearDepth();const t=new ie;e.getViewport(t),e.setViewport(this.viewPort),e.render(this.scene,this.camera),e.setViewport(t)}draw(e){if(this.ctx=e,this.drawActionGauges&&this.wrappedEngine&&this.drawArr){const{y:t}=this.wrappedEngine.viewPortSize;this.drawArr.forEach((i=>{i.img&&et(e,i.img,i.x,i.y(t),0,0,i.width,i.height)}))}}clickRotationButtonsHandler=e=>{const t=this.getEventPosition(e),i=this.testClick(t);i&&i.length>0&&("right"===i[0].name&&this.handleClickRight(),"left"===i[0].name&&this.handleClickLeft(),"top"===i[0].name&&this.handleClickUp(),"bottom"===i[0].name&&this.handleClickDown(),"rightTop"===i[0].name&&this.handleClickRotateRight(),"leftTop"===i[0].name&&this.handleClickRotateLeft())};bindRotationButtonEvents(){if(this.wrappedEngine&&this.wrappedEngine.parentDiv){const e=this.wrappedEngine.parentDiv;e&&e.addEventListener("click",this.clickRotationButtonsHandler)}}unbindRotationButtonEvents(){if(this.wrappedEngine&&this.wrappedEngine.parentDiv){const e=this.wrappedEngine.parentDiv;e&&e.removeEventListener("click",this.clickRotationButtonsHandler)}}testClick(e){if(this.ctx&&this.wrappedEngine){const{y:t}=this.wrappedEngine.viewPortSize;return this.drawArr.filter((i=>e.x>i.x&&e.xi.y(t)&&e.y=this.viewPort.x&&e.offsetX<=this.viewPort.x+this.viewPort.z&&i.viewPortSize.y-e.offsetY>=this.viewPort.y&&i.viewPortSize.y-e.offsetY<=this.viewPort.y+this.viewPort.w){const t=i.renderTargetAndReadFloat(this.detectScene,e.offsetX,e.offsetY,1,1,this.camera,this.viewPort,void 0);let n=t[0]+2*t[1]+3*t[2];if(n<0&&(n=3-n),n-=1,n<0)return!1;const s=i.rotationMatrix.clone();let r=this.turnSelectedDir2Z(n,s);return r=this.alignSelectedDir(n,r),i.rotationMatrix=r,!0}}return!1}alignSelectedDir(e,i){const n=os[(e+1)%6].clone().applyMatrix4(i);let s=0,r=0;for(let e=0;e=0&&t>s&&(s=t,r=e)}const a=os[2].clone(),o=Math.asin(n.clone().cross(os[r]).z);a.normalize();const h=(new t).makeRotationAxis(a,o);return h.multiply(i),h}turnSelectedDir2Z(e,i){const n=new t,s=os[e].clone(),r=new a(0,0,1);s.applyMatrix4(i);let o=s.clone().cross(r),h=0;return o.length()<1e-5?(o=new a(0,1,0),s.z+r.z<1&&(h=Math.PI)):(o.normalize(),h=Math.acos(s.clone().dot(r))),n.makeRotationAxis(o,h),n.multiply(i),n}prepareEnvironment(){const e=new C(5066061),t=new _(16777215,.7);t.position.set(3,3,3);const i=new _(16777215,.7);i.position.set(-3,-3,3),this.scene.add(e),this.scene.add(t),this.scene.add(i)}onTransformChanged=()=>{if(this.wrappedEngine&&this.wrappedEngine.rotationMatrix&&this.navigatorGroup){const e=(new t).extractRotation(this.wrappedEngine.rotationMatrix);this.navigatorGroup.matrix=e,this.detectGroup.matrix=e}};handleClickDown(){if(this.wrappedEngine){const e=new a;this.camera.getWorldDirection(e);const t=e.cross(this.camera.up);this.rotate(t,Math.PI/4,hs)}}handleClickUp(){if(this.wrappedEngine){const e=new a;this.camera.getWorldDirection(e);const t=e.cross(this.camera.up);this.rotate(t,-Math.PI/4,hs)}}handleClickRight(){this.wrappedEngine&&this.rotate(this.camera.up,Math.PI/4,hs)}handleClickLeft(){this.wrappedEngine&&this.rotate(this.camera.up,-Math.PI/4,hs)}handleClickRotateRight(){if(this.wrappedEngine){const e=new a;this.camera.getWorldDirection(e);const t=new a(1,0,0).cross(this.camera.up);this.rotate(t,Math.PI/4,hs)}}handleClickRotateLeft(){if(this.wrappedEngine){const e=new a;this.camera.getWorldDirection(e);const t=new a(1,0,0).cross(this.camera.up);this.rotate(t,-Math.PI/4,hs)}}rotate(e,t,i){this.wrappedEngine&&ji.Rotate(this.wrappedEngine,e,this.wrappedEngine.rotationCenter instanceof we?this.wrappedEngine.rotationCenter.origin:this.wrappedEngine.rotationCenter,t,i)}}class ps extends Sn{renderOrder=10;wrappedEngine;scene=new A;camera=new e(-1.4,1.4,1.4,-1.4,1,100);navigatorGroup;viewPort=new ie(10,10,150,150);arrowGroup=new T;drawActionGauges=!0;bindChangedEvent=new ht;constructor(){super(3),this.camera.position.set(0,0,10),this.prepareEnvironment()}get engine(){return this.wrappedEngine}init(){if(this.navigatorGroup)return;this.navigatorGroup=new T;const{position:e,normal:t}=St(.7,.2,.05,.1,10);this.navigatorGroup.add(this.arrowGroup);const i=new o,n=new ye(this.getSpriteMaterial(new g("#000"),"Y")),s=new ye(this.getSpriteMaterial(new g("#000"),"X"));this.arrowGroup.add(s),this.arrowGroup.add(n),s.position.x=1,n.position.y=1,i.attributes.position=e,i.attributes.normal=t;const r=new S(i,new c({color:"red"}));r.rotateY(Math.PI/2),this.arrowGroup.add(r);const a=new o;a.attributes.position=e,a.attributes.normal=t;const h=new S(a,new c({color:"green"}));h.rotateX(-Math.PI/2),this.arrowGroup.add(h);const d=new Ee(.1),p=new S(d,new c({color:"white"}));this.arrowGroup.add(p),this.scene.add(this.navigatorGroup),this.wrappedEngine&&(this.navigatorGroup.matrix=this.wrappedEngine.rotationMatrix,this.navigatorGroup.matrixAutoUpdate=!1,this.wrappedEngine.invalidate())}bind(e){e!==this.wrappedEngine&&(this.wrappedEngine&&(this.wrappedEngine.removeRenderHandler(this),this.wrappedEngine.rotationChangedEvent.remove(this.onTransformChanged),this.wrappedEngine.invalidate(),this.wrappedEngine=void 0),this.wrappedEngine=e,this.wrappedEngine&&(this.navigatorGroup&&(this.navigatorGroup.matrix=this.wrappedEngine.rotationMatrix,this.navigatorGroup.matrixAutoUpdate=!1),this.wrappedEngine.rotationChangedEvent.add(this.onTransformChanged),this.wrappedEngine.addRenderHandler(this),this.wrappedEngine.invalidate()),this.bindChangedEvent.trigger({bound:void 0!==this.wrappedEngine}))}render(e){if(!this.isEnabled)return;e.clearDepth();const t=new ie;e.getViewport(t),e.setViewport(this.viewPort),e.render(this.scene,this.camera),e.setViewport(t)}getTextCanvasText(e,t){const i=document.createElement("canvas");i.width=64,i.height=64;const n=i.getContext("2d");return n&&e&&(n.beginPath(),n.lineWidth=3,n.fillStyle="rgba(0,0,0,0)",n.fillRect(0,0,64,64),n.font='16px " bold',n.textAlign="center",n.textBaseline="middle",n.strokeStyle="#FFF",n.strokeText(e,32,32),n.fillStyle=t,n.fillText(e,32,32),n.closePath()),i}getSpriteMaterial(e,t=""){return new Me({map:new be(this.getTextCanvasText(t,e.getStyle())),toneMapped:!1})}prepareEnvironment(){const e=new C(5066061),t=new _(16777215,.7);t.position.set(3,3,3);const i=new _(16777215,.7);i.position.set(-3,-3,3),this.scene.add(e),this.scene.add(t),this.scene.add(i)}onTransformChanged=()=>{if(this.wrappedEngine&&this.wrappedEngine.rotationMatrix&&this.navigatorGroup){const e=(new t).extractRotation(this.wrappedEngine.rotationMatrix);this.navigatorGroup.matrix=e}}}const ls=gn.newSeed(),cs=gn.newSeed(),us=gn.newSeed();class gs extends Sn{enableZoom3d=!1;enableZoom2d=!0;enableTranslate2d=!0;enableRotation=!0;previousPosition=new r;touchPointerId=[];touchPointer=[];wheelTimer;constructor(){super(10)}handleLeftButtonDown(e,t){if(this.isEnabled){const i=t;if("touch"===e.pointerType){if(this.touchPointerId.length<2&&-1===this.touchPointerId.indexOf(e.pointerId)&&(this.touchPointerId.push(e.pointerId),this.touchPointer.push({position:new r(e.offsetX,e.offsetY),direction:""})),-1===this.touchPointerId.indexOf(e.pointerId))return!1;if(2===this.touchPointerId.length)return!1}if(0===i.state)return this.previousPosition=new r(e.offsetX,e.offsetY),!1}return!1}handleLeftButtonUp(e,t){if(this.isEnabled){const i=t;if("touch"===e.pointerType){const t=this.touchPointerId.indexOf(e.pointerId);if(t>=0&&(this.touchPointerId.splice(t,1),this.touchPointer.splice(t,1)),2===this.touchPointerId.length)return!1}if(i.state===ls)return i.cursorType=fn.NONE,i.releasePointer(),i.state=0,!0}return!1}handleRightButtonDown(e,t){if(this.isEnabled){if(0===t.state)return this.previousPosition=new r(e.offsetX,e.offsetY),!1}return!1}handleRightButtonUp(e,t){if(this.isEnabled){const e=t;if(e.state===cs)return e.cursorType=fn.NONE,e.releasePointer(),e.state=0,!0}return!1}handleMouseMove(e,t){if(this.isEnabled){const i=t,n=new r(e.offsetX,e.offsetY),s=n.clone().sub(this.previousPosition);if("touch"===e.pointerType){const t=this.touchPointerId.indexOf(e.pointerId);if(t>=0&&2===this.touchPointerId.length){const e=this.touchPointer[t].position;if(this.touchPointer[t].position=n,this.touchPointer[t].direction=n.x+n.y-e.x-e.y>0?"rightTop":"leftBottom",this.touchPointer[0].direction!==this.touchPointer[1].direction){const s=this.touchPointer[0===t?1:0].position,r=(s.y-n.y)**2+(s.x-n.x)**2,a=(s.y-e.y)**2+(s.x-e.x)**2;a>r?this.zoom3d(12,i):a2&&(1===e.buttons&&this.enableRotation?(i.capturePointer(e.pointerId),i.state=ls,i.cursorType=fn.HAND):2===e.buttons&&this.enableTranslate2d&&(i.capturePointer(e.pointerId),i.state=cs,i.cursorType=fn.HAND)),i.state===ls)return this.rotate(n.x-this.previousPosition.x,n.y-this.previousPosition.y,i),this.previousPosition=n,!0;if(i.state===cs)return this.translate2d((n.x-this.previousPosition.x)/i.viewPortSize.x*2,-(n.y-this.previousPosition.y)/i.viewPortSize.y*2,i),this.previousPosition=n,!0}return!1}handleMouseWheel(e,t){if(this.isEnabled){if(0===t.state)return!0}return!1}handleKeyDown(e,t){if(this.isEnabled){if(0===t.state)return!0}return!1}handleKeyUp(e,t){if(this.isEnabled){if(0===t.state)return!0}return!1}static stopWheel(e){e.state===us&&(e.state=0)}handleWheel(e,t){if(this.isEnabled){const i=t;if(i.state=us,i.state===us){clearTimeout(this.wheelTimer),this.wheelTimer=setTimeout((()=>{gs.stopWheel(i)}),200);let n=e.deltaY;return e.deltaMode===WheelEvent.DOM_DELTA_LINE?n*=40:e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(n*=800),e.ctrlKey?this.zoom3d(n,t):this.zoom2d(e.offsetX/i.viewPortSize.x*2-1,1-e.offsetY/i.viewPortSize.y*2,n,t),!1}}return!1}zoom2d(e,i,n,s){if(this.enableZoom2d){const r=s,o=1-n/120/10,h=new t;if(h.makeTranslation(e,i,0),h.scale(new a(o,o,1)),h.multiply((new t).makeTranslation(-e,-i,0)),ot(r.camera)){const e=r.camera;e.afterProjectionMatrix=h.multiply(e.afterProjectionMatrix),e.raiseCameraChangeEvent()}}}zoom3d(e,t){if(this.enableZoom3d){const{camera:i}=t;i.position.z*=1+e/120/10,i.raiseCameraChangeEvent()}}translate2d(e,i,n){if(this.enableTranslate2d){const s=n,r=new t;if(r.makeTranslation(e,i,0),ot(s.camera)){const e=s.camera;e.afterProjectionMatrix=r.multiply(e.afterProjectionMatrix),e.raiseCameraChangeEvent()}}}rotate(e,t,i){if(this.enableRotation){const n=i;n.rotationMatrix=Kn(e,t,i).multiply(n.rotationMatrix)}}}class fs{isEnabled=!0;wrappedEngine;frontColor="#DDDDDD";bindChangedEvent=new ht;get engine(){return this.wrappedEngine}bind(e){e!==this.wrappedEngine&&(this.wrappedEngine&&(this.wrappedEngine.removeOverlayLayer(this),this.wrappedEngine.invalidOverlap(),this.wrappedEngine.rotationChangedEvent.remove(this.updateOverlap),this.wrappedEngine.cameraChangeEvent.remove(this.updateOverlap),this.wrappedEngine.adaptRangeChangedEvent.remove(this.updateOverlap),this.wrappedEngine=void 0),this.wrappedEngine=e,this.wrappedEngine&&(this.wrappedEngine.addOverlayLayer(this),this.wrappedEngine.rotationChangedEvent.add(this.updateOverlap),this.wrappedEngine.cameraChangeEvent.add(this.updateOverlap),this.wrappedEngine.adaptRangeChangedEvent.add(this.updateOverlap),this.wrappedEngine.invalidOverlap()),this.bindChangedEvent.trigger({bound:void 0!==this.wrappedEngine}))}draw(e){if(this.isEnabled&&this.wrappedEngine&&this.wrappedEngine.camera instanceof pt){const{x:t,y:i}=this.wrappedEngine.viewPortSize,{afterProjectionMatrix:n}=this.wrappedEngine.camera,s=n.elements[0],{maxDim:r}=this.wrappedEngine,a=i/((this.wrappedEngine.camera.top-this.wrappedEngine.camera.bottom)/2)*s/r;let o=function(e,t){if(!Number.isNaN(e)&&t){let i,n=e/t,s=0,r=0,a=1;if(n>=1){n=Math.floor(n);const e=n.toString();s=e.length,r=parseInt(e[0],10),a=10}else if(n<1&&n>0){for(a=.1,s=2;a**(s-1)>n;)s+=1;r=Math.floor(n/a**(s-1))}i=r>5?10:r>2?5:2;let o=i*a**(s-1);return o<1&&(o=Number(o.toFixed(s-1))),o<1e-9&&(o=1e-9),o}return 1}(i/5,a);const h=o*a;o*=this.wrappedFactor,(o>5e3||o<.01)&&(o=Number(o.toExponential()));const d=`${o}${this.unit}`;e.save(),e.font="Normal 12px Arial",e.setLineDash([]),e.fillStyle=this.frontColor,e.strokeStyle=this.frontColor,e.lineWidth=2,e.beginPath(),e.moveTo(t/2+h/2,i-30),e.lineTo(t/2+h/2,i-25),e.lineTo(t/2-h/2,i-25),e.lineTo(t/2-h/2,i-30),e.stroke();const p=e.measureText(d);e.fillText(d,t/2-p.width/2,i-33),e.restore()}}updateOverlap=()=>{this.wrappedEngine?.invalidOverlap()};wrappedUnit="mm";get unit(){return this.wrappedUnit}set unit(e){this.wrappedUnit=e,this.updateOverlap()}wrappedFactor=1;get factor(){return this.wrappedFactor}set factor(e){this.wrappedFactor=e,this.updateOverlap()}}class ms{obj;wrappedAxisLocation=new a;originMatrixWorld=new t;bind(e){this.obj=e,It(e,this.onPreRendering,this.onPostRendering,10)}unbind(e){Bt(e,this.onPreRendering,this.onPostRendering),this.obj=void 0}get axisLocation(){return this.wrappedAxisLocation}set axisLocation(e){this.wrappedAxisLocation=e}onPreRendering=()=>{if(this.obj){this.originMatrixWorld=this.obj.matrixWorld;const e=(new Se).setFromMatrix4(this.obj.matrixWorld);if(new a(0,0,1).applyMatrix3(e).dot(new a(0,0,1))<0){let e=(new t).makeTranslation(-this.wrappedAxisLocation.x,-this.wrappedAxisLocation.y,-this.wrappedAxisLocation.z);e=(new t).makeScale(-1,1,1).multiply(e),e=(new t).makeTranslation(this.wrappedAxisLocation.x,this.wrappedAxisLocation.y,this.wrappedAxisLocation.z).multiply(e);const i=this.obj.matrixWorld.clone();this.obj.matrixWorld=i.multiply(e)}}};onPostRendering=()=>{this.obj&&(this.obj.matrixWorld=this.originMatrixWorld)}}class ws extends S{wrappedText;wrappedCharacterSpacing=0;wrappedTexture;mirrorOnFlipAction=new ms;zoomPreventAction=new Nt;wrappedSize=new r(0,0);wrappedPreventZoom=!1;wrappedMirrorOnFlip=!0;constructor(e,t,i,n=0){super(new o,new jt({mapArray:t.texture,color:i,side:K})),this.wrappedText=e,this.wrappedCharacterSpacing=n,this.wrappedTexture=t,this.frustumCulled=!1,this.updateText(),this.wrappedMirrorOnFlip&&this.mirrorOnFlipAction.bind(this),this.wrappedPreventZoom&&this.zoomPreventAction.bind(this)}get size(){return this.wrappedSize}get characterSpacing(){return this.wrappedCharacterSpacing}set characterSpacing(e){this.wrappedCharacterSpacing!==e&&(this.wrappedCharacterSpacing=e,this.updateText())}get preventZoom(){return this.wrappedPreventZoom}set preventZoom(e){this.wrappedPreventZoom!==e&&(this.wrappedPreventZoom=e,this.wrappedPreventZoom?this.zoomPreventAction.bind(this):this.zoomPreventAction.unbind(this))}get anchorPoint(){return new r(this.zoomPreventAction.anchorPoint.x,this.zoomPreventAction.anchorPoint.y)}set anchorPoint(e){this.zoomPreventAction.anchorPoint=new a(e.x,e.y,0)}get mirrorOnFlip(){return this.wrappedMirrorOnFlip}set mirrorOnFlip(e){this.wrappedMirrorOnFlip!==e&&(this.wrappedMirrorOnFlip=e,this.wrappedMirrorOnFlip?this.mirrorOnFlipAction.bind(this):this.mirrorOnFlipAction.unbind(this))}get text(){return this.wrappedText}set text(e){this.wrappedText!==e&&(this.wrappedText=e,this.updateText())}get texture(){return this.wrappedTexture}set texture(e){this.wrappedTexture!==e&&(this.wrappedTexture=e,this.updateText())}raycast(e,t){const{geometry:i,material:n,matrixWorld:s}=this;if(void 0===n)return;null!==i.boundingSphere&&void 0!==i.boundingBox||i.computeBoundingSphere();const r=i.boundingSphere?.clone();r.applyMatrix4(s);const o=e.ray.clone().recast(e.near);if(!1===r.containsPoint(o.origin)){const t=new a;if(null===o.intersectSphere(r,t))return;if(o.origin.distanceToSquared(t)>(e.far-e.near)**2)return}const h=s.clone().invert();o.copy(e.ray).applyMatrix4(h),null!==i.boundingBox&&void 0!==i.boundingBox&&!1===o.intersectsBox(i.boundingBox)||this.computeIntersections(e,t,o)}computeIntersections(e,t,i){let n;const{geometry:s,material:r}=this,{position:a,uv:o,uv1:h,normal:d}=s.attributes,{index:p,groups:l,drawRange:c}=s;if(null!==p)if(Array.isArray(r))for(let s=0,a=l.length;st.far?null:{object:this,distance:d,point:h.clone()}}checkGeometryIntersection(e,t,i,n,s,o,h,d,p){const l=new a,c=new a,u=new a;this.getVertexPosition(h,l),this.getVertexPosition(d,c),this.getVertexPosition(p,u);const g=new a,f=this.checkIntersection(e,t,i,l,c,u,g);if(f){const e=new r,t=new r,s=new r;if(n&&(e.fromBufferAttribute(n,h),t.fromBufferAttribute(n,d),s.fromBufferAttribute(n,p),f.uv=Y.getInterpolation(g,l,c,u,e,t,s,new r)),o){const e=new a,t=new a,n=new a;e.fromBufferAttribute(o,h),t.fromBufferAttribute(o,d),n.fromBufferAttribute(o,p),f.normal=Y.getInterpolation(g,l,c,u,e,t,n,new a),f.normal.dot(i.direction)>0&&f.normal.multiplyScalar(-1)}const m={a:h,b:d,c:p,normal:new a,materialIndex:0};Y.getNormal(l,c,u,m.normal),f.face=m}return f}updateText(){Array.from(this.wrappedText).forEach((e=>{this.wrappedTexture.addChar(e)})),this.wrappedTexture.updateTexture();const e=this.wrappedTexture.generateGeometry(this.wrappedText,this.wrappedCharacterSpacing);this.geometry.setAttribute("position",new n(e.positions,3)),this.geometry.setAttribute("uv",new n(e.uvs,2)),this.geometry.setAttribute("mapIndex",new Te(e.mapIndexes,1)),this.geometry.setIndex(e.indexes),this.mirrorOnFlipAction.axisLocation.set(e.size.x/2,0,0),this.wrappedSize=e.size}}class vs{font;size;textureWidth;textureHeight;canvas;ctx;cursor=new r(1,1);maxCharHeight=0;textureMap=new Map;constructor(e,t,i,n){if(this.font=e,this.size=t,this.textureWidth=i,this.textureHeight=n,this.canvas=st(i,n),this.ctx=this.canvas.getContext("2d"),!this.ctx)throw Error("no context");this.ctx.antialias="subpixel",this.ctx.imageSmoothingEnabled=!0,this.ctx.textBaseline="top",this.ctx.textAlign="left",this.ctx.font=`Normal ${this.size}px ${this.font}`,this.ctx.fillStyle="rgba(255, 0, 0, 255)",this.ctx.textDrawingMode="glyph"}addChar(e){const t=this.ctx.measureText(e);if(t.width<=0)throw Error("un-printable character");const i=Math.ceil(t.width),n=new r(0,0);if(t.actualBoundingBoxLeft>0&&(n.x=t.actualBoundingBoxLeft),t.actualBoundingBoxAscent>0&&(n.y=t.actualBoundingBoxAscent),this.cursor.x+n.x+i>this.textureWidth&&(this.cursor.x=1,this.cursor.y+=this.maxCharHeight+1,this.maxCharHeight=0,this.cursor.y+t.actualBoundingBoxDescent+n.y>this.textureHeight))return!1;t.actualBoundingBoxDescent+n.y>this.maxCharHeight&&(this.maxCharHeight=t.actualBoundingBoxDescent+n.y),this.ctx.fillText(e,this.cursor.x+n.x,this.cursor.y+n.y);const s=new Z(new r(this.cursor.x-t.actualBoundingBoxLeft+n.x,this.cursor.y-t.actualBoundingBoxAscent+n.y),new r(this.cursor.x+t.actualBoundingBoxRight+n.x,this.cursor.y+t.actualBoundingBoxDescent+n.y)),a=new Z(new r(-t.actualBoundingBoxLeft,-t.actualBoundingBoxDescent),new r(t.actualBoundingBoxRight,t.actualBoundingBoxAscent));return s.min.divideScalar(this.textureWidth),s.max.divideScalar(this.textureWidth),this.textureMap.set(e,{uv:s,position:a,width:i}),this.cursor.x+=i+n.x+1,!0}reset(){this.ctx.clearRect(0,0,this.textureWidth,this.textureHeight),this.cursor.x=0,this.cursor.y=0,this.maxCharHeight=0,this.textureMap.clear()}getImageData(){const e=this.canvas.getContext("2d");if(!e)throw Error("no context");return e.getImageData(0,0,this.canvas.width,this.canvas.width)}}class xs{font;size;textureWidth;textureHeight;currentIndex=0;textureMap=new Map;texture;generator;constructor(e,t,i=1024,n=1024){this.texture=new Ce(void 0,i,n,1),this.texture.format=F,this.texture.wrapS=I,this.texture.wrapT=I,this.texture.magFilter=_e,this.texture.minFilter=_e,this.font=e,this.size=t,this.textureWidth=i,this.textureHeight=n,this.generator=new vs(this.font,this.size,this.textureWidth,this.textureHeight),this.addAsciiCodes()}addChar(e){if(this.textureMap.has(e))return;this.generator.addChar(e)||(this.updateTexture(),this.currentIndex+=1,this.generator.reset(),this.generator.addChar(e));const t=this.generator.textureMap.get(e);this.textureMap.set(e,{mapIndex:this.currentIndex,charInfo:t})}updateTexture(){const e=this.texture.image;let t;if(!e.data||e.depth<=this.currentIndex){if(t=new Uint8Array(this.textureWidth*this.textureHeight*(this.currentIndex+1)),e.data)for(let i=0;i{const h=this.textureMap.get(e);if(h){const{uv:e,position:d,width:p}=h.charInfo,{mapIndex:l}=h;i.push(d.min.x+o.x,d.min.y,0),i.push(d.max.x+o.x,d.min.y,0),i.push(d.min.x+o.x,d.max.y,0),i.push(d.max.x+o.x,d.max.y,0),n.push(e.min.x,e.max.y),n.push(e.max.x,e.max.y),n.push(e.min.x,e.min.y),n.push(e.max.x,e.min.y),a.push(4*r,4*r+1,4*r+2,4*r+2,4*r+1,4*r+3),s.push(l,l,l,l),o.x+=p+t,o.y=Math.max(o.y,d.max.y)}})),{positions:i,uvs:n,mapIndexes:s,indexes:a,size:new r(o.x,o.y)}}addAsciiCodes(){[9,...it(32,126)].forEach((e=>{const t=String.fromCharCode(e);this.addChar(t)})),this.updateTexture()}}class ys{renderOrder=Number.MAX_VALUE;scene;camera;canvas;sprite;size=new r(0,0);updateRequired=!1;drawers=[];init(){this.camera=new e(-1,1,1,-1,1,2),this.camera.position.set(0,0,1),this.canvas=st(1,1);const t=new be(this.canvas);t.minFilter=_e,this.sprite=new ye,this.sprite.material=new Me({map:t}),this.sprite.scale.set(2,2,2),this.sprite.position.set(0,0,0),this.scene=new A,this.scene.add(this.sprite)}update(){if(!this.canvas||!this.scene)throw Error("not initialized.");this.canvas.width=this.size.x,this.canvas.height=this.size.y;const e=this.canvas.getContext("2d");if(e&&(e.clearRect(0,0,this.canvas.width,this.canvas.height),this.drawers.forEach((t=>{t.draw(e)}))),this.sprite){const e=new be(this.canvas);e.minFilter=_e,this.sprite.material.dispose(),this.sprite.material=new Me({map:e})}}resize(e,t){if(!this.camera||!this.sprite)throw new Error("not initialized.");this.size.set(e,t);const i=e/t;this.camera.left=-i,this.camera.right=i,this.camera.updateProjectionMatrix(),this.sprite.scale.set(2*i,2,2),this.update()}render(e){if(!this.scene||!this.camera)throw new Error("not initialized.");this.updateRequired&&(this.update(),this.updateRequired=!1),this.drawers.length>0&&(e.clearDepth(),e.render(this.scene,this.camera))}invalidate(){this.updateRequired=!0}hitTest(e,t,i,n){if(this.canvas){this.canvas.width=this.size.x,this.canvas.height=this.size.y;const s=this.canvas.getContext("2d");if(s)return this.drawers.reduce(((r,a)=>{const o=a.hitTest?.(s,e,t,n,i);return o?[...r||[],...o]:r}),void 0)}}}class Ms{}class bs{factories=[];register(e){if(this.factories.find((t=>t===e)))throw Error("factory registered.");this.factories.push(e)}async createGeometry(e,t){const i=this.factories.find((t=>t.isMatch(e)));if(!i)throw Error("no mesh factory");return i.createGeometry(e,t)}}function Es(e,t,i){const{width:n,height:s}=e;let r,a=1;switch(e.texture.format){case E:a=4;break;case F:a=1;break;default:throw Error("Unsupported format")}switch(e.texture.type){case Re:r=new Uint8Array(n*s*a);break;case O:r=new Float32Array(n*s*a);break;default:throw Error("Unsupported type")}if(t.readRenderTargetPixels(e,0,0,n,s,r),function(e,t,i){const n=Math.floor(i/2);let s;for(let r=0;r0&&(this.wrappedCursorTypeStack.pop(),this.wrappedCursorTypeStack.length>0&&(this.wrappedCursorType=this.wrappedCursorTypeStack[this.wrappedCursorTypeStack.length-1])):this.wrappedCursorTypeStack.push(e),this.wrappedCursorType){case fn.CROSS:this.wrappedRenderer.domElement.style.cursor="crosshair";break;case fn.HAND:this.wrappedRenderer.domElement.style.cursor="move";break;case fn.ARROW:this.wrappedRenderer.domElement.style.cursor="pointer";break;default:this.wrappedRenderer.domElement.style.cursor="default"}}addActionHandler(e){this.wrappedActionHandlers.push(e),this.wrappedActionHandlers.sort(((e,t)=>e.priority-t.priority))}removeActionHandler(e){const t=this.wrappedActionHandlers.indexOf(e);t>=0&&this.wrappedActionHandlers.splice(t,1)}addRenderHandler(e){this.wrappedRenderHandlers.push(e),this.wrappedRenderHandlers.sort(((e,t)=>e.renderOrder-t.renderOrder))}removeRenderHandler(e){const t=this.wrappedRenderHandlers.indexOf(e);t>=0&&this.wrappedRenderHandlers.splice(t,1)}addOverlayLayer(e){if(!this.overlapLayer)throw Error("not initialized.");this.overlapLayer.drawers.push(e)}removeOverlayLayer(e){if(!this.overlapLayer)throw Error("not initialized.");const t=this.overlapLayer.drawers.indexOf(e);t>=0&&this.overlapLayer.drawers.splice(t,1)}get camera(){if(!this.wrappedCamera)throw Error("not initialized.");return this.wrappedCamera}set camera(e){this.wrappedCamera!==e&&(this.wrappedCamera.cameraChangedEvent.remove(this.onCameraUpdate),this.wrappedCamera=e,this.wrappedCamera.cameraChangedEvent.add(this.onCameraUpdate),this.onCameraUpdate())}get maxDim(){return this.wrappedMaxDim}capturePointer(e){if(!this.wrappedRenderer)throw new Error("not initialized.");this.capturedPointerId>=0||(this.wrappedRenderer.domElement.setPointerCapture?.(e),this.capturedPointerId=e)}releasePointer(){if(!this.wrappedRenderer)throw new Error("not initialized.");this.capturedPointerId>=0&&(this.wrappedRenderer.domElement.releasePointerCapture?.(this.capturedPointerId),this.capturedPointerId=-1)}set enableClipping(e){if(!this.wrappedRenderer)throw new Error("not initialized.");this.wrappedRenderer.localClippingEnabled=e}get enableClipping(){if(!this.wrappedRenderer)throw new Error("not initialized.");return this.wrappedRenderer.localClippingEnabled}renderFrame(){if(!this.wrappedCamera)throw new Error("not initialized.");this.render(this.wrappedCamera),this.stats?.update()}invalidate(){this.leftAnimatingFrame=30}animate=()=>{requestAnimationFrame(this.animate),this.leftAnimatingFrame>0&&this.animating&&(this.animationEvent.trigger(),this.postComposer?this.postComposer.render():this.render(this.wrappedCamera),this.leftAnimatingFrame-=1,this.stats?.update())};startAnimate(){if(!this.wrappedCamera)throw new Error("not initialized.");this.animating||(this.animating=!0),this.animate()}stopAnimate(){this.animating=!1}exportImage(e=void 0,t=void 0,i=void 0,n=void 0,s=void 0,r=void 0,a=void 0){const o=this.wrappedRenderer;if(!o)throw new Error("not initialized.");const h=e||this.width,d=t||this.height,p={data:void 0};return this.renderScene(h,d,(e=>{p.data=Es(e,o,a)}),{type:Re,stencilBuffer:!0,samples:4},i,n,s,r),p.data}renderTargetAndReadFloat(e,t,i,n,s,r,a,o){const h=new Float32Array(4*(n??1)*(s??1)),d=this.wrappedRenderer;if(!d)throw new Error("not initialized.");return this.renderScene(this.viewPortSize.x,this.viewPortSize.y,(e=>{d.readRenderTargetPixels(e,t,e.height-i-(s??1),n??1,s??1,h)}),{type:O,stencilBuffer:!0},e,r,a,o),h}renderScene(e,t,i,n=void 0,s=void 0,a=void 0,o=void 0,h=void 0){if(!this.wrappedRenderer||!this.wrappedCamera)throw new Error("not initialized.");const{wrappedRenderer:d}=this,p=new r;d.getSize(p),this.resize(e,t,void 0===s);const l=new P(e,t,n);let c;if(d.setRenderTarget(l),void 0!==h&&d.setClearColor(new g(h.x,h.y,h.z),h.w),o&&(c=new ie,d.getViewport(c),d.setViewport(o)),void 0===s)this.render(this.wrappedCamera);else if(s instanceof zi)d.autoClear=!1,d.clear(),s.render(d,a||this.camera),d.autoClear=!0;else{const e=s instanceof Array?s:[s];d.autoClear=!1,d.clear(),e.forEach((e=>{d.render(e,void 0===a?this.wrappedCamera:a)})),d.autoClear=!0}c&&d.setViewport(c),this.resize(p.width,p.height,void 0===s),i(l),d.setRenderTarget(null),l.dispose()}get adaptMatrix(){return this.wrappedAdaptMatrix}get rotationMatrix(){return this.wrappedRotateMatrix}set rotationMatrix(e){this.wrappedRotateMatrix=e,this.updateRootObjectMatrix(),this.invalidate(),this.rotationChangedEvent.trigger(e)}get matrix(){return this.wrappedRotateMatrix.clone().multiply(this.wrappedAdaptMatrix)}resetView(){const e=this.wrappedCamera;e.afterProjectionMatrix=new t,this.rotationMatrix=new t,e.raiseCameraChangeEvent()}invalidOverlap(){this.overlapLayer.invalidate(),this.invalidate()}resize(e,t,i){if(!this.wrappedCamera||!this.wrappedRenderer)throw Error("Not initialized.");this.wrappedWidth===e&&this.wrappedHeight===t||(this.wrappedWidth=Math.round(e),this.wrappedHeight=Math.round(t),this.wrappedCamera instanceof lt?this.wrappedCamera.aspect=this.wrappedWidth/this.wrappedHeight:(this.wrappedCamera.left=-this.wrappedWidth/this.wrappedHeight*dt,this.wrappedCamera.right=this.wrappedWidth/this.wrappedHeight*dt),this.wrappedCamera.updateProjectionMatrix(),(void 0===i||i)&&(this.wrappedRenderer.setSize(this.wrappedWidth,this.wrappedHeight),this.postComposer?.setSize(this.wrappedWidth,this.wrappedHeight)),this.overlapLayer.resize(this.wrappedWidth,this.wrappedHeight),this.sizeChangedEvent.trigger({width:this.wrappedWidth,height:this.wrappedHeight}),(void 0===i||i)&&this.invalidate())}updateBackground(e){if(e instanceof Array){const t=e,i=Si.generateTexture1d(t,!0);i.needsUpdate=!0,i.magFilter=_e,i.minFilter=_e,this.wrappedScenes.defaultScene.scene.background=i}else this.wrappedScenes.defaultScene.scene.background=e;this.invalidate()}onObjectAdd=e=>{e&&(this.updateDomainRange(),this.invalidate())};onObjectRemove=e=>{e&&(this.updateDomainRange(),this.invalidate())};updateDomainRange(){const e=this.calculateDomainRange();qi(this.wrappedDomainRange,e)||(this.wrappedDomainRange=e,this.wrappedUserDefinedAdaptRange||(this.adaptRange=e),this.domainRangeChangedEvent.trigger(this.domainRange))}pointerDownEventHandler=e=>{for(let t=0;t{for(let t=0;t{for(let t=0;t{for(let t=0;t{for(let t=0;t{for(let t=0;t{const{renderer:t}=this;if(!t)throw new Error("not initialized.");t.autoClear=!1,t.clear(),this.wrappedScenes.render(t,e),this.wrappedRenderHandlers.forEach((e=>{e.render(t)})),t.autoClear=!0};hitTest(e,t,i,n){if(!this.wrappedCamera)throw new Error("not initialized.");const s=[];s.push(...this.overlapLayer.hitTest(e,t,n,i)||[]);const o=new Ss;if(o.layers.set(2),this.camera.updateWorldMatrix(!1,!0),o.setFromCamera(new r(e/this.viewPortSize.x*2-1,-t/this.viewPortSize.y*2+1),this.wrappedCamera),void 0!==n){const e=new a,t=new X,i=new a;this.wrappedCamera.afterProjectionMatrix.decompose(e,t,i);const s=2*n/this.viewPortSize.y*(this.cameraType===mn.Orthographic?dt:1)*this.wrappedMaxDim/i.x;o.params.Line={threshold:s},o.params.Points={threshold:s}}this.rayCasterConfigCallback&&this.rayCasterConfigCallback(o,n),this.scenes.forEachObject((e=>(!i&&e.visible||i&&i(e)?(e.updateMatrixWorld(!0),e.layers.enable(2)):e.layers.disable(2),!0)));const{matrix:h}=this,d=h.invert(),p=[];return this.scenes.forEachScene((e=>{const t=this.scenes.findGroup(e,Lt);t.updateWorldMatrix(!1,!0);o.intersectObject(t).forEach((t=>{const i=this.rayCastResultConvertHub.toHitTestResult(t,d);i.scene=e,p.push(i)}))})),p.sort(((e,t)=>e.distance-t.distance)),s.push(...p),s.length>0?s:null}calculateDomainRange(){let e;return this.scenes.forEachObject(((t,...i)=>{if(_i(t)){const n={path:i,filtered:!1};if(this.autoScaleFilterEvent.trigger(n),!n.filtered){const i=t;i.matrixAutoUpdate&&i.updateMatrix();let n,s=i.matrix,{parent:r}=i;for(;null!==r&&r.name!==Lt;)s=s.multiplyMatrices(r.matrix,s),r=r.parent;if(i instanceof d){const e=i;e.boundingBox||e.computeBoundingBox(),n=e.boundingBox}else{const e=i.geometry;e&&(e.boundingBox||e.computeBoundingBox(),n=e.boundingBox?.clone())}n&&(n.applyMatrix4(s),e?e.union(n):e=n)}}return!0}),!0),e}updateScales(){if(this.adaptRange){const e=Ts.calculateAdaptMatrix(this.adaptRange);this.wrappedAdaptMatrix=e.mat,this.wrappedMaxDim=e.maxDim}else this.wrappedAdaptMatrix=new t,this.wrappedMaxDim=1;this.updateRootObjectMatrix(),this.invalidate()}static calculateAdaptMatrix(e){const i=new a;e.getCenter(i);const n=new a;e.getSize(n);const s=Math.max(n.x,n.y,n.z),r=new t;r.makeTranslation(-i.x,-i.y,-i.z);const o=new t;return o.makeScale(2/s,2/s,2/s),o.multiply(r),{mat:o,maxDim:s}}updateRootObjectMatrix(){const{matrix:e}=this;this.wrappedScenes.updateWorldMatrix(e)}set cameraType(e){if(this.cameraType!==e){const t=this.wrappedWidth/this.wrappedHeight,i=e===mn.Perspective?new lt(15,t,1,100):new pt(-t*dt,t*dt,1.732,-1.732,0,100);i.position.set(0,0,10),i.updateMatrixWorld(!0),this.camera=i,this.onCameraUpdate()}}get cameraType(){return this.wrappedCamera instanceof pt?mn.Orthographic:mn.Perspective}onCameraUpdate=()=>{this.cameraChangeEvent.trigger(void 0),this.invalidate()};resetViewEvent=new ht;meshVisibleChangedEvent=new ht;meshOpacityChangedEvent=new ht;meshColorChangedEvent=new ht;get root(){return this.wrappedScenes.defaultRoot}addMesh(e){this.scenes.addObject(Ot,e,Lt,Dt)}removeMesh(e){return void 0!==this.scenes.removeObject(Ot,Lt,Dt,e)}setVisible(e,t){let i=!1;return this.scenes.forEachObject((n=>{if(n.name===t){const t=n;t.visible=e,this.meshVisibleChangedEvent.trigger({target:t.name,visible:e}),i=!0}return!0})),i&&this.invalidate(),i}setMeshColor(e,t){let i=!1;return this.scenes.forEachObject((n=>{if(n.name===t){if(_i(n)){const t=n,i=Array.isArray(t.material)?t.material[0]:t.material;i&&(i.color=e),this.meshColorChangedEvent.trigger({target:n.name,color:e})}i=!0}return!0})),i&&this.invalidate(),i}setMeshOpacity(e,t){let i=!1;return this.scenes.forEachObject((n=>{if(n.name===t){if(_i(n)){const t=n,i=Array.isArray(t.material)?t.material[0]:t.material;i&&(i.opacity=e,i.transparent=e<.999,i.needsUpdate=!0,this.meshOpacityChangedEvent.trigger({target:n.name,opacity:e}))}i=!0}return!0})),i&&this.invalidate(),i}clearMeshes(){const e=this.scenes.findGroup(Ot,Lt,Dt);zi.disposeGroup(e)}findFirstObject(e){return this.scenes.findGroup(Ot,Lt,Dt).children.find(e)}findMesh(e){return this.findFirstObject((t=>t instanceof S&&t.name===e))}filterMeshByUserDataKey(e,t){return this.scenes.findGroup(Ot,Lt,Dt).children.filter((i=>i.userData[e]===t))}findGeometry(e){const t=this.findMesh(e);if(t)return t.geometry}getAllTargetModal(){return this.scenes.findGroup(Ot,Lt,Dt)}}class Cs{type;cancelBubble;returnValue;bubbles;cancelable;composed;currentTarget;defaultPrevented;eventPhase;isTrusted;srcElement;target;timeStamp;NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;constructor(e,t){this.type=e,this.bubbles=t?.bubbles||!1,this.cancelable=t?.bubbles||!1,this.cancelBubble=!1,this.returnValue=!0,this.composed=!1,this.currentTarget=null,this.defaultPrevented=!1,this.eventPhase=0,this.isTrusted=!1,this.srcElement=null,this.target=null,this.timeStamp=0}initEvent(e,t,i){this.type=e,this.bubbles=t||!1,this.cancelable=i||!1}composedPath(){return[]}preventDefault(){}stopImmediatePropagation(){}stopPropagation(){}}class _s extends Cs{detail;view;which;constructor(e,t){super(e,t),this.detail=t?.detail||0,this.view=t?.view||null,this.which=t?.which||0}initUIEvent(e,t,i,n,s){this.initEvent(e,t,i),this.view=n||null,this.detail=s||0}}class Rs extends _s{altKey;button;buttons;clientX;clientY;ctrlKey;layerX=0;layerY=0;metaKey;movementX;movementY;offsetX;offsetY;pageX;pageY;relatedTarget;screenX;screenY;shiftKey;x;y;constructor(e,t){super(e,t),this.altKey=t?.altKey||!1,this.button=t?.button||0,this.buttons=t?.buttons||0,this.clientX=t?.clientX||0,this.clientY=t?.clientY||0,this.ctrlKey=t?.ctrlKey||!1,this.metaKey=t?.metaKey||!1,this.movementX=t?.movementX||0,this.movementY=t?.movementY||0,this.relatedTarget=t?.relatedTarget||null,this.screenX=t?.screenX||0,this.screenY=t?.screenY||0,this.shiftKey=t?.shiftKey||!1,this.offsetX=t?.clientX||0,this.offsetY=t?.clientY||0,this.pageX=t?.screenX||0,this.pageY=t?.screenY||0,this.x=t?.clientX||0,this.y=t?.clientY||0}getModifierState(){throw Error("Not implemented")}initMouseEvent(e,t,i,n,s,r,a,o,h,d,p,l,c,u,g){this.initUIEvent(e,t,i,n,s),this.screenX=r,this.screenY=a,this.clientX=o,this.clientY=h,this.ctrlKey=d,this.altKey=p,this.shiftKey=l,this.metaKey=c,this.button=u,this.relatedTarget=g}}class As extends Rs{height;isPrimary;pointerId;pointerType;pressure;tangentialPressure;tiltX;tiltY;twist;width;coalescedEvents=[];predictedEvents=[];constructor(e,t){super(e,t),this.height=t?.height||0,this.isPrimary=t?.isPrimary||!1,this.pointerId=t?.pointerId||0,this.pointerType=t?.pointerType||"",this.pressure=t?.pressure||0,this.tangentialPressure=t?.tangentialPressure||0,this.tiltX=t?.tiltX||0,this.tiltY=t?.tiltY||0,this.twist=t?.twist||0,this.width=t?.width||0}getCoalescedEvents(){return this.coalescedEvents}getPredictedEvents(){return this.predictedEvents}}class Ps extends Rs{deltaMode;deltaX;deltaY;deltaZ;DOM_DELTA_PIXEL=0;DOM_DELTA_LINE=1;DOM_DELTA_PAGE=2;constructor(e,t){super(e,t),this.deltaMode=t?.deltaMode||0,this.deltaX=t?.deltaX||0,this.deltaY=t?.deltaY||0,this.deltaZ=t?.deltaZ||0}}class Os extends _s{altKey;charCode;code;ctrlKey;isComposing;key;keyCode;location;metaKey;repeat;shiftKey;DOM_KEY_LOCATION_STANDARD=0;DOM_KEY_LOCATION_LEFT=1;DOM_KEY_LOCATION_RIGHT=2;DOM_KEY_LOCATION_NUMPAD=3;constructor(e,t){super(e,t),this.altKey=t?.altKey||!1,this.charCode=t?.charCode||0,this.code=t?.code||"",this.ctrlKey=t?.ctrlKey||!1,this.isComposing=t?.isComposing||!1,this.key=t?.key||"",this.keyCode=t?.keyCode||0,this.location=t?.location||0,this.metaKey=t?.metaKey||!1,this.repeat=t?.repeat||!1,this.shiftKey=t?.shiftKey||!1}getModifierState(){return!1}initKeyboardEvent(e,t,i,n,s,r,a,o,h,d){this.initUIEvent(e,t,i,n,0),this.key=s||"",this.location=r||0,this.ctrlKey=a||!1,this.altKey=o||!1,this.shiftKey=h||!1,this.metaKey=d||!1}}function Ls(e,i,n,s){const r=new t;r.makeTranslation(i,n,0),r.scale(new a(s,s,1)),r.multiply((new t).makeTranslation(-i,-n,0));e.afterProjectionMatrix=r.multiply(e.afterProjectionMatrix)}function Ds(e=1920,t=1080,i=void 0){const n=new Ts,s=document.createElement("div");return n.init(s,e,t),n.updateBackground(i||new g(0)),n}function zs(e,t){const i=e,n=new As("pointerdown",t);i.pointerDownEventHandler(n)}function Is(e,t){const i=e,n=new As("pointerup",t);i.pointerUpEventHandler(n)}function Bs(e,t){const i=e,n=new As("pointermove",t);i.pointerMoveEventHandler(n)}function Fs(e,t){const i=e,n=new Ps("wheel",t);i.wheelEventHandler(n)}function Ns(e,t){const i=e,n=new Os("keydown",t);i.keyDownEventHandler(n)}function Us(e,t){const i=e,n=new Os("keyup",t);i.keyUpEventHandler(n)}var Gs;!function(e){e[e.TopLeft=0]="TopLeft",e[e.TopMiddle=1]="TopMiddle",e[e.TopRight=2]="TopRight",e[e.CenterLeft=3]="CenterLeft",e[e.Center=4]="Center",e[e.CenterRight=5]="CenterRight",e[e.BottomLeft=6]="BottomLeft",e[e.BottomMiddle=7]="BottomMiddle",e[e.BottomRight=8]="BottomRight"}(Gs||(Gs={}));class Hs{wrappedConfig;wrappedPoints;wrappedHeadArrow;wrappedTailArrow;wrappedVisible=!0;name;updateEvent=new ht;constructor(e,t,i,n,s){this.name=s,this.wrappedConfig=e,this.wrappedPoints=t,this.wrappedHeadArrow=i,this.wrappedTailArrow=n}get config(){return this.wrappedConfig}set config(e){if(e!==this.wrappedConfig){const t=this.wrappedConfig;this.wrappedConfig=e,this.updateEvent.trigger({source:this,property:"config",oldValue:t})}}get points(){return this.wrappedPoints}set points(e){if(e!==this.wrappedPoints){const t=this.wrappedPoints;this.wrappedPoints=e,this.updateEvent.trigger({source:this,property:"points",oldValue:t})}}get headArrow(){return this.wrappedHeadArrow}set headArrow(e){if(e!==this.wrappedHeadArrow){const t=this.wrappedHeadArrow;this.wrappedHeadArrow=e,this.updateEvent.trigger({source:this,property:"headArrow",oldValue:t})}}get tailArrow(){return this.wrappedTailArrow}set tailArrow(e){if(e!==this.wrappedTailArrow){const t=this.wrappedTailArrow;this.wrappedTailArrow=e,this.updateEvent.trigger({source:this,property:"tailArrow",oldValue:t})}}get visible(){return this.wrappedVisible}set visible(e){if(e!==this.wrappedVisible){const t=this.wrappedVisible;this.wrappedVisible=e,this.updateEvent.trigger({source:this,property:"visible",oldValue:t})}}}class ks{id;name;type;visible=!0;constructor(e,t,i){this.id=Fe(),this.type=e,this.name=t,this.visible=void 0===i||i}}class js extends ks{children=[];constructor(e){super("group",e)}add(e){this.children.push(e)}remove(e){const t=this.children.indexOf(e);t>-1&&this.children.splice(t,1)}ensureGroup(...e){let t=this;for(let i=0;it.name===e[i]));if(n){if("group"!==n.type)throw new Error("Invalid path");t=n}else{const n=new js(e[i]);t.add(n),t=n}}return t}getDescendants(...e){let t=this;for(let i=0;it.name===e[i]))}return t}enumerateDescendants(e,...t){this.children.forEach((i=>{if(e(i,...t,i.name||""),"group"===i.type){const n=i;n.enumerateDescendants(e,...t,n.name||"")}}))}}class Vs{color;size;font;align;baseline;constructor(e){this.color=e.color,this.size=e.size,this.font=e.font,this.align=e.align,this.baseline=e.baseline}apply(e){e.fillStyle=`#${this.color}`,e.textAlign=this.align,e.font=`${this.size}px ${this.font}`,e.textBaseline=this.baseline}}class Ws extends ks{config;text;location;direction;constructor(e,t,i,n,s){super("text",s),this.config=e,this.text=t,this.location=i,this.direction=n||0}draw(e){const[t,i]=this.location;e.save(),e.translate(t,i),e.rotate(this.direction),e.fillText(this.text,0,0),e.restore()}hitTest(e,t,i){const[n,s]=this.location,a=e.measureText(this.text),o=new Z(new r(-a.actualBoundingBoxLeft,-a.actualBoundingBoxAscent),new r(a.actualBoundingBoxRight,a.actualBoundingBoxDescent)),h=new r(t-n,i-s),d=(new Se).rotate(this.direction);return h.applyMatrix3(d),o.containsPoint(h)}}class Ks{color;width;dashPattern;arrow;constructor(e){this.color=e.color,this.width=e.width,this.dashPattern=e.dashPattern,this.arrow=e.arrow}apply(e){e.strokeStyle=`#${this.color}`,e.lineWidth=this.width,e.fillStyle=`#${this.color}`,this.dashPattern&&e.setLineDash(this.dashPattern)}}class Ys extends ks{config;points;headArrow;tailArrow;constructor(e,t,i,n,s){super("line",s),this.config=e,this.points=t,this.headArrow=i,this.tailArrow=n}draw(e){this.points.length>=2&&(e.beginPath(),e.moveTo(this.points[0][0],this.points[0][1]),this.points.slice(1).forEach((t=>{e.lineTo(t[0],t[1])})),e.stroke(),this.headArrow&&this.drawArray(e,this.points[0],this.points[1]),this.tailArrow&&this.drawArray(e,this.points[this.points.length-1],this.points[this.points.length-2]))}hitTest(e,t,i,n){const s=this.points.length-1;if(s>=1)for(let e=0;e=-(n||0))return!0}return!1}drawArray(e,t,i){if(this.config.arrow){const n=new r(t[0],t[1]),s=new r(i[0],i[1]).sub(n).normalize(),{length:a,width:o}=this.config.arrow,h=n.clone().add(s.clone().multiplyScalar(a)),d=s.clone().rotateAround(new r(0,0),Math.PI/2),p=d.clone().multiplyScalar(o/2).add(h),l=d.clone().multiplyScalar(-o/2).add(h);e.beginPath(),e.moveTo(n.x,n.y),e.lineTo(p.x,p.y),e.lineTo(l.x,l.y),e.closePath(),e.fill()}}}class Xs{texts=new rt;lines=new rt;cacheDirty=!1;root=new js;constructor(){this.root.name="root"}addObject(e,...t){const i=this.root.getDescendants(...t);if(!i||"group"!==i.type)throw new Error("Invalid path");i.children.push(e),this.cacheDirty=!0}removeObjects(...e){const t=this.root.getDescendants(...e.slice(0,e.length-1));if(!t||"group"!==t.type)throw new Error("Invalid path");const i=t.children.findIndex((t=>t.name===e[e.length-1]));i>=0&&t.children.splice(i,1),this.cacheDirty=!0}invalidate(){this.cacheDirty=!0}hitTest(e,t,i,n,s){this.cacheDirty&&(this.updateCache(),this.cacheDirty=!1);const r=[];return Oi(this.lines.keys(),(a=>{a.apply(e);const o=this.lines.get(a);o&&o.forEach((a=>{if(n&&!n(a))return;a.hitTest(e,t,i,s)&&r.push({type:"annotation-line",object:a})}))})),Oi(this.texts.keys(),(s=>{s.apply(e);const a=this.texts.get(s);a&&a.forEach((s=>{if(n&&!n(s))return;s.hitTest(e,t,i)&&r.push({type:"annotation-text",object:s})}))})),r.length>0?r:void 0}draw(e){this.cacheDirty&&(this.updateCache(),this.cacheDirty=!1),Oi(this.texts.keys(),(t=>{t.apply(e);const i=this.texts.get(t);i&&i.forEach((t=>{t.draw(e)}))})),Oi(this.lines.keys(),(t=>{t.apply(e);const i=this.lines.get(t);i&&i.forEach((t=>{t.draw(e)}))}))}updateCache(){this.texts.clear(),this.lines.clear(),this.root.enumerateDescendants((e=>{if("text"===e.type){const t=e;this.texts.set(t.config,t)}else if("line"===e.type){const t=e;this.lines.set(t.config,t)}}))}}const qs="annotation-lines";class Zs{engine;annotations;group=new js(qs);configMap=new Map;config2Line2D=new rt;lineMap=new at;bind(e,t){e!==this.engine&&(this.annotations&&this.annotations.removeObjects(qs),this.engine&&(this.engine.rotationChangedEvent.remove(this.update),this.engine.cameraChangeEvent.remove(this.update),this.engine.adaptRangeChangedEvent.remove(this.update),this.engine.sizeChangedEvent.remove(this.update)),this.engine=e,this.annotations=t,this.annotations&&this.annotations.addObject(this.group),this.engine&&(this.engine.rotationChangedEvent.add(this.update),this.engine.cameraChangeEvent.add(this.update),this.engine.adaptRangeChangedEvent.add(this.update),this.engine.sizeChangedEvent.add(this.update)),this.update())}addLine(e){const{config:t}=e;let i=this.configMap.get(t);i||(i=this.addConfig(t));const n=new Ys(i,e.points.map((e=>[e.x,e.y])),e.headArrow,e.tailArrow,e.name);n.visible=e.visible,this.lineMap.set(e,n),this.config2Line2D.set(t,e),this.engine&&this.updateLocation(e),this.group.add(n),this.annotations?.invalidate(),e.updateEvent.add(this.onLineUpdate),this.engine?.invalidOverlap()}removeLine(e){e.updateEvent.remove(this.onLineUpdate);const{config:t}=e;this.config2Line2D.deleteValue(e)&&this.removeConfig(t);const i=this.lineMap.get(e);i&&this.group.remove(i),this.lineMap.deleteKey(e),this.annotations?.invalidate(),this.engine?.invalidOverlap()}queryLine(e){return this.lineMap.getKey(e)}update=()=>{this.engine&&(Oi(this.lineMap.keys(),(e=>{this.updateLocation(e)})),this.engine.invalidate())};onLineUpdate=e=>{if(e){const{property:t,oldValue:i}=e,n=e.source,s=new Map;Array.isArray(t)?t.forEach(((e,t)=>{s.set(e,i[t])})):s.set(t,i);const r=this.lineMap.get(n);if(s.size>0){if(s.has("config")){const e=s.get("config");this.config2Line2D.deleteValue(n)&&this.removeConfig(e);const t=n.config,i=this.lineMap.get(n);if(this.configMap.has(t))i.config=this.configMap.get(t);else{const e=this.addConfig(t);this.config2Line2D.set(t,n),i.config=e}}s.has("visible")&&(r.visible=n.visible),s.has("headArrow")&&(r.headArrow=n.headArrow),s.has("tailArrow")&&(r.tailArrow=n.tailArrow),s.has("points")&&this.updateLocation(n)}}};addConfig(e){if(this.configMap.has(e))throw Error("config already exists");const t=Zs.createConfig2D(e);return this.configMap.set(e,t),e.updateEvent.add(this.onConfigUpdate),t}removeConfig(e){this.configMap.has(e)&&(e.updateEvent.remove(this.onConfigUpdate),this.configMap.delete(e))}onConfigUpdate=e=>{if(e){const{source:t,property:i}=e,n=this.configMap.get(t);if(!n)throw Error("config not found");const s=new Set;Array.isArray(i)?i.forEach((e=>{s.add(e)})):s.add(i);this.config2Line2D.get(t)&&(s.has("color")&&(n.color=t.color.getHexString()),s.has("width")&&(n.width=t.width),s.has("dashPattern")&&(n.dashPattern=t.dashPattern),s.has("arrow")&&(n.arrow=t.arrow))}};static createConfig2D(e){const{color:t,width:i,dashPattern:n}=e,s={color:t.getHexString(),width:i,dashPattern:n,arrow:e.arrow};return new Ks(s)}updateLocation(e){const t=this.lineMap.get(e);if(t&&this.engine){const{engine:i}=this,{points:n}=e,s=[];n.forEach((e=>{const t=rn.worldToScreen(new a(e.x,e.y,e.z),i);s.push([t.x,t.y])})),t.points=s}}}class Qs{wrappedColor;wrappedWidth;wrappedDashPattern;updateEvent=new ht;wrappedArrow;constructor(e){this.wrappedColor=e.color,this.wrappedWidth=e.width,this.wrappedDashPattern=e.dashPattern,this.wrappedArrow=e.arrow}get color(){return this.wrappedColor}set color(e){this.wrappedColor=e,this.updateEvent.trigger({source:this,property:"color"})}get width(){return this.wrappedWidth}set width(e){this.wrappedWidth=e,this.updateEvent.trigger({source:this,property:"width"})}get dashPattern(){return this.wrappedDashPattern}set dashPattern(e){this.wrappedDashPattern=e,this.updateEvent.trigger({source:this,property:"dashPattern"})}get arrow(){return this.wrappedArrow}set arrow(e){this.wrappedArrow=e,this.updateEvent.trigger({source:this,property:"arrow"})}}class $s{type;name;wrappedText;wrappedAnchorPoint;wrappedConfig;wrappedVisible=!0;id=Fe();updateEvent=new ht;constructor(e,t,i,n){this.type=e,this.wrappedConfig=t,this.wrappedText=i,this.wrappedAnchorPoint=n}get config(){return this.wrappedConfig}set config(e){if(e!==this.wrappedConfig){const t=this.wrappedConfig;this.wrappedConfig=e,this.updateEvent.trigger({source:this,property:"config",oldValue:t})}}get text(){return this.wrappedText}set text(e){if(e!==this.wrappedText){const t=this.wrappedText;this.wrappedText=e,this.updateEvent.trigger({source:this,property:"text",oldValue:t})}}get anchorPoint(){return this.wrappedAnchorPoint}set anchorPoint(e){if(e!==this.wrappedAnchorPoint){const t=this.wrappedAnchorPoint;this.wrappedAnchorPoint=e,this.updateEvent.trigger({source:this,property:"anchorPoint",oldValue:t})}}get visible(){return this.wrappedVisible}set visible(e){if(e!==this.wrappedVisible){const t=this.wrappedVisible;this.wrappedVisible=e,this.updateEvent.trigger({source:this,property:"visible",oldValue:t})}}}class Js extends $s{wrappedAngle;constructor(e,t,i,n){super("2D",e,t,i),this.wrappedAngle=n}get direction(){return this.wrappedAngle}set direction(e){if(e!==this.wrappedAngle){const t=this.wrappedAngle;this.wrappedAngle=e,this.updateEvent.trigger({source:this,property:"angle",oldValue:t})}}}const er="annotation-texts";class tr{engine;annotations;group=new js(er);configMap=new Map;config2Text2D=new rt;textMap=new at;bind(e,t){e!==this.engine&&(this.annotations&&this.annotations.removeObjects(er),this.engine&&(this.engine.rotationChangedEvent.remove(this.update),this.engine.cameraChangeEvent.remove(this.update),this.engine.adaptRangeChangedEvent.remove(this.update),this.engine.sizeChangedEvent.remove(this.update)),this.engine=e,this.annotations=t,this.annotations&&this.annotations.addObject(this.group),this.engine&&(this.engine.rotationChangedEvent.add(this.update),this.engine.cameraChangeEvent.add(this.update),this.engine.adaptRangeChangedEvent.add(this.update),this.engine.sizeChangedEvent.add(this.update)),this.update())}addText(e){const{config:t}=e;let i=this.configMap.get(t);i||(i=this.addConfig(t));const n=new Ws(i,e.text,[0,0],"number"==typeof e.direction?e.direction:0,e.name);n.visible=e.visible,this.textMap.set(e,n),this.config2Text2D.set(t,e),this.engine&&this.updateLocation(e),this.group.add(n),this.annotations?.invalidate(),e.updateEvent.add(this.onTextUpdate),this.engine?.invalidOverlap()}removeText(e){e.updateEvent.remove(this.onTextUpdate);const{config:t}=e;this.config2Text2D.deleteValue(e)&&this.removeConfig(t);const i=this.textMap.get(e);i&&this.group.remove(i),this.textMap.deleteKey(e),this.annotations?.invalidate(),this.engine?.invalidOverlap()}queryText2D(e){return this.textMap.getKey(e)}update=()=>{this.engine&&(Oi(this.textMap.keys(),(e=>{this.updateLocation(e)})),this.engine.invalidOverlap())};onTextUpdate=e=>{if(e){const{property:t,oldValue:i}=e,n=e.source,s=new Map;Array.isArray(t)?t.forEach(((e,t)=>{s.set(e,i[t])})):s.set(t,i);const r=this.textMap.get(n);if(s.size>0){if(s.has("config")){const e=s.get("config");this.config2Text2D.deleteValue(n)&&this.removeConfig(e);const t=n.config,i=this.textMap.get(n);if(this.configMap.has(t))i.config=this.configMap.get(t);else{const e=this.addConfig(t);this.config2Text2D.set(t,n),i.config=e}}s.has("text")&&(r.text=n.text),s.has("visible")&&(r.visible=n.visible),s.has("anchorPoint")&&this.updateLocation(n),s.has("angle")&&this.updateLocation(n)}this.update()}};addConfig(e){if(this.configMap.has(e))throw Error("config already exists");const t=tr.createConfig2D(e);return this.configMap.set(e,t),e.updateEvent.add(this.onConfigUpdate),t}removeConfig(e){this.configMap.has(e)&&(e.updateEvent.remove(this.onConfigUpdate),this.configMap.delete(e))}onConfigUpdate=e=>{if(e){const{source:t,property:i,oldValue:n}=e,s=this.configMap.get(t);if(!s)throw Error("config not found");const r=new Map;Array.isArray(i)?i.forEach(((e,t)=>{r.set(e,n[t])})):r.set(i,n);if(this.config2Text2D.get(t)&&(r.has("color")&&(s.color=t.color.getHexString()),r.has("size")&&(s.size=t.size),r.has("font")&&(s.font=t.font),r.has("alignment"))){const e=tr.mapAlignment(t.alignment);[s.align,s.baseline]=e}}};static createConfig2D(e){const t=tr.mapAlignment(e.alignment),i={color:e.color.getHexString(),size:e.size,font:e.font,baseline:t[1],align:t[0]};return new Vs(i)}static mapAlignment(e){switch(e){case Gs.TopLeft:return["left","top"];case Gs.TopMiddle:return["center","top"];case Gs.TopRight:return["right","top"];case Gs.CenterLeft:return["left","middle"];case Gs.Center:return["center","middle"];case Gs.CenterRight:return["right","middle"];case Gs.BottomLeft:return["left","bottom"];case Gs.BottomMiddle:return["center","bottom"];case Gs.BottomRight:return["right","bottom"];default:return["left","top"]}}updateLocation(e){const t=this.textMap.get(e);if(t&&this.engine){const i=e.anchorPoint,n=rn.worldToScreen(new a(i.x,i.y,i.z),this.engine);if(t.location=[n.x,n.y],"number"!=typeof e.direction){const i=rn.worldToScreen(new a(0,0,0),this.engine),n=e.direction,s=rn.worldToScreen(new a(n.x,n.y,n.z),this.engine);if(s.sub(i),s.length()<1e-6)t.direction=0;else{s.normalize(),s.y=-s.y;const e=s.clone().dot(new r(1,0)),i=s.clone().cross(new r(1,0));let n=Math.acos(e);i<0&&(n=-n),t.direction=n}}else t.direction=e.direction}}}class ir{wrappedType;wrappedColor;wrappedFont;wrappedSize;wrappedAlignment;updateEvent=new ht;constructor(e){this.wrappedType="2D",this.wrappedColor=e.color,this.wrappedFont=e.font,this.wrappedSize=e.size,this.wrappedAlignment=e.alignment}get type(){return this.wrappedType}set type(e){this.wrappedType=e}get color(){return this.wrappedColor}set color(e){if(this.wrappedColor===e)return;const t=this.wrappedColor;this.wrappedColor=e,this.updateEvent.trigger({source:this,property:"color",oldValue:t})}get font(){return this.wrappedFont}set font(e){if(this.wrappedFont===e)return;const t=this.wrappedFont;this.wrappedFont=e,this.updateEvent.trigger({source:this,property:"font",oldValue:t})}get size(){return this.wrappedSize}set size(e){if(this.wrappedSize===e)return;const t=this.wrappedSize;this.wrappedSize=e,this.updateEvent.trigger({source:this,property:"size",oldValue:t})}get alignment(){return this.wrappedAlignment}set alignment(e){if(this.wrappedAlignment===e)return;const t=this.wrappedAlignment;this.wrappedAlignment=e,this.updateEvent.trigger({source:this,property:"alignment",oldValue:t})}}class nr extends ir{constructor(e){super(e),this.type="2D"}}class sr extends $s{wrappedTextDirection={x:1,y:0,z:0};wrappedFacingDirection={x:0,y:1,z:0};constructor(e,t,i,n,s){super("3D",e,t,i),this.setDirections(n,s)}get textDirection(){return this.wrappedTextDirection}set textDirection(e){this.setDirections(e,this.wrappedFacingDirection)}get facingDirection(){return this.wrappedFacingDirection}set facingDirection(e){this.setDirections(this.wrappedTextDirection,e)}setDirections(e,t){const i=new a(e.x,e.y,e.z).normalize();if(new a(t.x,t.y,t.z).normalize().clone().cross(i).length()<1e-5)throw Error("invalid directions");const n=[],s=[];this.wrappedTextDirection!==e&&(n.push("textDirection"),s.push(this.wrappedTextDirection),this.wrappedTextDirection=e),this.wrappedFacingDirection!==t&&(n.push("facingDirection"),s.push(this.wrappedFacingDirection),this.wrappedFacingDirection=t),n.length>0&&s.length>0&&this.updateEvent.trigger({source:this,property:n,oldValue:s})}}function rr(e,t){let{font:i,size:n}=e;return`#${i}#${n}#`}class ar{engine;scenes;configKey2Textures=new Map;configKey2Config=new rt;config2Text3D=new rt;meshes=new at;id=Fe();bind(e){e!==this.engine&&(this.engine&&this.scenes&&(Array.from(this.meshes.keys()).forEach((e=>{this.unApply(e)})),this.scenes.removeObject(Ot,Lt,Dt,this.id),this.engine.autoScaleFilterEvent.remove(this.onAutoScaleFilter)),this.engine=e,this.scenes=e?.scenes,this.engine&&this.scenes&&(this.engine.autoScaleFilterEvent.add(this.onAutoScaleFilter),Array.from(this.meshes.keys()).forEach((e=>{this.apply(e)}))))}add(e){this.apply(e)}remove(e){this.meshes.hasKey(e)&&this.unApply(e)}queryText3D(e){return this.meshes.getKey(e)}onAutoScaleFilter=e=>{e&&e.path[0]===Ot&&e.path[1]===Lt&&e.path[2]===Dt&&e.path[3]===this.id&&(e.filtered=!0)};onTextUpdate=e=>{if(e){const{property:t,oldValue:i}=e,n=e.source,s=new Map;Array.isArray(t)?t.forEach(((e,t)=>{s.set(e,i[t])})):s.set(t,i);const r=this.meshes.get(n);if(s.size>0){let e=!1;if(s.has("config")){const t=s.get("config");this.config2Text3D.deleteValue(n)&&this.removeConfig(t);const i=this.addConfig(n.config);this.config2Text3D.set(n.config,n);const{material:a}=r;a.color=n.config.color,a.mapArray=i.texture,e=!0}s.has("text")&&(r.text=n.text,e=!0),s.has("visible")&&(r.visible=n.visible),(s.has("anchorPoint")||s.has("textDirection")||s.has("facingDirection"))&&(e=!0),e&&this.locateText(n)}}};onConfigPropertiesChanged=e=>{if(e){const{property:t,oldValue:i}=e,n=e.source,s=new Map;Array.isArray(t)?t.forEach(((e,t)=>{s.set(e,i[t])})):s.set(t,i);const r=this.config2Text3D.get(n);if(r){const e=rr(n);if(s.has("size")||s.has("font")){const t=this.configKey2Config.getKey(n);this.configKey2Config.deleteValue(n)&&this.configKey2Textures.delete(t),this.configKey2Textures.set(e,new xs(n.font,n.size,2048,2048)),this.configKey2Config.set(e,n)}r.forEach((t=>{const i=this.meshes.get(t);if(i){const r=i.material;(s.has("size")||s.has("font"))&&(r.mapArray=this.configKey2Textures.get(e).texture),s.has("characterSpacing")&&(i.characterSpacing=n.characterSpacing),s.has("color")&&(r.color=n.color),s.has("alignment")&&this.locateText(t)}}))}}};apply(e){e.updateEvent.add(this.onTextUpdate);const t=this.addConfig(e.config);this.config2Text3D.set(e.config,e);const i=new ws(e.text,t,e.config.color,e.config.characterSpacing);i.preventZoom=!0,i.name=e.id,i.visible=e.visible,this.scenes?.addObject(Ot,i,Lt,Dt,this.id),this.meshes.set(e,i),this.locateText(e)}unApply(e){e.updateEvent.remove(this.onTextUpdate);const t=this.meshes.get(e);t&&(this.scenes?.removeObject(Ot,Lt,Dt,this.id,t.name),this.meshes.deleteKey(e),nn(t));const{config:i}=e;this.config2Text3D.deleteValue(e)&&this.removeConfig(i)}addConfig(e){const t=rr(e);return this.config2Text3D.hasKey(e)||(e.updateEvent.add(this.onConfigPropertiesChanged),this.configKey2Config.set(t,e),this.configKey2Textures.has(t)||this.configKey2Textures.set(t,new xs(e.font,e.size,2048,2048))),this.configKey2Textures.get(t)}removeConfig(e){e.updateEvent.remove(this.onConfigPropertiesChanged);const t=this.configKey2Config.getKey(e);t&&this.configKey2Config.deleteValue(e)&&this.configKey2Textures.delete(t)}locateText(i){const n=this.meshes.get(i);if(n&&this.engine){if(n.geometry.boundingBox||n.geometry.computeBoundingBox(),!n.geometry.boundingBox)return;const{boundingBox:s}=n.geometry,o=ar.calculateAlignPoint(i,s);n.anchorPoint=new r(o.x,o.y);const{camera:h}=this.engine;let d=1;if(h instanceof e){d=(h.top-h.bottom)/this.engine.viewPortSize.height*this.engine.maxDim/2}else d=this.engine.maxDim/this.engine.viewPortSize.height/2;const p=(new t).makeTranslation(i.anchorPoint.x,i.anchorPoint.y,i.anchorPoint.z),l=new a(i.textDirection.x,i.textDirection.y,i.textDirection.z).normalize(),c=new a(i.facingDirection.x,i.facingDirection.y,i.facingDirection.z).normalize(),u=new t;if(c!==new a(0,0,1)){const e=new a(0,0,1).cross(c).normalize(),t=Math.acos(new a(0,0,1).dot(c));u.makeRotationAxis(e,t)}p.multiply(u);const g=new t;if(l!==new a(1,0,0)){const e=new a(1,0,0).cross(l).normalize(),t=Math.acos(new a(1,0,0).dot(l));g.makeRotationAxis(e,t)}p.multiply(g),p.multiply((new t).makeScale(d,d,d)),p.multiply((new t).makeTranslation(-o.x,-o.y,-o.z)),n.matrixAutoUpdate=!1,n.matrix=p}}static calculateAlignPoint(e,t){let i=new a(0,0,0);switch(e.config.alignment){case Gs.TopLeft:i=new a(t.min.x,t.max.y,0);break;case Gs.TopMiddle:i=new a((t.min.x+t.max.x)/2,t.max.y,0);break;case Gs.TopRight:i=t.max;break;case Gs.CenterLeft:i=new a(t.min.x,(t.min.y+t.max.y)/2,0);break;case Gs.Center:i=new a((t.min.x+t.max.x)/2,(t.min.y+t.max.y)/2,0);break;case Gs.CenterRight:i=new a(t.max.x,(t.min.y+t.max.y)/2,0);break;case Gs.BottomLeft:i=t.min;break;case Gs.BottomMiddle:i=new a((t.min.x+t.max.x)/2,t.min.y,0);break;case Gs.BottomRight:i=new a(t.max.x,t.min.y,0);break;default:throw Error("invalid alignment")}return i}}class or extends ir{wrappedCharacterSpacing;constructor(e){super(e),this.type="3D",this.wrappedCharacterSpacing=void 0===e.characterSpacing?0:e.characterSpacing}get characterSpacing(){return this.wrappedCharacterSpacing}set characterSpacing(e){if(this.wrappedCharacterSpacing===e)return;const t=this.wrappedCharacterSpacing;this.wrappedCharacterSpacing=e,this.updateEvent.trigger({source:this,property:"characterSpacing",oldValue:t})}}class hr{wrappedColorMapMode;wrappedColors;wrappedAttributeName;wrappedInterpreterMode;wrappedFrom;wrappedTo;type="color_map";updateEvent=new ht;get colorMapMode(){return this.wrappedColorMapMode}set colorMapMode(e){this.wrappedColorMapMode=e,this.updateEvent.trigger({source:this,properties:"colorMapMode"})}get colors(){return this.wrappedColors}set colors(e){this.wrappedColors=e,this.updateEvent.trigger({source:this,properties:"colors"})}get attributeName(){return this.wrappedAttributeName}set attributeName(e){this.wrappedAttributeName=e,this.updateEvent.trigger({source:this,properties:"attributeName"})}get interpreterMode(){return this.wrappedInterpreterMode}set interpreterMode(e){this.wrappedInterpreterMode=e,this.updateEvent.trigger({source:this,properties:"interpreterMode"})}get from(){return this.wrappedFrom}set from(e){this.wrappedFrom=e,this.updateEvent.trigger({source:this,properties:"from"})}get to(){return this.wrappedTo}set to(e){this.wrappedTo=e,this.updateEvent.trigger({source:this,properties:"to"})}constructor(e,t,i,n,s,r){this.wrappedColorMapMode=e,this.wrappedColors=t,this.wrappedAttributeName=i,this.wrappedInterpreterMode=n,this.wrappedFrom=s,this.wrappedTo=r}}var dr,pr,lr;!function(e){e[e.Nearest=0]="Nearest",e[e.Liner=1]="Liner"}(dr||(dr={}));class cr{wrappedGroups=[];get groups(){return this.wrappedGroups}clone(){const e=new cr;return e.wrappedGroups=this.wrappedGroups.map((e=>({start:e.start,length:e.length,config:e.config}))),e}get configs(){const e=new Set;return this.wrappedGroups.forEach((t=>e.add(t.config))),e}updateGroup(e,t,i){if(e<0||t<=0)throw Error("invalid args.");let n=!1;const s=e+t,r=[];for(let a=0;as)if(o.config===i){const e=r[r.length-1];e.length=h-e.start}else r.push({start:s,length:h-s,config:o.config})}else r.push(o)}n||i&&r.push({start:e,length:t,config:i});const a=cr.diff(this.wrappedGroups,r);return this.wrappedGroups=r,a}rangesOfConfig(e){const t=[];return this.wrappedGroups.forEach((i=>{i.config===e&&t.push({start:i.start,length:i.length})})),t}indexesFromConfig(e,t){const i=this.rangesOfConfig(e);let n=[];if(t){let e;if(Array.isArray(t))e=t;else{e=t.array}let s=0;i.forEach((e=>{s+=e.length})),n=new Array(s);let r=0;i.forEach((t=>{const i=t.start+t.length;for(let s=t.start;se+t.length),0);n=new Array(e);let t=0;i.forEach((e=>{const i=e.start+e.length;for(let s=e.start;s{if(a.config===e){const e=a.start+a.length;for(;i[s]*t+rt?a+=1:e===t?(r+=1,a+=1):r+=1}}for(;r{n.has(e)||o.push(e)})),n.forEach((e=>{i.has(e)||h.push(e)})),o.forEach((e=>s.delete(e))),h.forEach((e=>s.delete(e)));const d=[];s.forEach((e=>d.push(e)));return{added:h,removed:o,updated:d}}}class ur{groups=new cr;customAttributes=new Map;index=void 0;updateEvent=new ht;configToMeshMap=new at;wrappedFactoryHub;wrappedMatrix=new t;batchConfigCache=void 0;id=Fe();wrappedVisible=!0;constructor(e,...t){e&&(Array.isArray(e)?this.index=new Ae(e,1):this.index=e),t.forEach((e=>{this.customAttributes.set(e.name,Array.isArray(e.attr)?new n(e.attr,e.attributeSize||1):e.attr)}))}get visible(){return this.wrappedVisible}set visible(e){if(this.wrappedVisible!==e){this.wrappedVisible=e;const t=[];Oi(this.configToMeshMap.values(),(i=>{const n=i;n.visible=e,t.push({config:this.configToMeshMap.getKey(n),mesh:n})})),this.updateEvent.trigger({source:this,added:[],removed:[],updated:t})}}get size(){return this.index?this.index.count/this.itemSize:0}get matrix(){return this.wrappedMatrix}set matrix(e){this.wrappedMatrix=e;const t=[];Oi(this.configToMeshMap.values(),(i=>{const n=i;n.matrix=e,n.matrixAutoUpdate=!1,n.matrixWorldNeedsUpdate=!0,t.push({config:this.configToMeshMap.getKey(n),mesh:n})})),this.updateEvent.trigger({source:this,added:[],removed:[],updated:t})}configs(){return this.configToMeshMap.keys()}meshes(){return this.configToMeshMap.values()}getMesh(e){return this.configToMeshMap.get(e)}findMesh(e){const t=this.configToMeshMap.values();let i=t.next();for(;!i.done;){if(e(i.value))return i.value;i=t.next()}}startBatchConfigUpdate(){this.batchConfigCache=this.groups.clone()}finishBatchConfigUpdate(){if(this.batchConfigCache){const e=this.groups.diffGroups(this.batchConfigCache);this.raiseUpdateEvent(e),this.batchConfigCache=void 0}}updateConfig(e,t,i){const n=this.groups.updateGroup(e*this.itemSize,t*this.itemSize,i);void 0===this.batchConfigCache&&this.raiseUpdateEvent(n)}raiseUpdateEvent(e){const t={source:this,added:[],removed:[],updated:[]},{wrappedFactoryHub:i}=this;i&&(e.removed.forEach((e=>{const i=this.configToMeshMap.get(e),{geometry:n}=i;n.dispose(),t.removed.push({config:e,mesh:i}),e.updateEvent.remove(this.handleConfigUpdateEvent),this.configToMeshMap.deleteKey(e)})),e.updated.forEach((e=>{const n=this.configToMeshMap.get(e),s=this.groups.indexesFromConfig(e,this.index);i.detectMeshFactory(e,this).updateGeometry(e,this,s),t.updated.push({config:e,mesh:n})})),e.added.forEach((e=>{const i=this.createMesh(e);e.updateEvent.add(this.handleConfigUpdateEvent),t.added.push({config:e,mesh:i})}))),this.updateEvent.trigger(t)}handleConfigUpdateEvent=e=>{if(e&&this.wrappedFactoryHub){const{source:t,property:i}=e,n=this.configToMeshMap.get(t);if(n){const e=this.wrappedFactoryHub.detectMeshFactory(t,this).updateMesh(t,this,Array.isArray(i)?i:[i]);if(e){const i=[{config:t,mesh:n}],s=[{config:t,mesh:e}];e.visible=this.wrappedVisible,e.matrix=this.wrappedMatrix,e.matrixAutoUpdate=!1,e.matrixWorldNeedsUpdate=!0,this.configToMeshMap.set(t,e),this.updateEvent.trigger({source:this,added:s,removed:i,updated:[]})}else this.updateEvent.trigger({source:this,added:[],removed:[],updated:[{config:t,mesh:n}]})}}};mapOriginIndexes(e,t){const i=this.configToMeshMap.getKey(e);if(i)return this.groups.mapOriginIndexes(i,this.itemSize,t)}getConfig(e){return this.configToMeshMap.getKey(e)}get factoryHub(){return this.wrappedFactoryHub}set factoryHub(e){if(!e)throw Error("unexpected factory");if(this.factoryHub&&this.factoryHub!==e)throw Error("factory already set.");this.wrappedFactoryHub=e}createMesh(e){const t=e,{wrappedFactoryHub:i}=this;if(!i)throw Error("no factory");const n=i.detectMeshFactory(t,this).createMesh(t,this);return n.matrix=this.wrappedMatrix,n.matrixAutoUpdate=!1,n.matrixWorldNeedsUpdate=!0,n.name=Fe(),n.visible=this.wrappedVisible,this.configToMeshMap.set(t,n),n}dispose(){this.updateConfig(0,this.size,void 0)}}!function(e){e[e.Line=0]="Line",e[e.Segment=1]="Segment"}(pr||(pr={}));class gr extends ur{isLines=!0;position;lineType;constructor(e,t,i,...s){super(i,...s),this.lineType=e,this.position=Array.isArray(t)?new n(t,3):t}get size(){return super.size||this.position.count/this.itemSize}get itemSize(){return 2}}class fr{detectMeshFactory(e){const t=e,i=t.color,n=t.config;return!(!i||"color_map"!==i.type||!n||"line"!==n.type)}updateGeometry(e,t,i){const n=t,s=n.getMesh(e),r=e.color;fr.updateAttribute(n,r.attributeName,i,s.geometry),s.computeLineDistances()}static updateAttribute(e,t,i,n,s=!0){const r=t?e.customAttributes.get(t):void 0;let a=[];if(e.lineType===pr.Line){const t=s?[{data:e.position.array,itemSize:3}]:[];r&&t.push({data:r.array,itemSize:r.itemSize}),a=Pt([i],t)}else s&&a.push(At(i,{data:e.position.array,itemSize:e.position.itemSize})),r&&a.push(At(i,{data:r.array,itemSize:r.itemSize}));if(s&&n.setPositions(a[0]),r){const e=new Pe(a[s?1:0],2,1);n.setAttribute("valueStart",new Oe(e,r.itemSize,0)),n.setAttribute("valueEnd",new Oe(e,r.itemSize,r.itemSize))}}createMesh(e,t){const i=new qe,n=e,s=n.color,r=t,a=n.config,o=fr.createColorMapMaterial(s,a,n),h=new Ze(i,o),d=r.groups.indexesFromConfig(e,r.index);return fr.updateAttribute(r,s.attributeName,d,i),h.computeLineDistances(),h}updateMesh(e,t,i){const n=e,s=n.color,r=n.config,a=t.getMesh(e);if(!a)throw Error("invalid config or mesh.");{const o=Array.isArray(a.material)?a.material:[a.material];if(2===i.length&&"config"===i[0])return void("lineWidth"===i[1]?o.forEach((e=>{const t=e;t.linewidth=r.lineWidth,t.needsUpdate=!0})):"dashSize"===i[1]?o.forEach((e=>{const t=e;t.dashSize=r.dashSize,t.needsUpdate=!0})):"gapSize"===i[1]?o.forEach((e=>{const t=e;t.gapSize=r.gapSize,t.needsUpdate=!0})):"dashScale"===i[1]?o.forEach((e=>{const t=e;t.dashScale=r.dashScale,t.needsUpdate=!0})):"polygonOffset"===i[1]&&o.forEach((t=>{const i=t;i.polygonOffset=!!e.polygonOffset,e.polygonOffset&&(i.polygonOffsetFactor=e.polygonOffset,i.polygonOffsetUnits=e.polygonOffset)})));if(2===i.length&&"color"===i[0]&&"attributeName"===i[1]){const e=t,{geometry:i}=a,r=e.groups.indexesFromConfig(n,e.index);fr.updateAttribute(e,s.attributeName,r,i,!1)}else{const e=fr.createColorMapMaterial(s,r,n);e.resolution=o[0].resolution,a.material=e}}}static createColorMapMaterial(e,t,i){let n;switch(e.colorMapMode){case Vt.None:n=new oi({colorMapMode:e.colorMapMode,color:e.colors[0].getHex(),linewidth:t.lineWidth,dashed:0!==t.gapSize&&0!==t.dashSize,dashSize:t.dashSize,gapSize:t.gapSize,dashScale:t.dashScale});break;case Vt.Vertex_Color_Map:case Vt.Fragment_Color_Map:{const i=Si.generateTexture1d(e.colors);i.magFilter=void 0===e.interpreterMode||e.interpreterMode===dr.Liner?_e:z,i.minFilter=void 0===e.interpreterMode||e.interpreterMode===dr.Liner?_e:z,n=new oi({colorMapMode:e.colorMapMode,colorMap:i,colorMapOffset:-1*(e.from||0),colorMapRatio:void 0!==e.from&&void 0!==e.to?1/(e.to-e.from):1,linewidth:t.lineWidth,dashed:0!==t.gapSize&&0!==t.dashSize,dashSize:t.dashSize,gapSize:t.gapSize,dashScale:t.dashScale})}break;case Vt.Discrete_Color_Map:n=new oi({colorMapMode:e.colorMapMode,colorMap:Si.generateTexture1d(e.colors),linewidth:t.lineWidth,dashed:0!==t.gapSize&&0!==t.dashSize,dashSize:t.dashSize,gapSize:t.gapSize,dashScale:t.dashScale});break;default:throw Error("not implemented.")}if(n)return n.polygonOffset=!!i.polygonOffset,i.polygonOffset&&(n.polygonOffsetFactor=i.polygonOffset,n.polygonOffsetUnits=i.polygonOffset),n;throw Error("invalid color map mode.")}}class mr{detectMeshFactory(e){const{color:t,config:i}=e;return!!(t&&t instanceof g&&"line"===i.type)}static createGeometry(){return new qe}updateGeometry(e,t,i){const n=t,s=n.getMesh(e),r=s.geometry;mr.updateGeometryImpl(n,r,i),s.computeLineDistances()}static updateGeometryImpl(e,t,i){e.lineType===pr.Line?t.setPositions(Pt([i],{data:e.position.array,itemSize:e.position.itemSize})):t.setPositions(At(i,{data:e.position.array,itemSize:e.position.itemSize})),tn(t)}static createMaterial(e){const t=e,{color:i}=t,n=t.config,s=new Ue({color:i.getHex(),linewidth:n.lineWidth,dashed:0!==n.gapSize&&0!==n.dashSize,dashSize:n.dashSize,gapSize:n.gapSize,dashScale:n.dashScale});return s.polygonOffset=!!e.polygonOffset,e.polygonOffset&&(s.polygonOffsetFactor=e.polygonOffset,s.polygonOffsetUnits=e.polygonOffset),s}createMesh(e,t){const i=mr.createGeometry(),n=mr.createMaterial(e),s=new Ze(i,n),r=t,a=r.groups.indexesFromConfig(e,r.index);return mr.updateGeometryImpl(r,i,a),s.computeLineDistances(),s}updateMesh(e,t,i){const n=e,{color:s}=n,r=n.config,a=t.getMesh(e);if(a&&s&&s instanceof g){const t=a.material;return i.includes("color")&&t.color.set(s),i.includes("lineWidth")&&(t.linewidth=r.lineWidth),i.includes("dashSize")&&(t.dashScale=r.dashSize),i.includes("gapSize")&&(t.gapSize=r.gapSize),i.includes("dashScale")&&(t.dashScale=r.dashScale),void(i.includes("polygonOffset")&&(t.polygonOffset=!!e.polygonOffset,e.polygonOffset&&(t.polygonOffsetFactor=e.polygonOffset,t.polygonOffsetUnits=e.polygonOffset)))}throw Error("invalid line or config")}}class wr{wrappedStyle;wrappedPolygonOffset;get style(){return this.wrappedStyle}set style(e){this.wrappedStyle=e,this.updateEvent.trigger({source:this,property:"style"})}get polygonOffset(){return this.wrappedPolygonOffset}set polygonOffset(e){this.wrappedPolygonOffset=e,this.updateEvent.trigger({source:this,property:"polygonOffset"})}updateEvent=new ht;wrappedMaterial;constructor(e){this.wrappedStyle=e.style,this.wrappedPolygonOffset=e.polygonOffset}get material(){return this.wrappedMaterial}set material(e){if(this.wrappedMaterial)throw Error("material already exists.");this.wrappedMaterial=e}dispose(){this.wrappedMaterial&&this.wrappedMaterial.dispose()}}class vr extends wr{wrappedColor;wrappedConfig;constructor(e){super(e),this.wrappedConfig=e.config,this.wrappedColor=e.color;{const e=this.wrappedColor.updateEvent;e&&e.add(this.updateEventHandler)}{const e=this.config.updateEvent;e&&e.add(this.updateEventHandler)}}get config(){return this.wrappedConfig}set config(e){const t=this.wrappedConfig.updateEvent;void 0!==t&&t.remove(this.updateEventHandler),this.wrappedConfig=e,this.updateEvent.trigger({source:this,property:"config"});const i=this.wrappedConfig.updateEvent;i&&i.add(this.updateEventHandler),this.updateEvent.trigger({source:this,property:"config"})}get color(){return this.wrappedColor}set color(e){const t=this.wrappedColor.updateEvent;void 0!==t&&t.remove(this.updateEventHandler),this.wrappedColor=e;const i=this.wrappedColor.updateEvent;i&&i.add(this.updateEventHandler),this.updateEvent.trigger({source:this,property:"color"})}updateEventHandler=e=>{if(e){let t="color";switch(e.source.type){case"color_map":t="color";break;case"line":case"arrow":if(e.source.type!==this.config.type)throw Error("config type mismatch");t="config"}Array.isArray(e.properties)?this.updateEvent.trigger({source:this,property:[t,...e.properties]}):this.updateEvent.trigger({source:this,property:[t,e.properties]})}}}!function(e){e[e.Regular=0]="Regular",e[e.AboveAll=1]="AboveAll",e[e.GrayOutBlocked=2]="GrayOutBlocked"}(lr||(lr={}));const xr="#above_all_scene",yr=1e3;class Mr{meshFactories=new Set;registerMeshFactory(e){this.meshFactories.add(e)}unregisterMeshFactory(e){this.meshFactories.delete(e)}detectMeshFactory(e,t){let i;if(Li(this.meshFactories.values(),(n=>!n.detectMeshFactory(e,t)||(i=n,!1))),!i)throw Error("invalid config or geometry factory");return i}}class br{shapes=[];scenes;engine;factoryHub=new Mr;meshLocationMap=new Map;wrappedVisible=!0;id=Fe();get visible(){return this.wrappedVisible}set visible(e){this.wrappedVisible!==e&&(this.wrappedVisible=e,this.updateVisible())}bind(e){if(e!==this.engine){if(this.engine){this.onUnbind();const e=this.engine.scenes;this.shapes.forEach((t=>{Oi(t.configs(),(i=>{const n=t.getMesh(i);n&&this.removeMeshFromScenes(n,e)}))})),e.removeObject(Ot,Lt,Dt,this.id),e.removeObject(xr,Lt,Dt,this.id)}if(this.engine=e,this.scenes=this.engine?.scenes,this.scenes){const e=this.scenes;this.shapes.forEach((t=>{Oi(t.configs(),(i=>{const n=t.getMesh(i);n&&this.addMeshToScenes(t,i,e,n)}))})),this.updateVisible(),this.onBind()}}}add(e){const t=e;t.factoryHub=this.factoryHub,this.shapes.push(t);const i=this.scenes,{configs:n}=t.groups;return n.forEach((e=>{let n=t.getMesh(e);n||(n=t.createMesh(e)),n&&this.addMeshToScenes(t,e,i,n)})),t.updateEvent.add(this.onUpdateEvent),t}remove(e){const t=e;t.finishBatchConfigUpdate();const i=this.scenes,{configs:n}=t.groups;n.forEach((e=>{const n=t.getMesh(e);n&&this.removeMeshFromScenes(n,i)})),i&&(i.hasObject(Ot,Lt,Dt,this.id,t.id)&&i.removeObject(Ot,Lt,Dt,this.id,t.id),i.hasObject(xr,Lt,Dt,this.id,t.id)&&i.removeObject(xr,Lt,Dt,this.id,t.id)),t.dispose(),t.updateEvent.remove(this.onUpdateEvent),this.shapes=this.shapes.filter((e=>e!==t))}checkPath(...e){if(e.length<6)return!1;if(e[3]!==this.id)return!1;const t=this.shapes.find((t=>t.id===e[4]));return!!t&&void 0!==t.findMesh((t=>t.name===e[5]))}findShapes(...e){if(e.length<6)return;if(e[3]!==this.id)return;const t=this.shapes.find((t=>t.id===e[4]));if(!t)return;const i=t.findMesh((t=>t.name===e[5]));return i?{shapes:t,mesh:i}:void 0}preAddObject(e){}preRemoveObject(e){}getPaths(e){const t=this.meshLocationMap.get(e);return t?[...t,e.name]:void 0}onUnbind(){}onBind(){}onUpdateEvent=e=>{const t=e,i=t.source,n=this.scenes;t.removed.forEach((e=>{this.removeMeshFromScenes(e.mesh,n)})),t.added.forEach((e=>{const{mesh:t,config:s}=e;t&&this.addMeshToScenes(i,s,n,t)})),(t.added.length>0||t.removed.length>0||t.updated.length>0)&&this.engine?.invalidate()};addMeshToScenes(e,t,i,n){const s=[Lt,Dt,this.id,e.id],r=t.style===lr.AboveAll?xr:Ot;this.preAddObject(n),i?.addObject(r,n,...s),this.meshLocationMap.set(n,[r,...s])}removeMeshFromScenes(e,t){const i=this.meshLocationMap.get(e);if(i){const[n,...s]=i;this.preRemoveObject(e),t?.removeObject(n,...s,e.name),this.meshLocationMap.delete(e),nn(e)}}updateVisible(){this.scenes&&this.scenes.forEachScene((e=>{const t=this.scenes?.getObject(e,Lt,Dt,this.id);t&&(t.visible=this.wrappedVisible)}))}}class Er extends br{addLines(e,t,i,...n){const s=new gr(e,t,i,...n);return this.add(s),s}preAddObject(e){if(this.engine){const{width:t,height:i}=this.engine,n=e;if(void 0!==n?.material){n.material.resolution.set(t,i)}}}onUnbind(){this.engine?.sizeChangedEvent.remove(this.onSizeChanged)}onBind(){this.updateResolution(),this.engine?.sizeChangedEvent.add(this.onSizeChanged)}updateResolution(){if(this.engine){const{width:e,height:t}=this.engine;Array.from(this.meshLocationMap.keys()).forEach((i=>{const n=i;if(void 0!==n?.material){n.material.resolution.set(e,t)}}))}}onSizeChanged=()=>{this.updateResolution()}}class Sr{type="line";wrappedDashSize;wrappedGapSize;wrappedDashScale;wrappedWidth;updateEvent=new ht;constructor(e=1,t=0,i=0,n=1){this.wrappedDashSize=t,this.wrappedGapSize=i,this.wrappedWidth=e,this.wrappedDashScale=n}get dashSize(){return this.wrappedDashSize}set dashSize(e){this.wrappedDashSize=e,this.updateEvent.trigger({source:this,properties:"dashSize"})}get gapSize(){return this.wrappedGapSize}set gapSize(e){this.wrappedGapSize=e,this.updateEvent.trigger({source:this,properties:"gapSize"})}get dashScale(){return this.wrappedDashScale}set dashScale(e){this.wrappedDashScale=e,this.updateEvent.trigger({source:this,properties:"dashScale"})}get lineWidth(){return this.wrappedWidth}set lineWidth(e){this.wrappedWidth=e,this.updateEvent.trigger({source:this,properties:"width"})}}class Tr{order=0;toHitTestResult(e,t){const{object:i}=e;if("Line"===i.type||"LineSegments2"===i.type){const n=e.faceIndex,s={type:"Line",object:i,distance:e.distance,pos:e.pointOnLine.applyMatrix4(t),faceIndex:e.faceIndex},r=i.geometry.index;return s.face=r?[r.array[2*n],r.array[2*n+1]]:[2*n,2*n+1],s}}}class Cr{type="arrow";wrappedDirectionAttributeName;wrappedBodyLengthAttributeName;wrappedBodyRadiusAttributeName;wrappedHeadLengthAttributeName;wrappedHeadRadiusAttributeName;wrappedBodyLength=.5;wrappedBodyRadius=.1;wrappedHeadLength=.5;wrappedHeadRadius=.2;updateEvent=new ht;constructor(e,t,i,n,s){this.wrappedDirectionAttributeName=e,this.wrappedBodyLengthAttributeName=t,this.wrappedBodyRadiusAttributeName=i,this.wrappedHeadLengthAttributeName=n,this.wrappedHeadRadiusAttributeName=s}get bodyLength(){return this.wrappedBodyLength}set bodyLength(e){this.wrappedBodyLength=e,this.updateEvent.trigger({source:this,properties:"length"})}get bodyRadius(){return this.wrappedBodyRadius}set bodyRadius(e){this.wrappedBodyRadius=e,this.updateEvent.trigger({source:this,properties:"radius"})}get headLength(){return this.wrappedHeadLength}set headLength(e){this.wrappedHeadLength=e,this.updateEvent.trigger({source:this,properties:"headLength"})}get headRadius(){return this.wrappedHeadRadius}get directionAttributeName(){return this.wrappedDirectionAttributeName}set directionAttributeName(e){this.wrappedDirectionAttributeName=e,this.updateEvent.trigger({source:this,properties:"directionAttributeName"})}get bodyLengthAttributeName(){return this.wrappedBodyLengthAttributeName}set bodyLengthAttributeName(e){this.wrappedBodyLengthAttributeName=e,this.updateEvent.trigger({source:this,properties:"lengthAttributeName"})}get bodyRadiusAttributeName(){return this.wrappedBodyRadiusAttributeName}set bodyRadiusAttributeName(e){this.wrappedBodyRadiusAttributeName=e,this.updateEvent.trigger({source:this,properties:"radiusAttributeName"})}get headLengthAttributeName(){return this.wrappedHeadLengthAttributeName}set headLengthAttributeName(e){this.wrappedHeadLengthAttributeName=e,this.updateEvent.trigger({source:this,properties:"headLengthAttributeName"})}get headRadiusAttributeName(){return this.wrappedHeadRadiusAttributeName}set headRadiusAttributeName(e){this.wrappedHeadRadiusAttributeName=e,this.updateEvent.trigger({source:this,properties:"headRadiusAttributeName"})}}var _r,Rr;!function(e){e[e.Primary=0]="Primary",e[e.Square=1]="Square",e[e.Cross=2]="Cross",e[e.Ball=3]="Ball",e[e.CustomImage=4]="CustomImage"}(_r||(_r={}));class Ar extends ur{position;constructor(e,t,...i){super(t,...i),this.position=Array.isArray(e)?new n(e,3):e}get size(){return super.size||this.position.count/this.itemSize}get itemSize(){return 1}}class Pr extends br{addPoints(e,t,...i){const n=new Ar(e,t,...i);return this.add(n),n}}class Or extends wr{wrappedShape;wrappedColor;wrappedOpacity;wrappedSize;wrappedCustomShapeUrl;get shape(){return this.wrappedShape}set shape(e){this.wrappedShape=e,this.updateEvent.trigger({source:this,property:"shape"})}get color(){return this.wrappedColor}set color(e){const t=this.wrappedColor.updateEvent;void 0!==t&&t.remove(this.updateEventHandler),this.wrappedColor=e;const i=this.wrappedColor.updateEvent;i&&i.add(this.updateEventHandler),this.updateEvent.trigger({source:this,property:"color"})}get opacity(){return this.wrappedOpacity}set opacity(e){this.wrappedOpacity=e,this.updateEvent.trigger({source:this,property:"opacity"})}get size(){return this.wrappedSize}set size(e){this.wrappedSize=e,this.updateEvent.trigger({source:this,property:"size"})}get customShapeUrl(){return this.wrappedCustomShapeUrl}set customShapeUrl(e){this.wrappedCustomShapeUrl=e,this.updateEvent.trigger({source:this,property:"customShapeUrl"})}constructor(e){super(e),this.wrappedShape=e.shape,this.wrappedColor=e.color,this.wrappedOpacity=e.opacity,this.wrappedSize=e.size,this.wrappedCustomShapeUrl=e.customShapeUrl;{const e=this.wrappedColor.updateEvent;e&&e.add(this.updateEventHandler)}}updateEventHandler=e=>{e&&(Array.isArray(e.properties)?this.updateEvent.trigger({source:this,property:["color",...e.properties]}):this.updateEvent.trigger({source:this,property:["color",e.properties]}))}}class Lr{textures=new Map;async init(){const e=new En;window.assetBaseUrl&&e.setPath(window.assetBaseUrl);const t=[[_r.Ball,"/assets/ball.png"],[_r.Cross,"/assets/cross.png"],[_r.Square,"/assets/cross.png"]];await Promise.all(t.map((async t=>{const[i,n]=t,s=await e.load(n);this.textures.set(i,s)})))}async initTexture(e){const t=new En,i=await t.load(e);this.textures.set(e,i)}removeTexture(e){this.textures.delete(e)}detectMeshFactory(e){return e.shape.type,!0}static createGeometry(e,t){const i=t,n=new o;return n.setAttribute("position",i.position),n}updateGeometry(e,t,i){t.getMesh(e).geometry.setIndex(i)}createMaterial(e){const t=e,{color:i,size:n,opacity:s,customShapeUrl:r}=t,a=t.shape;if(!(i instanceof g))throw Error("not implemented. ");let o;switch(a){case _r.Primary:o=new Le({color:i,size:void 0===n?1:n,transparent:void 0!==s&&s<1,opacity:void 0===s?1:s});break;case _r.CustomImage:{const e=void 0===r?void 0:this.textures.get(r);if(void 0===e)throw Error("custom shape is not initialized.");o=new Le({color:i,size:void 0===n?1:n,map:e,transparent:!0,opacity:void 0===s?1:s,sizeAttenuation:!1})}break;default:{const e=this.textures.get(a);if(void 0===e)throw Error("point shape is not initialized.");o=new Le({color:i,size:void 0===n?1:n,map:e,transparent:!0,opacity:void 0===s?1:s,sizeAttenuation:!1});break}}return o.polygonOffset=!!e.polygonOffset,e.polygonOffset&&(o.polygonOffsetFactor=e.polygonOffset,o.polygonOffsetUnits=e.polygonOffset),o}createMesh(e,t){const i=Lr.createGeometry(e,t),n=t,s=n.groups.indexesFromConfig(e,n.index);i.setIndex(s);const r=this.createMaterial(e);return new De(i,r)}updateMesh(e,t,i){const n=t.getMesh(e);if(!n)throw Error("invalid mesh or config.");{const{shape:t,color:s,size:r,opacity:a,customShapeUrl:o}=e;if(!(s instanceof g))throw Error("not implemented. ");const h=n.material;if(i.includes("color")&&(h.color=s,h.needsUpdate=!0),i.includes("opacity")&&(h.opacity=void 0===a?1:a,h.transparent=void 0!==a&&a<1,h.needsUpdate=!0),i.includes("size")&&(h.size=void 0===r?1:r,h.needsUpdate=!0),i.includes("polygonOffset")&&(h.polygonOffset=!!e.polygonOffset,e.polygonOffset&&(h.polygonOffsetFactor=e.polygonOffset,h.polygonOffsetUnits=e.polygonOffset)),i.includes("shape")||t===_r.CustomImage&&i.includes("customShapeUrl"))switch(t){case _r.Primary:h.map=null,h.needsUpdate=!0;break;case _r.CustomImage:{const e=void 0===o?void 0:this.textures.get(o);if(void 0===e)throw Error("custom shape is not initialized");h.map=e,h.needsUpdate=!0}break;default:{const e=this.textures.get(t);if(void 0===e)throw Error("specified shape is not initialized");h.map=e,h.needsUpdate=!0}}}}}!function(e){e[e.Lambert=0]="Lambert",e[e.Phong=1]="Phong"}(Rr||(Rr={}));class Dr extends ur{position;normal;isTriangles=!0;constructor(e,t,i,...s){let r;if(super(i,...s),this.position=Array.isArray(e)?new n(e,3):e,void 0!==t&&(Array.isArray(t)?t.length===this.position.array.length&&(r=new n(t,3)):r=t),!r){const e=new o;e.setAttribute("position",this.position),this.index&&(e.index=this.index),e.computeVertexNormals(),r=e.getAttribute("normal")}this.normal=r}get size(){return super.size||this.position.count/this.itemSize}get itemSize(){return 3}}class zr extends br{addTriangles(e,t,i=void 0,...n){const s=new Dr(e,t,i,...n);return this.add(s),s}}class Ir extends wr{wrappedColor;wrappedEmissive;wrappedSpecular;wrappedShininess;wrappedOpacity=1;wrappedSide;wrappedLightingModel=Rr.Lambert;get color(){return this.wrappedColor}set color(e){const t=this.wrappedColor.updateEvent;void 0!==t&&t.remove(this.updateEventHandler),this.wrappedColor=e;const i=this.wrappedColor.updateEvent;i&&i.add(this.updateEventHandler),this.updateEvent.trigger({source:this,property:"color"})}get emissive(){return this.wrappedEmissive}set emissive(e){this.wrappedEmissive=e,this.updateEvent.trigger({source:this,property:"emissive"})}get specular(){return this.wrappedSpecular}set specular(e){this.wrappedSpecular=e,this.updateEvent.trigger({source:this,property:"specular"})}get shininess(){return this.wrappedShininess}set shininess(e){this.wrappedShininess=e,this.updateEvent.trigger({source:this,property:"shininess"})}get opacity(){return this.wrappedOpacity}set opacity(e){this.wrappedOpacity=e,this.updateEvent.trigger({source:this,property:"opacity"})}get side(){return this.wrappedSide}set side(e){this.wrappedSide=e,this.updateEvent.trigger({source:this,property:"side"})}get lightingModel(){return this.wrappedLightingModel}set lightingModel(e){this.wrappedLightingModel=e,this.updateEvent.trigger({source:this,property:"lightingModel"})}updateEventHandler=e=>{e&&(Array.isArray(e.properties)?this.updateEvent.trigger({source:this,property:["color",...e.properties]}):this.updateEvent.trigger({source:this,property:["color",e.properties]}))};constructor(e){super(e),this.wrappedColor=e.color,this.wrappedEmissive=e.emissive,this.wrappedSpecular=e.specular,this.wrappedShininess=e.shininess,this.wrappedOpacity=void 0===e.opacity?1:e.opacity,this.wrappedSide=e.side,this.wrappedLightingModel=e.lightingModel;const t=this.wrappedColor.updateEvent;t&&t.add(this.updateEventHandler)}}var Br,Fr,Nr,Ur,Gr;!function(e){e[e.None=0]="None",e[e.NoSeal=1]="NoSeal",e[e.Seal=2]="Seal"}(Br||(Br={}));class Hr extends is{source;clippingMethods=new Map;clippingColors=new Map;defaultColor=new g(0,1,1);lightingModel=Rr.Lambert;constructor(e){super(100),this.source=e}detect(...e){return this.source.checkPath(...e)}allowClip(...e){const t=this.source.findShapes(...e);if(t){const{shapes:e}=t,i=this.clippingMethods.get(e);if(void 0!==i&&i===Br.None)return!1}return!0}mapGroup(...e){const t=e.slice(3,-1);return{groupId:`group#${t[t.length-1]}`,path:t}}sealingSurfaceCreateMethod(e,...t){const i=this.source.findShapes(...t);if(!i)throw Error("invalid path.");const n=this.clippingMethods.get(i.shapes);if(n===Br.None)throw Error("Invalid clipping method.");return void 0===n||n===Br.Seal?zn.ResultMaterial:zn.ResultNone}getSurfaceMesh(e,t,i,...n){const s=this.source.findShapes(...n);if(!s)throw Error("can not find shapes.");const{shapes:r}=s;if(this.clippingMethods.get(r)===Br.NoSeal)return;const a=this.clippingColors.get(r);return this.createMaterial({color:a||this.defaultColor})}getSurfaceMeshAsync(e,t,i,...n){return new Promise((s=>{setTimeout((()=>{const r=this.getSurfaceMesh(e,t,i,...n);s(r)}),3e3)}))}updateMesh(){return In.NothingReplaced}createMaterial(e){return this.lightingModel===Rr.Lambert?new c(e):new ze(e)}}class kr{detectMeshFactory(e){const{color:t}=e;return!!(t&&t instanceof g)}static createGeometry(e,t){const i=t,n=new o;return n.setAttribute("position",i.position),n.setAttribute("normal",i.normal),n}updateGeometry(e,t,i){t.getMesh(e).geometry.setIndex(i)}static createMaterial(e){const{color:t,emissive:i,specular:n,shininess:s,opacity:r,side:a,lightingModel:o,polygonOffset:h}=e;if(t&&t instanceof g){let e;if(o===Rr.Phong)e=new ze({color:t,emissive:i,specular:n,shininess:s,opacity:r,transparent:void 0!==r&&r<1,side:void 0===a?ge:a});else e=new c({color:t,opacity:r,transparent:void 0!==r&&r<1,side:void 0===a?ge:a});return e.polygonOffset=!!h,h&&(e.polygonOffsetFactor=h,e.polygonOffsetUnits=h),e}throw Error("invalid config")}createMesh(e,t){const i=kr.createGeometry(e,t),n=t,s=n.groups.indexesFromConfig(e,n.index);i.setIndex(s);const r=kr.createMaterial(e);return new S(i,r)}updateMesh(e,t,i){const{color:n,emissive:s,specular:r,shininess:a,opacity:o,side:h}=e,d=t.getMesh(e);if(d&&n&&n instanceof g)if(i.includes("lightingModel")){const t=kr.createMaterial(e);d.material=t}else{const t=d.material;i.includes("color")&&(t.color=n),i.includes("emissive")&&void 0!==s&&(t.emissive=s),i.includes("specular")&&void 0!==r&&(t.specular=r),i.includes("shininess")&&void 0!==a&&(t.shininess=a),i.includes("opacity")&&(t.opacity=void 0===o?1:o,t.transparent=void 0!==o&&o<1,t.needsUpdate=!0),i.includes("side")&&(t.side=void 0===h?ge:h,t.needsUpdate=!0),i.includes("polygonOffset")&&(t.polygonOffset=!!e.polygonOffset,e.polygonOffset&&(t.polygonOffsetFactor=e.polygonOffset,t.polygonOffsetUnits=e.polygonOffset))}}}class jr{detectMeshFactory(e){return"color_map"===e.color.type}static createGeometry(e,t){const i=t,n=e.color,s=new o;s.setAttribute("position",i.position),s.setAttribute("normal",i.normal);const r=i.customAttributes.get(n.attributeName);if(r)s.setAttribute("value",r);else if(""!==n.attributeName)throw Error("invalid attribute name");return s}updateGeometry(e,t,i){t.getMesh(e).geometry.setIndex(i)}static createMaterial(e){const t=e,i=t.color,n=void 0===t.opacity?1:t.opacity,s=void 0===t.side?ge:t.side;return jr.createColorMapMaterial(t,i,n,s)}createMesh(e,t){const i=jr.createGeometry(e,t),n=t,s=n.groups.indexesFromConfig(e,n.index);i.setIndex(s);const r=jr.createMaterial(e);return new S(i,r)}updateMesh(e,t,i){const n=e,s=n.color,r=t.getMesh(e);if(!r)throw Error("invalid mesh");{const a=Array.isArray(r.material)?r.material:[r.material];if(1===i.length&&"opacity"===i[0])return void a.forEach((e=>{const t=e;t.opacity=void 0===n.opacity?1:n.opacity,t.transparent=void 0!==n.opacity&&n.opacity<1,t.needsUpdate=!0}));if(1===i.length&&"emissive"===i[0])return void a.forEach((e=>{const t=e;t.emissive=n.emissive||new g(0),t.needsUpdate=!0}));if(n.lightingModel===Rr.Phong){if(1===i.length&&"specular"===i[0])return void a.forEach((e=>{const t=e;t.specular=n.specular||new g(1118481),t.needsUpdate=!0}));if(1===i.length&&"shininess"===i[0])return void a.forEach((e=>{const t=e;t.shininess=n.shininess||.3,t.needsUpdate=!0}))}if(1===i.length&&"side"===i[0])return void a.forEach((e=>{const t=e;t.side=void 0===n.side?ge:n.side,t.needsUpdate=!0}));if(2===i.length&&"attributeName"===i[1]){const e=t,{geometry:i}=r,n=e.customAttributes.get(s.attributeName);if(!n)throw Error("invalid attribute name");i.setAttribute("value",n)}else{const t=jr.createMaterial(e);r.material=t}}}static createMaterialByLightingModel(e,t){return e.lightingModel===Rr.Lambert?new Kt(t):new ti(t)}static createColorMapMaterial(e,t,i,n){let s;switch(t.colorMapMode){case Vt.None:s=jr.createMaterialByLightingModel(e,{colorMapMode:t.colorMapMode,color:t.colors[0]});break;case Vt.Vertex_Color_Map:case Vt.Fragment_Color_Map:{const r=Si.generateTexture1d(t.colors);r.magFilter=void 0===t.interpreterMode||t.interpreterMode===dr.Liner?_e:z,r.minFilter=void 0===t.interpreterMode||t.interpreterMode===dr.Liner?_e:z,s=jr.createMaterialByLightingModel(e,{colorMapMode:t.colorMapMode,colorMap:r,colorMapOffset:-1*(t.from||0),colorMapRatio:void 0!==t.from&&void 0!==t.to?1/(t.to-t.from):1,opacity:i,transparent:i<1,side:void 0===n?ge:n})}break;case Vt.Discrete_Color_Map:s=jr.createMaterialByLightingModel(e,{colorMapMode:t.colorMapMode,colorMap:Si.generateTexture1d(t.colors),side:void 0===n?ge:n});break;default:throw Error("not implemented.")}return s.polygonOffset=!!e.polygonOffset,e.polygonOffset&&(s.polygonOffsetFactor=e.polygonOffset,s.polygonOffsetUnits=e.polygonOffset),s}}class Vr extends Sn{constructor(){super(9)}tolerance=0;conditionCallback;mouseMoveOnEvent=new ht;selectionEvent=new ht;enableDynSel=!1;hitObjects(e,t){return t.hitTest(e.offsetX,e.offsetY,this.conditionCallback,this.tolerance)}handleLeftButtonUp(e,t){if(0===e.button&&this.isEnabled&&0===t.state){const i={on:null,processed:!1,pos2:{x:e.offsetX,y:e.offsetY}};if(!this.enableDynSel){const n=this.hitObjects(e,t);i.on=n}return this.selectionEvent.trigger(i),!1}return!1}handleMouseMove(e,t){if(this.isEnabled&&0===t.state){if(this.enableDynSel){const i={on:null,processed:!1},n=this.hitObjects(e,t);i.on=n,this.mouseMoveOnEvent.trigger(i)}return!1}return!1}}class Wr{type="AnnotationHitInfo";annotation;constructor(e){this.annotation=e}}!function(e){e[e.UnInitialized=0]="UnInitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"}(Fr||(Fr={}));class Kr{wrappedEngine;navigator=new ds;navigator2d=new ps;rotationHandler=new gs;clippingManager=new ts;wrappedRulerManager;wrappedCrossRulerManager;wrappedEnableClipping=!1;wrappedUserDefinedAdaptRange;wrappedDebugMode=!1;is2d=!1;status=Fr.UnInitialized;initStatusEvent=new ht;engineChangeEvent=new ht;get engine(){return this.wrappedEngine}get debugMode(){return this.wrappedDebugMode}set debugMode(e){this.wrappedDebugMode!==e&&(this.wrappedDebugMode=e,this.wrappedEngine&&(this.wrappedEngine.debugMode=e))}get enableNavigator(){return this.navigator.isEnabled}set enableNavigator(e){this.navigator.isEnabled!==e&&(this.navigator.isEnabled=e)}get enableNavigator2D(){return this.navigator2d.isEnabled}set enableNavigator2D(e){this.navigator2d.isEnabled!==e&&(this.navigator2d.isEnabled=e)}set enable2DMode(e){e!==this.is2d&&(this.is2d=e,this.is2d?(this.navigator2d.bind(this.engine),this.navigator.bind(void 0),this.rotationHandler.enableRotation=!1):(this.navigator.bind(this.engine),this.navigator2d.bind(void 0),this.rotationHandler.enableRotation=!0),this.engine?.invalidate())}get enable2DMode(){return this.is2d}get enableClippingAction(){return this.clippingManager.enableAction}set enableClippingAction(e){this.clippingManager.enableAction=e}get enableClipping(){return this.wrappedEnableClipping}set enableClipping(e){e!==this.wrappedEnableClipping&&(this.wrappedEnableClipping=e,this.clippingManager.bind(this.wrappedEnableClipping?this.engine:void 0))}get enableClippingEdge(){return this.clippingManager.showClippingEdge}set enableClippingEdge(e){this.clippingManager.showClippingEdge=e}get sectionsManager(){if(!this.clippingManager.sectionManager)throw new Error("SectionsManager is not enabled");return this.clippingManager.sectionManager}get enableSections(){return this.clippingManager.enableSection}set enableSections(e){this.clippingManager.enableSection=e}get rulerManager(){if(!this.wrappedRulerManager)throw new Error("RulerManager is not enabled");return this.wrappedRulerManager}get enableRuler(){return void 0!==this.wrappedRulerManager}set enableRuler(e){e&&void 0===this.wrappedRulerManager?(this.wrappedRulerManager=new fs,this.wrappedRulerManager.bind(this.wrappedEngine)):e||void 0===this.wrappedRulerManager||(this.wrappedRulerManager.bind(void 0),this.wrappedRulerManager=void 0)}get crossRulerManager(){if(!this.wrappedCrossRulerManager)throw new Error("CrossRulerManager is not enabled");return this.wrappedCrossRulerManager}get enableCrossRuler(){return void 0!==this.wrappedCrossRulerManager}set enableCrossRuler(e){e&&void 0===this.wrappedCrossRulerManager?(this.wrappedCrossRulerManager=new as,this.wrappedCrossRulerManager.bind(this.wrappedEngine)):e||void 0===this.wrappedCrossRulerManager||(this.wrappedCrossRulerManager.bind(void 0),this.wrappedCrossRulerManager=void 0)}get userDefinedAdaptRange(){return this.wrappedUserDefinedAdaptRange}set userDefinedAdaptRange(e){this.wrappedUserDefinedAdaptRange=e,this.engine&&(this.engine.userDefinedAdaptRange=this.wrappedUserDefinedAdaptRange)}async onInit(){}async init(){this.status===Fr.UnInitialized&&(this.status=Fr.Initializing,this.initStatusEvent.trigger(this.status),this.navigator2d.init(),await this.navigator.init(),await this.onInit(),this.status=Fr.Initialized,this.initStatusEvent.trigger(this.status),this.clippingManager.sealingSurfaceFactoryHub.register(new is))}focus(e){if(!this.engine)return;this.engine.scenes.forEachScene(((e,t)=>{t.updateMatrixWorld(!0)}));const t=rn.calculateBoundingBox(e);if(!t)return;const{camera:i}=this.engine;rn.focusCamera(t,i),i.raiseCameraChangeEvent()}bind(e){if(this.wrappedEngine===e)return;const t=this.wrappedEngine;void 0!==this.wrappedEngine&&(this.navigator.bind(void 0),this.navigator2d.bind(void 0),this.wrappedEngine.removeActionHandler(this.rotationHandler),this.clippingManager.bind(void 0),this.wrappedRulerManager?.bind(void 0),this.onUnbind()),this.wrappedEngine=e,this.wrappedEngine&&(this.onBind(),this.wrappedEngine.debugMode=this.wrappedDebugMode,this.wrappedEngine.userDefinedAdaptRange=this.wrappedUserDefinedAdaptRange,this.navigator.bind(this.is2d?void 0:this.wrappedEngine),this.navigator2d.bind(this.is2d?this.wrappedEngine:void 0),this.rotationHandler.enableRotation=!this.is2d,this.wrappedEngine.addActionHandler(this.rotationHandler),this.wrappedEnableClipping&&this.clippingManager.bind(this.wrappedEngine),this.wrappedRulerManager?.bind(this.wrappedEngine)),this.engineChangeEvent.trigger({old:t,new:this.wrappedEngine})}onUnbind(){}onBind(){this.wrappedEngine&&this.wrappedEngine.updateBackground([new g("grey"),new g("white")])}}class Yr{order=0;toHitTestResult(e,t){const{object:i}=e;if("Points"===i.type)return{type:"Points",object:i,distance:e.distance,pos:e.point.applyMatrix4(t),index:e.index}}}!function(e){e[e.MoveOn=0]="MoveOn",e[e.ClickOn=1]="ClickOn",e[e.Area=2]="Area"}(Nr||(Nr={}));class Xr{type="ShapesHitInfo";distance;//! distance from ray origin shape;//! hit shape x;//! hit coord y;z;index;//! hit index(maybe line, point or triangle) element;//! hit element, line: {index1, index2}, triangle: {index1, index2, index3}, point: {index} constructor(e,t,i,n,s,r,a){this.distance=e,this.shape=t,this.x=i,this.y=n,this.z=s,this.index=r,this.element=a}}class qr{order=0;toHitTestResult(e){const{object:t}=e;if(t instanceof ws)return{type:"Text3D",object:t}}}class Zr{scenes;trianglesCollection=new zr;linesCollection=new Er;pointsCollection=new Pr;annotationTextCollection=new tr;text3DCollection=new ar;annotationLine2DCollection=new Zs;annotations=new Xs;clippingSurfaceFactory;initEvent=new ht;selectableShapes=[];selectionEvent=new ht;selectionHandler=new Vr;pointsRayCastResultConverter=new Yr;linesRayCastResultConverter=new Tr;text3DRayCastResultConverter=new qr;clippingManager;engine;set selectTol(e){this.selectionHandler.tolerance=e}get selectTol(){return this.selectionHandler.tolerance}get enableSelection(){return this.selectionHandler.isEnabled}set enableSelection(e){this.selectionHandler.isEnabled=e}get enableDynSel(){return this.selectionHandler.enableDynSel}set enableDynSel(e){this.selectionHandler.enableDynSel=e}get showLines(){return this.linesCollection.visible}set showLines(e){this.linesCollection.visible=e}get showPoints(){return this.pointsCollection.visible}set showPoints(e){this.pointsCollection.visible=e}get showTriangles(){return this.trianglesCollection.visible}set showTriangles(e){this.trianglesCollection.visible=e}constructor(e){this.clippingManager=e,this.clippingSurfaceFactory=new Hr(this.trianglesCollection),this.selectionHandler.tolerance=3,this.selectionHandler.conditionCallback=e=>{let t=!1;return this.selectableShapes.forEach((i=>{if(!t)if(i instanceof ur&&i.visible)i.getConfig(e)&&(t=!0);else if(i instanceof sr){if(e instanceof ws){i===this.text3DCollection.queryText3D(e)&&(t=!0)}}else if(i instanceof Js){if(e instanceof Ws){i===this.annotationTextCollection.queryText2D(e)&&(t=!0)}}else if(i instanceof Hs&&e instanceof Ys){i===this.annotationLine2DCollection.queryLine(e)&&(t=!0)}})),t},this.selectionHandler.mouseMoveOnEvent.add((e=>{if(!e)throw Error("invalid args.");const t=e,{on:i}=e;if(i){const e=[];i.forEach((t=>{const i=this.convertHitTestResult(t);i&&e.push(i)})),this.selectionEvent.trigger({type:Nr.MoveOn,info:e}),t.processed=!0}else this.selectionEvent.trigger({type:Nr.MoveOn})})),this.selectionHandler.selectionEvent.add((e=>{if(!e)throw Error("invalid args.");const t=e,{on:i}=e;if(i){const n=[];i.forEach((e=>{const t=this.convertHitTestResult(e);t&&n.push(t)})),this.selectionEvent.trigger({type:Nr.ClickOn,info:n,pos2:e.pos2}),t.processed=!0}else this.selectionEvent.trigger({type:Nr.ClickOn,pos2:e.pos2})}))}async init(){{const e=new kr;this.trianglesCollection.factoryHub.registerMeshFactory(e)}{const e=new jr;this.trianglesCollection.factoryHub.registerMeshFactory(e)}{const e=new Lr;await e.init(),this.pointsCollection.factoryHub.registerMeshFactory(e)}{const e=new mr;this.linesCollection.factoryHub.registerMeshFactory(e)}{const e=new fr;this.linesCollection.factoryHub.registerMeshFactory(e)}this.clippingManager?.sealingSurfaceFactoryHub.register(this.clippingSurfaceFactory),this.initEvent.trigger()}focus(e){if(!this.engine)throw Error("engine is empty.");let t;if(e instanceof ur){const i=[];Oi(e.configs(),(t=>{const n=e.getMesh(t);n&&i.push(n)})),t=i}else t=e;this.engine.scenes.forEachScene(((e,t)=>{t.updateMatrixWorld(!0)}));const i=rn.calculateBoundingBox(t);if(!i)return;const{camera:n}=this.engine;rn.focusCamera(i,n),n.raiseCameraChangeEvent()}bind(e){this.engine!==e&&(void 0!==this.engine&&this.onUnbind(),this.engine=e,this.engine&&this.onBind())}onBind(){if(!this.engine)throw Error("engine is empty.");if(this.scenes=this.engine.scenes,this.restore(),this.trianglesCollection.bind(this.engine),this.linesCollection.bind(this.engine),this.pointsCollection.bind(this.engine),this.engine.rayCastResultConvertHub.register(this.pointsRayCastResultConverter),this.engine.rayCastResultConvertHub.register(this.linesRayCastResultConverter),this.engine.rayCastResultConvertHub.register(this.text3DRayCastResultConverter),this.engine.addActionHandler(this.selectionHandler),this.engine.rayCasterConfigCallback=(e,t)=>{e.params.Line2={threshold:t}},!this.scenes)throw Error("scenes is empty.");this.engine.addOverlayLayer(this.annotations),this.annotationTextCollection.bind(this.engine,this.annotations),this.annotationLine2DCollection.bind(this.engine,this.annotations),this.text3DCollection.bind(this.engine)}onUnbind(){this.engine&&(this.engine.rayCasterConfigCallback=void 0,this.engine.rayCastResultConvertHub.unregister(this.text3DRayCastResultConverter),this.engine.rayCastResultConvertHub.unregister(this.pointsRayCastResultConverter),this.engine.rayCastResultConvertHub.unregister(this.linesRayCastResultConverter),this.engine.removeActionHandler(this.selectionHandler),this.engine.removeOverlayLayer(this.annotations)),this.trianglesCollection.bind(void 0),this.linesCollection.bind(void 0),this.pointsCollection.bind(void 0),this.clean(),this.scenes=void 0,this.annotationTextCollection.bind(void 0,void 0),this.annotationLine2DCollection.bind(void 0,void 0),this.text3DCollection.bind(void 0)}registerClippingMethod(e,t){this.clippingSurfaceFactory.clippingMethods.set(e,t)}unregisterClippingMethod(e){this.clippingSurfaceFactory.clippingMethods.delete(e)}setClippingColor(e,t){this.clippingSurfaceFactory.clippingColors.set(e,t)}removeClippingColor(e){this.clippingSurfaceFactory.clippingColors.delete(e)}add(e,t){return void 0!==t&&this.registerClippingMethod(e,t),e.isTriangles?this.trianglesCollection.add(e):e.isLines?this.linesCollection.add(e):this.pointsCollection.add(e),e}remove(e){this.unregisterClippingMethod(e),this.removeClippingColor(e),e.isTriangles?this.trianglesCollection.remove(e):e.isLines?this.linesCollection.remove(e):this.pointsCollection.remove(e)}addTriangles(e,t=void 0,i=void 0,n=void 0,...s){const r=this.trianglesCollection.addTriangles(e,t,i,...s);return void 0!==n&&this.registerClippingMethod(r,n),r}addLines(e,t,i=void 0,...n){return this.linesCollection.addLines(e,t,i,...n)}addPoints(e,t=void 0){return this.pointsCollection.addPoints(e,t)}addText(e){"2D"===e.type?this.annotationTextCollection.addText(e):"3D"===e.type&&this.text3DCollection.add(e)}removeText(e){"2D"===e.type?this.annotationTextCollection.removeText(e):this.text3DCollection.remove(e)}addLine2D(e){this.annotationLine2DCollection.addLine(e)}removeLine2D(e){this.annotationLine2DCollection.removeLine(e)}restore(){if(this.scenes){It(this.scenes.addScene(xr,1e3).scene,Zr.onBeforeScene)}}clean(){if(this.scenes){const e=this.scenes.getSceneItem(xr);e&&Bt(e.scene,Zr.onBeforeScene)}}static onBeforeScene=e=>{e.clearDepth()};convertHitTestResult(e){switch(e.type){case"Mesh":case"Line":case"Points":{const t=this.selectableShapes.find((t=>t instanceof ur&&void 0!==t.getConfig(e.object)));if(t)return Zr.convertShapesHitTestResult(e,t)}break;case"annotation-line":{const t=this.annotationLine2DCollection.queryLine(e.object);if(t)return new Wr(t)}break;case"annotation-text":{const t=this.annotationTextCollection.queryText2D(e.object);if(t)return new Wr(t)}break;case"Text3D":{const t=this.text3DCollection.queryText3D(e.object);if(t)return new Wr(t)}}}static convertShapesHitTestResult(e,t){if(!(e.object instanceof h))throw Error("invalid hit target.");switch(e.object.type){case"Mesh":{const i=e,[n]=t.mapOriginIndexes(i.object,[i.faceIndex]);return new Xr(i.distance,t,i.pos.x,i.pos.y,i.pos.z,n,{index1:i.face[0],index2:i.face[1],index3:i.face[2]})}case"LineSegments2":{const i=e,[n]=t.mapOriginIndexes(i.object,[i.faceIndex]);return new Xr(i.distance,t,i.pos.x,i.pos.y,i.pos.z,n,{index1:i.face[0],index2:i.face[1]})}case"Points":{const i=e;return new Xr(i.distance,t,i.pos.x,i.pos.y,i.pos.z,i.index,{index1:i.index})}default:throw Error("invalid hit target.")}}}class Qr extends Kr{cadComponents;wboitAction=new ki;wrappedEnableOit=!1;get enableOit(){return this.wrappedEnableOit}set enableOit(e){this.wrappedEnableOit!==e&&(this.wrappedEnableOit=e,this.patchOit(e))}get trianglesCollection(){return this.cadComponents.trianglesCollection}get linesCollection(){return this.cadComponents.linesCollection}get pointsCollection(){return this.cadComponents.pointsCollection}get annotationTextCollection(){return this.cadComponents.annotationTextCollection}get text3DCollection(){return this.cadComponents.text3DCollection}get annotationLine2DCollection(){return this.cadComponents.annotationLine2DCollection}get annotations(){return this.cadComponents.annotations}get selectableShapes(){return this.cadComponents.selectableShapes}set selectableShapes(e){this.cadComponents.selectableShapes=e}get selectionEvent(){return this.cadComponents.selectionEvent}set selectTol(e){this.cadComponents.selectTol=e}get selectTol(){return this.cadComponents.selectTol}get enableSelection(){return this.cadComponents.enableSelection}set enableSelection(e){this.cadComponents.enableSelection=e}get enableDynSel(){return this.cadComponents.enableDynSel}set enableDynSel(e){this.cadComponents.enableDynSel=e}get showLines(){return this.cadComponents.linesCollection.visible}set showLines(e){this.cadComponents.linesCollection.visible=e}get showPoints(){return this.cadComponents.pointsCollection.visible}set showPoints(e){this.cadComponents.pointsCollection.visible=e}get showTriangles(){return this.cadComponents.trianglesCollection.visible}set showTriangles(e){this.cadComponents.trianglesCollection.visible=e}constructor(){super(),this.cadComponents=new Zr(this.clippingManager)}async onInit(){await this.cadComponents.init()}focus(e){this.cadComponents.focus(e)}patchOit(e){e?this.engine&&(di(),li(),ui(),fi(),mi(c),mi(ze),mi(Kt),mi(ti),mi(Q),mi(Le),mi(jt),this.wboitAction.bind(this.engine)):this.wboitAction.bind(void 0)}onBind(){if(super.onBind(),!this.engine)throw Error("engine is empty.");this.cadComponents.bind(this.engine),this.enableOit&&this.patchOit(!0)}onUnbind(){super.onUnbind(),this.cadComponents.bind(void 0),this.enableOit&&this.patchOit(!1)}registerClippingMethod(e,t){this.cadComponents.clippingSurfaceFactory.clippingMethods.set(e,t)}unregisterClippingMethod(e){this.cadComponents.clippingSurfaceFactory.clippingMethods.delete(e)}setClippingColor(e,t){this.cadComponents.clippingSurfaceFactory.clippingColors.set(e,t)}removeClippingColor(e){this.cadComponents.clippingSurfaceFactory.clippingColors.delete(e)}addTriangles(e,t=void 0,i=void 0,n=void 0,...s){return this.cadComponents.addTriangles(e,t,i,n,...s)}add(e,t){return this.cadComponents.add(e,t)}remove(e){this.cadComponents.remove(e)}addLines(e,t,i=void 0,...n){return this.cadComponents.addLines(e,t,i,...n)}addPoints(e,t=void 0){return this.cadComponents.addPoints(e,t)}addText(e){this.cadComponents.addText(e)}removeText(e){this.cadComponents.removeText(e)}addLine2D(e){this.cadComponents.addLine2D(e)}removeLine2D(e){this.cadComponents.removeLine2D(e)}}class $r extends a{}class Jr extends g{}class ea extends q{}class ta extends t{}class ia extends ie{}class na extends r{}class sa{xyz;//! 点坐标 constructor(e,t,i){this.xyz=new $r(e,t,i)}setCoord(e,t,i){this.xyz.set(e,t,i)}x(){return this.xyz.x}y(){return this.xyz.y}z(){return this.xyz.z}static toFloat32Array(e){return new Float32Array(this.toArray(e))}static toArray(e){const t=new Array;return e.forEach((e=>{t.push(e.x(),e.y(),e.z())})),t}static toArrayVec(e){const t=new Array;return e.forEach((e=>{t.push(e.x,e.y,e.z)})),t}}class ra extends sa{applayMatrix4(e){this.xyz.applyMatrix4(e)}}class aa{nodes;//! 点列表,为连续的点序列 constructor(){this.nodes=new Array}get nodeList(){return this.nodes}set nodeList(e){this.nodes=e}static createIndex(e,t){const i=[];for(let n=1;ne.expandByPoint(t.xyz))),e}}class oa{parent=null;props;constructor(e,t){this.parent=e,void 0!==t&&t.props&&(this.props=t.props)}name(){return this.props?.name}findEdge(e){throw new Error("Method not implemented.")}findFace(e){throw new Error("Method not implemented.")}findVertex(e){throw new Error("Method not implemented.")}getAllFaces(){return[]}getAllEdges(){return[]}getAllVertices(){return[]}static findBRep(e,t){if(Array.isArray(e)){const i=e;return t.find((e=>{const t=e.name();if(Array.isArray(t)){let e=!0;return i.forEach((i=>{t.includes(i)||(e=!1)})),e}return!1}))}return t.find((t=>{const i=t.name();return!Array.isArray(i)&&i===e}))}body(){if(this.parent)return this.parent.body();throw new Error("Method not implemented.")}}!function(e){e[e.COMPOUND=0]="COMPOUND",e[e.SOLID=2]="SOLID",e[e.SHELL=3]="SHELL",e[e.FACE=4]="FACE",e[e.WIRE=5]="WIRE",e[e.EDGE=6]="EDGE",e[e.VERTEX=7]="VERTEX",e[e.LOOP=9]="LOOP",e[e.HALFEDGE=10]="HALFEDGE"}(Ur||(Ur={})),function(e){e[e.BT_SolidBody=0]="BT_SolidBody",e[e.BT_ShellBody=1]="BT_ShellBody",e[e.BT_WireBody=2]="BT_WireBody",e[e.BT_AcornBody=3]="BT_AcornBody",e[e.BT_CompoundBody=4]="BT_CompoundBody"}(Gr||(Gr={}));class ha extends oa{geomType;//! 几何曲线类型 polygon;//! 用于显示的多边形 start;//! 起点 end;//! 末点 constructor(e,t){super(t,e),this.geomType=e.type,this.polygon=new aa,e.nodes.forEach((e=>{this.polygon.nodeList.push(new ra(e[0],e[1],e[2]))})),this.start=t.findVertex(e.start),this.end=t.findVertex(e.end)}isGeom(){return!0}getAllEdges(){return[this]}getAllVertices(){return this.start===this.end?[this.start]:[this.start,this.end]}shapeType(){return Ur.EDGE}}class da extends sa{constructor(e,t,i){super(e,t,i),this.xyz.normalize()}applayMatrix4(e){const t=new ia(this.xyz.x,this.xyz.y,this.xyz.z,0);t.applyMatrix4(e).normalize(),this.xyz.set(t.x,t.y,t.z)}}class pa{node1;//! 顶点1 node2;//! 顶点2 node3;//! 顶点3 constructor(e,t,i){this.node1=e,this.node2=t,this.node3=i}}class la{nodes;//! 顶点列表 normals;//! 顶点法向 triangles;//! 三角面片列表 constructor(){this.nodes=new Array,this.triangles=new Array,this.normals=new Array}get nodeList(){return this.nodes}set nodeList(e){this.nodes=e}get triangleList(){return this.triangles}set triangleList(e){this.triangles=e}get normalList(){return this.normals}set normalList(e){this.normals=e}static toUint32Array(e){return new Uint32Array(this.toArray(e))}static toArray(e,t=0){const i=new Array;return e.forEach((e=>{i.push(e.node1+t,e.node2+t,e.node3+t)})),i}static createFromBufferGeometry(e){if(!e.hasAttribute("position"))return null;const t=new la,i=e.attributes.position;for(let e=0;e0){const i=e.index;for(let e=0;et.applayMatrix4(e))),this.normalList.forEach((t=>t.applayMatrix4(e)))}bndBox(){const e=new ea;return this.nodeList.forEach((t=>e.expandByPoint(t.xyz))),e}expandSharedPoint(){const e=new Array,t=new Array;this.triangles.forEach((i=>{const n=t.length;e.push(new pa(n,n+1,n+2)),t.push(this.nodes[i.node1],this.nodes[i.node2],this.nodes[i.node3])})),this.nodes=t,this.triangles=e}}class ca extends oa{edge;//! 半边所引用的边 reversed;//! 是否与引用边反向 constructor(e,t){super(e,t),this.edge=e.parent?.parent?.findEdge(t.edge),this.reversed=t.reversed}shapeType(){return Ur.HALFEDGE}isGeom(){return!1}getAllEdges(){return[this.edge]}getAllVertices(){return this.edge.getAllVertices()}}class ua extends oa{halfEdges=[];//! 环所包含的半边 isOut;//! 是否为外环 constructor(e,t){super(e,t),this.isOut=t.isOut,t.halfEdges.forEach((e=>{this.halfEdges.push(new ca(this,e))}))}shapeType(){return Ur.LOOP}isGeom(){return!1}getAllEdges(){const e=[];return this.halfEdges.forEach((t=>e.push(t.edge))),e}getAllVertices(){const e=[];return this.getAllEdges().forEach((t=>{e.find((e=>e===t.start))||e.push(t.start),e.find((e=>e===t.end))||e.push(t.end)})),e}}class ga extends oa{geomType;//! 几何面类型 triangulation;//! 用于显示的面片集合 loops=[];//! 限定Face的环,第一个始终为外环 constructor(e,t){super(t,e),this.geomType=e.type,this.triangulation=new la,e.nodes.forEach((e=>{this.triangulation.nodeList.push(new ra(e[0],e[1],e[2]))})),e.normals.forEach((e=>{this.triangulation.normalList.push(new da(e[0],e[1],e[2]))})),e.indices.forEach((e=>{this.triangulation.triangleList.push(new pa(e[0],e[1],e[2]))})),e.loops&&e.loops.forEach((e=>{this.loops.push(new ua(this,e))}))}hasInnerLoop(){return this.loops.length>1}isGeom(){return!0}getAllFaces(){return[this]}getAllEdges(){const e=[];return this.loops.forEach((t=>{e.push(...t.getAllEdges())})),e}getAllVertices(){const e=[];return this.loops.forEach((t=>{e.push(...t.getAllVertices())})),e}shapeType(){return Ur.FACE}}class fa extends oa{point;//! 点坐标数据 wrappedBody=null;//! 所属的body constructor(e,t=null){super(t,e),this.point=new ra(e.coord[0],e.coord[1],e.coord[2])}isGeom(){return!0}shapeType(){return Ur.VERTEX}getAllVertices(){return[this]}body(){return this.wrappedBody?this.wrappedBody:super.body()}setBody(e){this.wrappedBody=e}}class ma extends oa{faces=[];//! BRep面集合 edges=[];//! 边集合 vertices=[];//! 顶点集合 wrappedBody=null;//! 所属的body constructor(e,t=null){super(t,e),e.vertices?.forEach((e=>{this.vertices.push(new fa(e,this))})),e.edges?.forEach((e=>{this.edges.push(new ha(e,this))})),e.faces?.forEach((e=>{this.faces.push(new ga(e,this))}))}findVertex(e){const t=oa.findBRep(e,this.vertices);if(t)return t}findEdge(e){const t=oa.findBRep(e,this.edges);if(t)return t}findFace(e){const t=oa.findBRep(e,this.faces);if(t)return t}shapeType(){return Ur.SHELL}isGeom(){return!1}getAllFaces(){return[...this.faces]}getAllEdges(){return[...this.edges]}getAllVertices(){return[...this.vertices]}body(){return this.wrappedBody?this.wrappedBody:super.body()}setBody(e){this.wrappedBody=e}}class wa extends oa{shells=[];//! 壳数组 wrappedBody=null;//! 所属的body constructor(e){super(null,e),e.shells.forEach((e=>{this.shells.push(new ma(e,this))}))}shapeType(){return Ur.SOLID}isGeom(){return!1}findVertex(e){for(const t of this.shells){const i=t.findVertex(e);if(i)return i}}findEdge(e){for(const t of this.shells){const i=t.findEdge(e);if(i)return i}}findFace(e){for(const t of this.shells){const i=t.findFace(e);if(i)return i}}getAllFaces(){const e=[];return this.shells.forEach((t=>e.push(...t.getAllFaces()))),e}getAllEdges(){const e=[];return this.shells.forEach((t=>e.push(...t.getAllEdges()))),e}getAllVertices(){const e=[];return this.shells.forEach((t=>e.push(...t.getAllVertices()))),e}body(){return this.wrappedBody?this.wrappedBody:super.body()}setBody(e){this.wrappedBody=e}}class va extends oa{edges=[];//! 边集合 vertices=[];//! 顶点集合 wrappedBody=null;//! 所属的body constructor(e){super(null,e),void 0!==e&&(e.vertices.forEach((e=>{this.vertices.push(new fa(e,this))})),e.edges.forEach((e=>{this.edges.push(new ha(e,this))})))}findVertex(e){const t=oa.findBRep(e,this.vertices);if(t)return t}findEdge(e){const t=oa.findBRep(e,this.edges);if(t)return t}isGeom(){return!1}shapeType(){return Ur.WIRE}getAllEdges(){return[...this.edges]}getAllVertices(){return[...this.vertices]}body(){return this.wrappedBody?this.wrappedBody:super.body()}setBody(e){this.wrappedBody=e}}class xa{toSolid(){throw new Error("Method not implemented.")}toShell(){throw new Error("Method not implemented.")}toWire(){throw new Error("Method not implemented.")}toAcorn(){throw new Error("Method not implemented.")}toCompound(){throw new Error("Method not implemented.")}findVertex(e){}findEdge(e){}findFace(e){}findWire(e){}findShell(e){}findSolid(e){}findBRepObject(e){return this.findFace(e)??this.findSolid(e)??this.findVertex(e)??this.findEdge(e)??this.findWire(e)??this.findShell(e)}static calcuBox(e){const t=e.shapeType();if(t===Ur.EDGE)return e.polygon.bndBox();if(t===Ur.FACE)return e.triangulation.bndBox();if(t===Ur.VERTEX){const t=e.point.xyz;return new ea(t,t)}if(t===Ur.WIRE){const t=e,i=new ea;return t.edges.forEach((e=>i.union(this.calcuBox(e)))),i}if(t===Ur.SHELL){const t=e,i=new ea;return t.faces.forEach((e=>i.union(this.calcuBox(e)))),i}if(t===Ur.SOLID){const t=e,i=new ea;return t.shells.forEach((e=>i.union(this.calcuBox(e)))),i}return new ea}}class ya extends xa{solid;//! brep实体对象 constructor(e){super(),this.solid=e,e.setBody(this)}bodyType(){return Gr.BT_SolidBody}toSolid(){return this}findVertex(e){return this.solid.findVertex(e)}findEdge(e){return this.solid.findEdge(e)}findFace(e){return this.solid.findFace(e)}findSolid(e){return e===this.solid.name()?this.solid:void 0}bndBox(){return xa.calcuBox(this.solid)}}class Ma extends xa{shell;//! brep壳对象 constructor(e){super(),this.shell=e,e.setBody(this)}bodyType(){return Gr.BT_ShellBody}toShell(){return this}findVertex(e){return this.shell.findVertex(e)}findEdge(e){return this.shell.findEdge(e)}findFace(e){return this.shell.findFace(e)}findShell(e){return e===this.shell.name()?this.shell:void 0}bndBox(){return xa.calcuBox(this.shell)}}class ba extends xa{wire;//! brep wire对象 constructor(e){super(),this.wire=e,e.setBody(this)}toWire(){return this}bodyType(){return Gr.BT_WireBody}findVertex(e){return this.wire.findVertex(e)}findEdge(e){return this.wire.findEdge(e)}findWire(e){return e===this.wire.name()?this.wire:void 0}bndBox(){return xa.calcuBox(this.wire)}}class Ea extends xa{point;//! BRep 点对象 constructor(e){super(),this.point=e,e.setBody(this)}bodyType(){return Gr.BT_AcornBody}toAcorn(){return this}findVertex(e){return e===this.point.name()?this.point:void 0}bndBox(){return xa.calcuBox(this.point)}}class Sa extends xa{solids=[];//! 实体对象数组 shells=[];//! 壳对象数组 wires=[];//! 线框对象数组 acorns=[];//! 顶点数组 bodyType(){return Gr.BT_CompoundBody}toCompound(){return this}addSubShape(e){switch(e.type){case Ur.SOLID:{const t=new wa(e);return this.solids.push(t),t.setBody(this),!0}case Ur.WIRE:{const t=new va(e);return this.wires.push(t),t.setBody(this),!0}case Ur.SHELL:{const t=new ma(e);return this.shells.push(t),t.setBody(this),!0}case Ur.VERTEX:{const t=new fa(e);return this.acorns.push(t),t.setBody(this),!0}default:return!1}}findVertex(e){for(const t of this.solids){const i=t.findVertex(e);if(i)return i}for(const t of this.shells){const i=t.findVertex(e);if(i)return i}for(const t of this.wires){const i=t.findVertex(e);if(i)return i}for(const t of this.acorns)if(t.name()===e)return t}findEdge(e){for(const t of this.solids){const i=t.findEdge(e);if(i)return i}for(const t of this.shells){const i=t.findEdge(e);if(i)return i}for(const t of this.wires){const i=t.findEdge(e);if(i)return i}}findFace(e){for(const t of this.solids){const i=t.findFace(e);if(i)return i}for(const t of this.shells){const i=t.findFace(e);if(i)return i}}findSolid(e){for(const t of this.solids)if(t.name()===e)return t}findShell(e){for(const t of this.shells)if(t.name()===e)return t}findWire(e){for(const t of this.wires)if(t.name()===e)return t}bndBox(){const e=new ea;return this.solids.forEach((t=>e.union(xa.calcuBox(t)))),this.shells.forEach((t=>e.union(xa.calcuBox(t)))),this.wires.forEach((t=>e.union(xa.calcuBox(t)))),this.acorns.forEach((t=>e.union(xa.calcuBox(t)))),e}}const Ta=e=>{switch(e.type){case Ur.SOLID:return new ya(new wa(e));case Ur.WIRE:return new ba(new va(e));case Ur.SHELL:return new Ma(new ma(e));case Ur.VERTEX:return new Ea(new fa(e));case Ur.COMPOUND:{const t=new Sa,i=e=>{if(e.type===Ur.COMPOUND){const{subShapes:t}=e;t.forEach((e=>{i(e)}))}else t.addSubShape(e)};return i(e),t}default:return null}};class Ca{subAssemblies=[];bodies=[];props;name(){return this.props?.name}static fromCompound(e){if(e.subShapes.length<=0)return null;const t=new Ca,{subShapes:i}=e;return i.forEach((e=>{if(e.type===Ur.COMPOUND){const i=this.fromCompound(e);i&&t.subAssemblies.push(i)}else{const i=Ta(e);i&&t.bodies.push(i)}})),e.props&&(t.props={name:e.props.name}),t}}class _a{pos=new $r(0,0,0);zDir=new $r(0,0,1);xDir=new $r(1,0,0);constructor(e,t,i){e&&this.pos.set(e.x,e.y,e.z),t&&this.zDir.set(t.x,t.y,t.z),i&&this.xDir.set(i.x,i.y,i.z),(t||i)&&this.normalize()}get yDir(){return this.zDir.clone().cross(this.xDir)}normalize(){this.zDir.normalize();const e=(e,t)=>{const i=e.angleTo(t);return i<1e-4||Math.abs(i-Math.PI)<1e-4};let t;t=e(this.zDir,this.xDir)?e(this.zDir,new $r(1,0,0))?this.zDir.clone().cross(new $r(0,1,0)):this.zDir.clone().cross(new $r(1,0,0)):this.zDir.clone().cross(this.xDir),t=t.cross(this.zDir),this.xDir.set(t.x,t.y,t.z),this.xDir.normalize()}toMatrix4(){const e=new ta,t=new $r(0,0,1),i=new $r(1,0,0),n=this.zDir.angleTo(t);if(n>1e-4){const s=t.clone().cross(this.zDir).normalize();Math.abs(n-Math.PI)<1e-4&&s.set(i.x,i.y,i.z),e.premultiply((new ta).makeRotationAxis(s,n)),i.applyMatrix4(e)}const s=this.xDir.angleTo(i);if(s>1e-4){const t=i.clone().cross(this.xDir).normalize();Math.abs(s-Math.PI)<1e-4&&t.set(this.zDir.x,this.zDir.y,this.zDir.z),e.premultiply((new ta).makeRotationAxis(t,s))}return this.pos.length()>1e-4&&e.premultiply((new ta).makeTranslation(this.pos.x,this.pos.y,this.pos.z)),e}}var Ra,Aa,Pa,Oa,La,Da,za,Ia,Ba,Fa,Na,Ua,Ga,Ha,ka,ja,Va;!function(e){e[e.Line=0]="Line",e[e.Circle=1]="Circle",e[e.Ellipse=2]="Ellipse",e[e.Parabola=3]="Parabola",e[e.Hyperbola=4]="Hyperbola",e[e.OffsetCurve=5]="OffsetCurve",e[e.BezierCurve=6]="BezierCurve",e[e.BSplineCurve=7]="BSplineCurve",e[e.Other=8]="Other"}(Ra||(Ra={}));class Wa{Aabb;Shape;ParentNode;LeftNode;RightNode;constructor(e,t,i,n,s){this.Aabb=e,this.Shape=t,this.ParentNode=i,this.LeftNode=n,this.RightNode=s}get IsLeaf(){return void 0===this.LeftNode}}class Ka{rootNode;shapeToNodeMap;constructor(){this.shapeToNodeMap=new Map}addShape(e){const t=e.getAABB();if(void 0===this.rootNode)return this.rootNode=new Wa(t,e,void 0,void 0,void 0),void this.shapeToNodeMap.set(e,this.rootNode);let i=this.rootNode,n=this.rootNode.Aabb;for(;!i.IsLeaf;){const e=i.LeftNode,s=i.RightNode,r=i.Aabb.merge(t),a=e.Aabb.merge(t),o=s.Aabb.merge(t),h=r.space-i.Aabb.space;if(h>0){let t,d;if(t=e.IsLeaf?a.space+h:a.space-e.Aabb.space+h,d=s.IsLeaf?o.space+h:o.space-s.Aabb.space+h,r.space<1.3*t&&r.space<1.3*d)break;i.Aabb=r,t>d?(i=s,n=o):(i=e,n=a)}i.Aabb=r;a.space-e.Aabb.space>o.space-s.Aabb.space?(i=s,n=o):(i=e,n=a)}const s=new Wa(i.Aabb,i.Shape,i,i.RightNode,i.LeftNode);void 0!==s.Shape&&this.shapeToNodeMap.set(s.Shape,s),i.LeftNode=s,i.RightNode=new Wa(t,e,i,void 0,void 0),i.Aabb=i===this.rootNode?this.rootNode.Aabb.merge(t):n,i.Shape=void 0,this.shapeToNodeMap.set(e,i.RightNode)}removeShape(e){if(!this.shapeToNodeMap.has(e))return;const t=this.shapeToNodeMap.get(e);this.removeNode(t),this.shapeToNodeMap.delete(e)}getShapesOverlappingWith(e){if(void 0===this.rootNode)return[];const t=[],i=[this.rootNode];let n=0;for(;i.length>n;){const s=i[n].LeftNode,r=i[n].RightNode;i[n]===this.rootNode&&this.rootNode.Shape&&this.rootNode.Shape.containsPoint(e)&&t.push(this.rootNode.Shape),s&&s.Aabb.containsPoint(e)&&(s.IsLeaf?s.Shape.containsPoint(e)&&t.push(s.Shape):i.push(s)),r&&r.Aabb.containsPoint(e)&&(r.IsLeaf?r.Shape.containsPoint(e)&&t.push(r.Shape):i.push(r)),n+=1}return t}getAllNodes(){const e=[];return void 0!==this.rootNode&&this.nodeIterator(this.rootNode,e),e}nodeIterator(e,t){t.push(e),e.IsLeaf||(this.nodeIterator(e.RightNode,t),this.nodeIterator(e.LeftNode,t))}removeNode(e){if(void 0===e.ParentNode)return void(this.rootNode=void 0);const t=e.ParentNode,i=t.LeftNode===e?t.RightNode:t.LeftNode;if(t.Aabb=i.Aabb,t.Shape=i.Shape,t.LeftNode=i.LeftNode,t.RightNode=i.RightNode,!i.IsLeaf){const e=i.LeftNode,n=i.RightNode;e.ParentNode=t,n.ParentNode=t}this.shapeToNodeMap.has(t.Shape)&&this.shapeToNodeMap.set(t.Shape,t);let n=t.ParentNode;for(;void 0!==n;)n.Aabb=n.LeftNode.Aabb.merge(n.RightNode.Aabb),n=n.ParentNode}ray2Tree(e){if(void 0===this.rootNode)return null;if(e.origin instanceof a&&e.direction instanceof a&&this.rootNode.Aabb.lowPoint instanceof a&&this.rootNode.Aabb.highPoint instanceof a){const t=[],i=[];for(i.push(this.rootNode);i.length>0;){const n=i[i.length-1];i.pop();const s=new q(n.Aabb.lowPoint,n.Aabb.highPoint),r=new a;null!==e.intersectBox(s,r)&&(n.IsLeaf?t.push(n.Shape):(n.LeftNode&&i.push(n.LeftNode),n.RightNode&&i.push(n.RightNode)))}return t}return null}}class Ya{lowPoint;highPoint;constructor(e,t,i,n,s,o){const h=Math.min(e,n),d=Math.max(e,n),p=Math.min(t,s),l=Math.max(t,s);if(null!==i&&null!==o){const e=Math.min(i,o),t=Math.max(i,o);this.lowPoint=new a(h,p,e),this.highPoint=new a(d,l,t)}else this.lowPoint=new r(h,p),this.highPoint=new r(d,l)}merge(e){return new Ya(Math.min(this.lowPoint.x,e.lowPoint.x),Math.min(this.lowPoint.y,e.lowPoint.y),this.is3D?Math.min(this.lowPoint.z,e.lowPoint.z):null,Math.max(this.highPoint.x,e.highPoint.x),Math.max(this.highPoint.y,e.highPoint.y),this.is3D?Math.max(this.highPoint.z,e.highPoint.z):null)}overlaps(e){if(this.is3D){const t=this.highPoint.z>e.lowPoint.z,i=this.lowPoint.ze.lowPoint.x&&this.lowPoint.xe.lowPoint.y&&this.lowPoint.ye.lowPoint.x&&this.lowPoint.xe.lowPoint.y&&this.lowPoint.ye.z;return this.lowPoint.xe.x&&this.lowPoint.ye.y&&t&&i}return this.lowPoint.xe.x&&this.lowPoint.ye.y}get is3D(){return this.lowPoint instanceof a}get width(){return this.highPoint.x-this.lowPoint.x}get height(){return this.highPoint.y-this.lowPoint.y}get depth(){return this.is3D?this.highPoint.z-this.lowPoint.z:0}get space(){const e=this.width*this.height;return this.is3D?e*this.depth:e}}class Xa{aabb;VectorList=[];type;constructor(e,t,i){this.type="TriAABBShape";const n=Math.min(e.x,t.x,i.x),s=Math.max(e.x,t.x,i.x),r=Math.min(e.y,t.y,i.y),o=Math.max(e.y,t.y,i.y);this.aabb=e instanceof a&&t instanceof a&&i instanceof a?new Ya(n,r,Math.min(e.z,t.z,i.z),s,o,Math.max(e.z,t.z,i.z)):new Ya(n,r,null,s,o,null),this.VectorList.push(e),this.VectorList.push(t),this.VectorList.push(i)}getAABB(){return this.aabb}containsPoint(e){return this.aabb.containsPoint(e)}getTypeName(){return this.type}points(){return this.VectorList}}class qa{aabb;VectorList=[];type;constructor(e,t){this.type="LineAABBShape";const i=Math.min(e.x,t.x),n=Math.max(e.x,t.x),s=Math.min(e.y,t.y),r=Math.max(e.y,t.y);this.aabb=e instanceof a&&t instanceof a?new Ya(i,s,Math.min(e.z,t.z),n,r,Math.max(e.z,t.z)):new Ya(i,s,null,n,r,null),this.VectorList.push(e),this.VectorList.push(t)}getAABB(){return this.aabb}containsPoint(e){return this.aabb.containsPoint(e)}getTypeName(){return this.type}points(){return this.VectorList}}class Za{nodes=[];lines=[];surfs=[];constructor(e){e?.forEach((e=>this.nodes.push(e.clone())))}static createIndex(e){const t=[];if(e.isSegment)t.push(...e.indices);else for(let i=1;ie.expandByPoint(t))),e}static createFromIPoly(e){const t=new Za;return e.nodes.forEach((e=>{t.nodes.push(new $r(e[0],e[1],e[2]))})),e.surfs?.forEach((e=>{const i=[];e.triangles.forEach((e=>{i.push(new pa(e[0],e[1],e[2]))})),e.props?t.surfs.push({triangles:i,props:e.props}):t.surfs.push({triangles:i})})),e.lines?.forEach((e=>{const i=[],n=e.indices[0]instanceof Array;e.indices.forEach((e=>{n?i.push(e[0],e[1]):i.push(e)})),e.props?t.lines.push({indices:i,isSegment:n,props:e.props}):t.lines.push({indices:i,isSegment:n})})),t}static ray2Tree(e,t){const i=t.ray2Tree(e);let n=Number.MAX_VALUE;return i?.forEach((t=>{if("TriAABBShape"===t.getTypeName()){const i=t.points();if(3===i.length&&i[0]instanceof a&&i[1]instanceof a&&i[2]instanceof a){const t=new $r,s=e.intersectTriangle(i[0],i[1],i[2],!1,t);null!==s&&(n=Math.min(n,s.distanceTo(e.origin)))}}if("LineAABBShape"===t.getTypeName()){const i=t.points();if(2===i.length&&i[0]instanceof a&&i[1]instanceof a){const t=new $r,s=new $r;e.distanceSqToSegment(i[0],i[1],t,s)<1e-6&&(n=Math.min(n,t.distanceTo(e.origin)))}}})),n}static calDistancewithAABB(e,t,i){let n=Number.MAX_VALUE,s=-Number.MAX_VALUE;const r=new Ka;e?.surfs.forEach((t=>{t.triangles.forEach((t=>{const i=e.nodes[t.node1],n=e.nodes[t.node2],s=e.nodes[t.node3],a=new Xa(i,n,s);r.addShape(a)}))})),e?.lines.forEach((t=>{const{isSegment:i}=t,n=[];i?t.indices.forEach(((e,t)=>{1!==Math.abs(t%2)&&0!==t||n.push(e)})):t.indices.forEach((e=>{n.push(e)})),n.forEach(((t,i)=>{if(0!==i){const t=new qa(e.nodes[n[i]],e.nodes[n[i-1]]);r.addShape(t)}}))}));const a=new Ka;t?.surfs.forEach((e=>{e.triangles.forEach((e=>{const i=t.nodes[e.node1],n=t.nodes[e.node2],s=t.nodes[e.node3],r=new Xa(i,n,s);a.addShape(r)}))})),t?.lines.forEach((e=>{const{isSegment:i}=e,n=[];i?e.indices.forEach(((e,t)=>{1!==Math.abs(t%2)&&0!==t||n.push(e)})):e.indices.forEach((e=>{n.push(e)})),n.forEach(((e,i)=>{if(0!==i){const e=new qa(t.nodes[n[i]],t.nodes[n[i-1]]);a.addShape(e)}}))}));const o=new we;e.nodes.forEach((e=>{o.origin.set(e.x,e.y,e.z),o.direction.set(i.x,i.y,i.z),n=Math.min(n,this.ray2Tree(o,a)),o.direction.set(-i.x,-i.y,-i.z),s=Math.max(s,-this.ray2Tree(o,a))})),t.nodes.forEach((e=>{o.origin.set(e.x,e.y,e.z),o.direction.set(i.x,i.y,i.z),s=Math.max(s,-this.ray2Tree(o,r)),o.direction.set(-i.x,-i.y,-i.z),n=Math.min(n,this.ray2Tree(o,r))}));let h=0;return h=Math.abs(s)Qa.zeroTol){s.nodeList.push(new ra(0,0,0)),s.normalList.push(new da(0,0,-1)),p+=1;for(let t=0;t1e-4&&s.triangleList.push(new pa(o,r,l)),t>1e-4&&s.triangleList.push(new pa(l,c,o))}if(p+=2*a,t>1e-4){s.nodeList.push(new ra(0,0,i)),s.normalList.push(new da(0,0,1)),p+=1;for(let e=0;er.nodeList.push(e))),h.normalList.forEach((e=>r.normalList.push(e))),h.triangleList.forEach((e=>{r.triangleList.push(new pa(d+e.node1,d+e.node2,d+e.node3))})),r}static cutPlaneByBox(e,t){const i=-t.zDir.dot(t.pos),n=new re(t.zDir,i);if(!n.intersectsBox(e))return null;const{min:s}=e,{max:r}=e,o=[s,new a(r.x,s.y,s.z),new a(r.x,r.y,s.z),new a(s.x,r.y,s.z),new a(s.x,s.y,r.z),new a(r.x,s.y,r.z),r,new a(s.x,r.y,r.z)],h=[0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7],d=[];for(let e=0;ee.distanceTo(s)<1e-4))&&d.push(s)}if(d.length<3)return null;const p=d[0].clone();for(let e=1;e0?l.push(i):l.push(-i)}const u=new Za(d),g=[];for(let e=0;e{a.push(e.xyz.clone())}));const o=new Za(a);for(let e=0;ee.clone())));const i=e[1].length-(n?2:1);for(let e=0;ee.clone())));for(let n=0;ne.clone())).concat(e[1].map((e=>e.clone()))));for(let e=0;et.nodes.push(...e.map((e=>e.clone())))));const h=[],d=[],p=[];for(let e=0;ee.applyMatrix4(r.toMatrix4())));const l=s+1;if(o.nodes.push(...p),a>this.zeroTol){const e=this.computeArcNodes(i,a,h,d,s,3);if(e.length!==l)throw new Error("Loop length are not equal for sphere2D");r&&e.forEach((e=>e.applyMatrix4(r.toMatrix4()))),o.nodes.push(...e);const t=[],n=[];for(let e=0;e=Math.abs(t.x))throw new Error("Radius is bigger than center.x for torus2D");if(!Number.isInteger(n))throw new Error("segments must be integer for quarter torus2D");if(i){const i=this.computeArcNodes(t,e,0,Math.PI,n,3);if(i.length!==n+1)throw new Error("loop length not equal segments + 1");s&&i.forEach((e=>e.applyMatrix4(s.toMatrix4())));const r=new Za(i),a=[];for(let e=0;ee.applyMatrix4(s.toMatrix4())));const a=new Za(r),o=[];for(let e=0;et)throw new Error("The radius of the cylinder cannot be smaller than the radius of the hole.");const[d,p,l,c]=s.map((e=>e=t-e-this.zeroTol)throw new Error("Param Error, r1 + r2 >= R2 - R1");if(l+c>=t-e-this.zeroTol)throw new Error("Param Error, r3 + r4 >= R2 - R1");if(d+c>=i-this.zeroTol)throw new Error("Param Error, r1 + r4 >= height");if(p+l>=i-this.zeroTol)throw new Error("Param Error, r2 + r3 >= height");const[u,g,f,m]=r;if(ethis.zeroTol&&"Fillet"===g||l>this.zeroTol&&"Fillet"===f))throw new Error("Param Error, If R1 is zero and r2 or r3 cannot be filleted.");const w=[],v=[];if(w.push(n.clone().add(new a(t,0,i-d))),v.push(w.length-1),d>this.zeroTol){if("Chamfer"===u)w.push(n.clone().add(new a(t-d,0,i)));else{const e=n.clone().add(new a(t-d,0,i-d));w.push(...this.computeArcNodes(e,d,0,Math.PI/2,h,2,!1))}v.push(w.length-1)}if(w.push(n.clone().add(new a(e+p,0,i))),v.push(w.length-1),p>this.zeroTol){if("Chamfer"===g)w.push(n.clone().add(new a(e,0,i-p)));else{const t=n.clone().add(new a(e+p,0,i-p));w.push(...this.computeArcNodes(t,p,Math.PI/2,Math.PI,h,2,!1))}v.push(w.length-1)}const x=w.length-1;if(o)return w.push(n.clone().add(new a(e,0,i/2))),v.push(w.length-1),w.push(n.clone().add(new a(t,0,i/2))),v.push(w.length-1),[w,v,x];if(w.push(n.clone().add(new a(e,0,l))),v.push(w.length-1),l>this.zeroTol){if("Chamfer"===f)w.push(n.clone().add(new a(e+l)));else{const t=n.clone().add(new a(e+l,0,l));w.push(...this.computeArcNodes(t,l,Math.PI,-Math.PI/2,h,2,!1))}v.push(w.length-1)}if(w.push(n.clone().add(new a(t-c))),v.push(w.length-1),c>this.zeroTol){if("Chamfer"===m)w.push(n.clone().add(new a(t,0,c)));else{const e=n.clone().add(new a(t-c,0,c));w.push(...this.computeArcNodes(e,c,-Math.PI/2,0,h,2,!1))}v.push(w.length-1)}return[w,v,x]}static cylinder(e,t,i,n=new $r,s=[0,0,0,0],r=["Chamfer","Chamfer","Chamfer","Chamfer"],o=9,h=!0,d=[0,2*Math.PI],p=!1,l=void 0){if(ie.applyMatrix4(l.toMatrix4())));const e=new Za;return this.create2DShape(e,c,u),e}const f=new Za,m=d[0];let w=d[1];for(;w{const t=e.x-n.x;if(te.applyMatrix4(l.toMatrix4()))),d}));for(let e=0;e1||i.length>1){const n=u[e]>g?[t,i]:[i,t];this.addSurfaceByLoops(n,f,this.floatEqual(t[0].x,i[0].x)?3:2,!v)}}else{const t=x.slice(u[e],u[e+1]+1);if(1===t[t.length-1].length){const e=[];for(let i=0;it[1][0].x?1:2,!v)}if(v){this.addSurfaceByLoops([x[x.length-1],x[0]],f,0,!v);const t=[],i=[];if(x.forEach((e=>{t.push(e[0]),i.push(e[e.length-1])})),this.addOneTopOrBottomPlane(f,t,u),this.addOneTopOrBottomPlane(f,i,u),ee===g));if(e>=0){const t=f.lines.length-u.length+e;if(f.lines.splice(t,1),this.floatEqual(w-m,Math.PI)){const t=f.lines.length-2*u.length+e+1;f.lines.splice(t,1)}}}}else this.addSurfaceByLoops([x[x.length-1],x[0]],f,0);return f}static box2DNodes(e,t,i=new a,n=[0,0,0,0],s=["Chamfer","Chamfer","Chamfer","Chamfer"],r=9){if(e{e.setY(e.z),e.setZ(i.z)})),[d,p]}static addOneTopOrBottomPlane(e,t,i,n=!0){const s=e.nodes.length;if(t.length<3)throw new Error("2 point can not create a plane!");Qa.create2DShape(e,t,i);const r=[];for(let e=0;ee.applyMatrix4(d.toMatrix4())));const e=new Za;return this.create2DShape(e,p,l),e}const c=new Za,u=p.map((e=>e.clone().add(new a(0,0,i))));d&&(p.forEach((e=>e.applyMatrix4(d.toMatrix4()))),u.forEach((e=>e.applyMatrix4(d.toMatrix4())))),this.addOneTopOrBottomPlane(c,p,l,!1),this.addOneTopOrBottomPlane(c,u,l);for(let e=0;et));if(!r)return o&&h.forEach((e=>e.applyMatrix4(o.toMatrix4()))),this.create2DShape(d,h,p),d;const l=h.map((e=>e.clone().add(new a(0,0,t))));o&&(h.forEach((e=>e.applyMatrix4(o.toMatrix4()))),l.forEach((e=>e.applyMatrix4(o.toMatrix4())))),this.addOneTopOrBottomPlane(d,h,p,!1),this.addOneTopOrBottomPlane(d,l,p);for(let e=0;ei.node1===e&&i.node2===t||i.node1===e&&i.node2===t))<0&&(this.edges.push({node1:e,node2:t}),this.addNode(e),this.addNode(t))}addNode(e){this.nodes.indexOf(e)<0&&this.nodes.push(e)}copy(){const e=new ho(this.id,this.nodes);return this.faces.forEach((t=>{e.addFace(t.nodes)})),e}}class po{keys=new Map;hasher;constructor(e){this.hasher=e}has(e){return this.keys.has(this.hasher(e))}add(e){const t=this.hasher(e);return!this.keys.has(t)&&(this.keys.set(t,e),!0)}remove(e){const t=this.hasher(e);return!!this.keys.has(t)&&(this.keys.delete(t),!0)}getKeys(){const e=[];return this.keys.forEach((t=>e.push(t))),e}get size(){return this.keys.size}firstKey(){if(0!==this.keys.size)return this.keys.values().next().value}}class lo{keys=new Map;values=new Map;hasher;constructor(e){this.hasher=e}has(e){return this.keys.has(this.hasher(e))}set(e,t){const i=this.hasher(e);this.keys.set(i,e),this.values.set(i,t)}remove(e){const t=this.hasher(e);return!!this.keys.has(t)&&(this.keys.delete(t),this.values.delete(t),!0)}getKeys(){const e=[];return this.keys.forEach((t=>e.push(t))),e}getValues(){const e=[];return this.values.forEach((t=>e.push(t))),e}get(e){const t=this.hasher(e);return this.values.get(t)}get size(){return this.keys.size}firstKey(){if(0!==this.keys.size)return this.keys.values().next().value}firstValue(){if(0!==this.keys.size)return this.values.get(this.keys.keys().next().value)}}function co(e){return e.node1>e.node2?`${e.node2.toFixed(0)}-${e.node1.toFixed(0)}`:`${e.node1.toFixed(0)}-${e.node2.toFixed(0)}`}function uo(e){const t=e.nodes.map((e=>e));t.sort(((e,t)=>e-t));let i="";return t.forEach((e=>{i+=`-${e.toFixed(0)}`})),i}class go{nodes=new Map;//! 网格节点数组 elements=new Map;//! 网格单元数组 props=[];//! 属性数据 constructor(e,t){e.forEach((e=>{this.nodes.set(e.id,e)})),t.forEach((e=>{this.elements.set(e.id,e)}))}getNodesFromFace(e,t){const i=this.getMeshFacesFromFace(t,e,void 0),n=new Set,s=[],r=e=>{!n.has(e)&&this.nodes.has(e)&&(s.push(this.nodes.get(e)),n.add(e))};return i.forEach((e=>{e.nodes.forEach((e=>r(e)))})),s}getMeshFaces(e,t){return this.getMeshFacesFromFace(t,void 0,e)}getMeshFacesFromFace(e,t,i){const n=new lo(co),s=new lo(uo);this.elements.forEach((e=>{e.faces.forEach((e=>{let t=!0;if(e.nodes.forEach((e=>{this.nodes.has(e)||(t=!1)})),!t)return;s.has(e)||s.set(e,new po(co));const i=s.get(e);for(let t=0;t{const t=a.get(e);if(t)return t;const i=[];if(e.nodes.forEach((e=>{const t=this.nodes.get(e);t&&i.push(t)})),i.length<3)return null;const n=new $r(i[1].coord[0]-i[0].coord[0],i[1].coord[1]-i[0].coord[1],i[1].coord[2]-i[0].coord[2]).normalize(),s=new $r(i[2].coord[0]-i[1].coord[0],i[2].coord[1]-i[1].coord[1],i[2].coord[2]-i[1].coord[2]).normalize(),r=n.cross(s).normalize();return a.set(e,r),r},h=new lo(co),d=new po(co),p=new po(uo);for(p.add(r),s.get(r)?.getKeys().forEach((e=>h.set(e,r)));h.size>0;){const t=h.firstKey(),i=h.firstValue();if(void 0===t||void 0===i)break;h.remove(t),d.add(t);const r=n.get(t)?.getKeys();if(void 0===r||0===r.length)continue;const a=uo(i),l=o(i);if(null!==l)for(const t of r){if(uo(t)===a)continue;const i=o(t);if(null!==i&&i.angleTo(l){h.has(e)?(h.remove(e),d.add(e)):d.has(e)||h.set(e,t)}))}}}return p.getKeys()}getMeshEdgesByFeat(e,t){const i=this.getEdgeBorders();if(!i.has(t))return[t];const n=[t];let s=this.nodes.get(t.node1),r=this.nodes.get(t.node2);const a=t=>{const a=()=>{t?s=void 0:r=void 0},o=t?s:r;if(void 0===o)return;const h=i.getKeys().find((e=>e.node1===o.id||e.node2===o.id));if(void 0===h)return void a();const d=t?n[0]:n[n.length-1],p=this.nodes.get(d.node1===o.id?d.node2:d.node1),l=this.nodes.get(h.node1===o.id?h.node2:h.node1);if(void 0===p||void 0===l)return void a();const c=new $r(p.coord[0],p.coord[1],p.coord[2]),u=new $r(o.coord[0],o.coord[1],o.coord[2]),g=new $r(l.coord[0],l.coord[1],l.coord[2]).sub(u),f=u.sub(c);g.angleTo(f){t.edges.forEach((i=>{e.has(i)?e.remove(i):e.set(i,t.id)}))})),e}static createFromData(e){const t=[],i=[];e.nodes.forEach((e=>{t.push({id:e[0],coord:[e[1],e[2],e[3]]})}));const n=new Map;return e.faces?.forEach((e=>{n.set(e[0],e.slice(1))})),e.elements.forEach((t=>{const s=e.faces?Pa.FaceBasedEle:t[0];if(s===Pa.Triangle_3)i.push(new io(t[1],t.slice(2)));else if(s===Pa.Quadrangle_4)i.push(new eo(t[1],t.slice(2)));else if(s===Pa.Tetrahedron_4)i.push(new to(t[1],t.slice(2)));else if(s===Pa.Hexahedron_8)i.push(new Ja(t[1],t.slice(2)));else if(s===Pa.Plane_Polygon)i.push(new oo(t[1],t.slice(2)));else if(s===Pa.Tetrahedron_10_Order2)i.push(new ao(t[1],t.slice(2)));else if(s===Pa.Hexahedron_20_Order2)i.push(new so(t[1],t.slice(2)));else if(s===Pa.Hexahedron_27_Order2)i.push(new ro(t[1],t.slice(2)));else if(s===Pa.Line_2)i.push(new no(t[1],t.slice(2)));else if(s===Pa.FaceBasedEle){const e=new ho(t[0],[]);t.slice(1).forEach((t=>{const i=n.get(t);i&&e.addFace(i)})),i.push(e)}})),new go(t,i)}attachProperty(e,t,i,n){if(""===e)return!1;if(void 0!==this.props.find((t=>t.name===e)))return!1;const s=e=>{let t=0;return e.forEach((e=>{t+=e*e})),Math.sqrt(t)},r=new Map,a={min:n.slice(1,t+1),max:n.slice(1,t+1)};if(t>1){const e=s(a.min);a.min.push(e),a.max.push(e)}for(let e=0;e1&&i.push(s(i));for(let e=0;ea.max[e]&&(a.max[e]=i[e]);r.set(n[e],i)}return this.props.push({name:e,size:t,forNode:i,data:r,range:a}),!0}getProperty(e){if(""!==e)return this.props.find((t=>t.name===e))}bndBox(){const e=new ea;return this.nodes.forEach((t=>e.expandByPoint(new $r(t.coord[0],t.coord[1],t.coord.length>2?t.coord[2]:0)))),e}to3DMeshByExtrude(e,t){const i=this.getEdgeBorders(),n=new Map,s=new Map;let r=0,a=this.nodes.size;this.nodes.forEach(((i,o)=>{n.set(o,{id:r,coord:[i.coord[0],i.coord[1],i.coord[2]+e]}),s.set(o,{id:a,coord:[i.coord[0],i.coord[1],i.coord[2]-t]}),r+=1,a+=1}));const o=[],h=[];let d=0;this.elements.forEach((e=>{const t=[],i=[];e.nodes.forEach((e=>{t.push(n.get(e).id),i.push(s.get(e).id)}));const r=e.copy();r.id=d,r.setNodes(t),o.push(r),h.push(e.id),d+=1;const a=e.copy();a.id=d,i.reverse(),a.setNodes(i),o.push(a),h.push(e.id),d+=1})),i.getKeys().forEach((e=>{const t=[];t.push(n.get(e.node2).id),t.push(n.get(e.node1).id),t.push(s.get(e.node1).id),t.push(s.get(e.node2).id),o.push(new eo(d,t)),h.push(i.get(e)),d+=1}));const p=[];n.forEach((e=>p.push(e))),s.forEach((e=>p.push(e)));const l=new go(p,o);return this.props.forEach((e=>{const t=new Map;e.forNode?e.data.forEach(((e,i)=>{t.set(n.get(i).id,e),t.set(s.get(i).id,e)})):h.forEach(((i,n)=>{t.set(i,e.data.get(n))})),l.props.push({forNode:e.forNode,name:e.name,size:e.size,data:t,range:e.range})})),l}to3DMeshByRevolve(e,t,i){const n=this.getEdgeBorders(),s=new Map,r=new Map;let a=0,o=this.nodes.size;const h=(e,t)=>{const i=t/180*Math.PI,n=-e[0]*Math.sin(i);return[e[0]*Math.cos(i),e[1],n]};this.nodes.forEach(((i,n)=>{s.set(n,{id:a,coord:h(i.coord,e)}),r.set(n,{id:o,coord:h(i.coord,e+t)}),a+=1,o+=1}));const d=[],p=[];let l=0;this.elements.forEach((e=>{const t=[],i=[];e.nodes.forEach((e=>{t.push(s.get(e).id),i.push(r.get(e).id)}));const n=e.copy();n.id=l,n.setNodes(t),d.push(n),p.push(e.id),l+=1;const a=e.copy();a.id=l,i.reverse(),a.setNodes(i),d.push(a),p.push(e.id),l+=1}));const c=Math.floor(t/i),u=t/c,g=new Map,f=t=>{if(g.has(t))return;const i=[];for(let n=0;n<=c;n+=1)i.push({id:o,coord:h(this.nodes.get(t).coord,e+n*u)}),o+=1;g.set(t,i)};n.getKeys().forEach((e=>{f(e.node1),f(e.node2);for(let t=0;tm.push(e))),r.forEach((e=>m.push(e))),g.forEach((e=>{e.forEach((e=>m.push(e)))}));const w=new go(m,d);return this.props.forEach((e=>{const t=new Map;e.forNode?e.data.forEach(((e,i)=>{t.set(s.get(i).id,e),t.set(r.get(i).id,e),g.get(i)?.forEach((i=>{t.set(i.id,e)}))})):p.forEach(((i,n)=>{t.set(n,e.data.get(i))})),w.props.push({forNode:e.forNode,name:e.name,size:e.size,data:t,range:e.range})})),w}}class fo{dimension;range;meshes=[];constructor(e){this.dimension=e.dimension,this.range=e.range,this.meshes=e.meshes}static createFromBoxLib(e){const{dimension:t}=e;let i;if(1===t)i={xMin:e.range[0],xMax:e.range[1]};else if(2===t)i={xMin:e.range[0],yMin:e.range[1],xMax:e.range[2],yMax:e.range[3]};else{if(3!==t)throw Error(`Invalid demension: ${t}`);i={xMin:e.range[0],yMin:e.range[1],zMin:e.range[2],xMax:e.range[3],yMax:e.range[4],zMax:e.range[5]}}const n=[];return e.mesh_levels.forEach((e=>{let s=0,r=0,a=0;const o=[],h=[],d=[];if(t>=1){s=e.resolution[0];const t=(i.xMax-i.xMin)/s;for(let n=0;n<=e.resolution[0];n+=1)o.push(i.xMin+t*n)}if(t>=2){r=e.resolution[1];const t=(i.yMax-i.yMin)/r;for(let n=0;n<=e.resolution[1];n+=1)h.push(i.yMin+t*n)}if(t>=3){a=e.resolution[2];const t=(i.zMax-i.zMin)/a;for(let n=0;n<=e.resolution[2];n+=1)d.push(i.zMin+t*n)}const p=[];1===t?(e.cell_idx.forEach((e=>{const t={i:e,index:e};p.push(t)})),n.push({level:e.level,xCoords:o,cells:p})):2===t?(e.cell_idx.forEach((e=>{const t={i:e%s,j:Math.floor(e/s),index:e};p.push(t)})),n.push({level:e.level,xCoords:o,yCoords:h,cells:p})):3===t&&(e.cell_idx.forEach((e=>{const t={i:e%(s*r)%s,j:Math.floor(e%(s*r)/s),k:Math.floor(e/(s*r)),index:e};p.push(t)})),n.push({level:e.level,xCoords:o,yCoords:h,zCoords:d,cells:p}))})),new fo({dimension:t,range:i,meshes:n})}bndBox(){const e=new ea;return e.min.x=this.range.xMin,e.max.x=this.range.xMax,this.dimension>1&&(e.min.y=this.range.yMin,e.max.y=this.range.yMax),this.dimension>2&&(e.min.z=this.range.zMin,e.max.z=this.range.zMax),e}}!function(e){e[e.OT_BRepOwner=0]="OT_BRepOwner",e[e.OT_SelectOwner=1]="OT_SelectOwner",e[e.OT_MeshNode=2]="OT_MeshNode",e[e.OT_MeshEdge=3]="OT_MeshEdge",e[e.OT_MeshFace=4]="OT_MeshFace",e[e.OT_MeshElement=5]="OT_MeshElement",e[e.OT_Triangulation=6]="OT_Triangulation",e[e.OT_PolyGeometry=7]="OT_PolyGeometry",e[e.OT_Custom=8]="OT_Custom"}(Oa||(Oa={}));class mo{owner;type;constructor(e,t){this.owner=e,this.type=t}asBRepObject(){return this.type===Oa.OT_BRepOwner?this.owner:null}asSelectElement(){return this.type===Oa.OT_SelectOwner?this.owner:null}}!function(e){e[e.Invalid=0]="Invalid",e[e.Points=1]="Points",e[e.LineSegments=2]="LineSegments",e[e.Mesh=3]="Mesh",e[e.Text=4]="Text",e[e.AnnoLine=5]="AnnoLine"}(La||(La={}));class wo{wrappedGroup;//! element所属的group constructor(e){this.wrappedGroup=e,e.eles.push(this)}isGeomEle(){return!1}isAnnotation(){return!1}unHilight(){this.hilight(this.wrappedGroup.config)}hilightOwner(e,t){}unHilightOwner(e){}get group(){return this.wrappedGroup}}class vo{wrappedOwner=null;//! 所关联的对象 wrappedEle;//! 所属的渲染元素 wrappedStartIndex=-1;//! 在attribute中起始下标 wrappedLength=0;//! 在attribute中的长度 constructor(e){this.wrappedEle=e}get owner(){return this.wrappedOwner}set owner(e){this.wrappedOwner=e}get element(){return this.wrappedEle}get start(){return this.wrappedStartIndex}set start(e){this.wrappedStartIndex=e}get length(){return this.wrappedLength}set length(e){this.wrappedLength=e}}class xo extends wo{items=[];//! element组成单元列表 wrappedShapes=null;//! 底层显示元素对象 constructor(e){super(e)}isGeomEle(){return!0}transform(e){this.shapes&&(this.shapes.matrix=e)}removeByOwner(e,t,i){this.shapes?.startBatchConfigUpdate();return[...this.items].forEach((e=>{e.owner?.owner===t&&this.removeItem(e,i)})),this.shapes?.finishBatchConfigUpdate(),!0}isEmpty(){return 0===this.items.length}get visible(){return!!this.shapes&&this.shapes.visible}set visible(e){this.shapes&&(this.shapes.visible=e)}get shapes(){return this.wrappedShapes}set shapes(e){this.wrappedShapes=e}getRenderItem(e){return this.items.find((t=>t.owner?.owner===e))}remove(e){return!!this.shapes&&(e.remove(this.shapes),!0)}createItem(e,t,i){const n=new vo(this);return n.owner=e,n.start=t,n.length=i,this.items.push(n),n}displayItem(e,t,i=!1){if(!this.shapes)return!1;if(i)this.shapes.updateConfig(t.start,t.length,e);else{const i=this.wrappedGroup.config.customCfgs.get(t);this.shapes.updateConfig(t.start,t.length,i||e)}return!0}displayAllItems(e,t=!1){this.wrappedShapes?.startBatchConfigUpdate(),this.items.forEach((i=>{this.displayItem(e,i,t)})),this.wrappedShapes?.finishBatchConfigUpdate()}removeItem(e,t=!1){if(!this.shapes)return!1;const i=this.items.indexOf(e);return!(i<0)&&(this.shapes.updateConfig(e.start,e.length,void 0),t&&this.items.splice(i,1),!0)}removeAllItems(e=!1){if(!this.shapes)return!1;let t=!0;return this.wrappedShapes?.startBatchConfigUpdate(),this.items.forEach((i=>{this.removeItem(i,e)||(t=!1)})),this.wrappedShapes?.finishBatchConfigUpdate(),t}get group(){return this.wrappedGroup}}class yo extends xo{display(e,t){return!!this.shapes&&(e.add(this.shapes,t.clippingMethod),this.displayAllItems(t.lineConfig),!0)}posAttr(){if(!this.shapes)throw Error("Null shape data!");return this.shapes.position}type(){return La.LineSegments}fillData(e,t,i){this.shapes=i?new gr(pr.Segment,e,t,...i):new gr(pr.Segment,e,t)}copyData(e){const i=new yo(e);return i.shapes=new gr(pr.Segment,this.shapes.position,this.shapes.index),this.shapes.matrix.equals(new t)||i.transform(this.shapes.matrix),i}isSameGeom(e){return e.type()===La.LineSegments&&this.shapes.position===e.shapes.position}hilight(e){this.displayAllItems(e.lineConfig,!0)}unHilight(){this.displayAllItems(this.group.config.lineConfig,!1)}hilightOwner(e,t){const i=this.items.find((e=>e.owner?.owner===t));i&&this.displayItem(e.lineConfig,i,!0)}unHilightOwner(e){const t=this.items.find((t=>t.owner?.owner===e));t&&this.displayItem(this.group.config.lineConfig,t,!1)}}class Mo extends xo{display(e,t){return!!this.shapes&&(e.add(this.shapes,t.clippingMethod),e.setClippingColor(this.shapes,t.clippingColor),this.displayAllItems(t.triConfig),!0)}posAttr(){if(!this.shapes)throw Error("Null shape data!");return this.shapes.position}type(){return La.Mesh}fillData(e,t,i,n){this.shapes=n?new Dr(e,t,i,...n):new Dr(e,t,i)}copyData(e){const i=new Mo(e),n=this.shapes;return i.shapes=new Dr(n.position,n.normal,n.index),n.matrix.equals(new t)||(i.shapes.matrix=n.matrix),i}isSameGeom(e){return e.type()===La.Mesh&&this.shapes.position===e.shapes.position}hilight(e){this.displayAllItems(e.triConfig,!0)}unHilight(){this.displayAllItems(this.group.config.triConfig,!1)}hilightOwner(e,t){const i=this.items.find((e=>e.owner?.owner===t));i&&this.displayItem(e.triConfig,i)}unHilightOwner(e){const t=this.items.find((t=>t.owner?.owner===e));t&&this.displayItem(this.group.config.triConfig,t,!1)}}class bo extends xo{display(e,t){return!!this.shapes&&(e.add(this.shapes,t.clippingMethod),this.displayAllItems(t.pntConfig),!0)}posAttr(){if(!this.shapes)throw Error("Null shape data!");return this.shapes.position}type(){return La.Points}fillData(e,t){this.shapes=new Ar(e,t)}copyData(e){const i=new bo(e);return i.shapes=new Ar(this.shapes.position,this.shapes.index),this.shapes.matrix.equals(new t)||i.transform(this.shapes.matrix),i}isSameGeom(e){return e.type()===La.Points&&this.shapes.position===e.shapes.position}hilight(e){this.displayAllItems(e.pntConfig,!0)}unHilight(){this.displayAllItems(this.group.config.pntConfig,!1)}hilightOwner(e,t){const i=this.items.find((e=>e.owner?.owner===t));i&&this.displayItem(e.pntConfig,i,!0)}unHilightOwner(e){const t=this.items.find((t=>t.owner?.owner===e));t&&this.displayItem(this.group.config.pntConfig,t,!1)}}class Eo{selectMode;//! 对应的拾取模式 object;//! 所属的拾取对象 owner;//! owner对象 enable=!0;//! enable or not constructor(e,t,i){this.selectMode=e,this.owner=t,this.object=i}}function So(e){switch(e){case Ur.VERTEX:return Da.SM_BRepVertex;case Ur.EDGE:return Da.SM_BRepEdge;case Ur.FACE:return Da.SM_BRepFace;case Ur.WIRE:return Da.SM_BRepWire;case Ur.SHELL:return Da.SM_BRepShell;case Ur.SOLID:return Da.SM_BRepSolid;default:return-1}}!function(e){e[e.SM_None=0]="SM_None",e[e.SM_BRepVertex=1]="SM_BRepVertex",e[e.SM_BRepEdge=2]="SM_BRepEdge",e[e.SM_BRepFace=3]="SM_BRepFace",e[e.SM_BRepWire=4]="SM_BRepWire",e[e.SM_BRepShell=5]="SM_BRepShell",e[e.SM_BRepSolid=6]="SM_BRepSolid",e[e.SM_BRepCompound=7]="SM_BRepCompound",e[e.SM_MeshNode=8]="SM_MeshNode",e[e.SM_MeshEdge=9]="SM_MeshEdge",e[e.SM_MeshFace=10]="SM_MeshFace",e[e.SM_MeshElement=11]="SM_MeshElement"}(Da||(Da={})),function(e){e[e.ESM_Undefined=0]="ESM_Undefined",e[e.ESM_MeshSurfNodes=1]="ESM_MeshSurfNodes",e[e.ESM_MeshAllNodes=2]="ESM_MeshAllNodes",e[e.ESM_MeshSurfFaces=3]="ESM_MeshSurfFaces",e[e.ESM_MeshAllFaces=4]="ESM_MeshAllFaces",e[e.ESM_MeshCurveEdges=5]="ESM_MeshCurveEdges"}(za||(za={})),function(e){e[e.SET_Single=0]="SET_Single",e[e.SET_Group=1]="SET_Group"}(Ia||(Ia={}));class To extends Eo{subElements=[];//! 子对象 isSelected(e){for(const t of this.subElements)if(t.isSelected(e))return!0;return!1}getSelRender(e,t){for(const i of this.subElements)if(!i.getSelRender(e,t))return!1;return!0}type(){return Ia.SET_Group}getRelatedRenders(){const e=[];return this.subElements.forEach((t=>{e.push(...t.getRelatedRenders())})),e}hilight(e){return this.subElements.forEach((t=>{t.hilight(e)})),!0}unHiligth(){return this.subElements.forEach((e=>{e.unHiligth()})),!0}}class Co extends Eo{target;//! 目标显示对象 constructor(e,t,i){super(t,e.owner,i),this.target=e}isSelected(e){const t=e;if(t.shape!==this.target.element.shapes)return!1;const i=this.target.element.shapes===t.shape,n=t.index>=this.target.start&&t.index!!e.isGeomEle()&&e.isSameGeom(this.target.element)));i||(i=this.target.element.copyData(e));const n=new mo(t,Oa.OT_SelectOwner);return i.createItem(n,this.target.start,this.target.length),!0}type(){return Ia.SET_Single}getRelatedRenders(){return[this.target.element]}hilight(e){return this.target.element.hilightOwner(e,this.owner.owner),!0}unHiligth(){return this.target.element.unHilightOwner(this.owner.owner),!0}}!function(e){e[e.WireFrame=0]="WireFrame",e[e.Shaded=1]="Shaded",e[e.WireShaded=2]="WireShaded"}(Ba||(Ba={}));class _o{wrappedTriConfig;//! mesh config wrappedLineConfig;//! line config wrappedPntConfig;//! point config clippingMethod=Br.Seal;clippingColor=new g(65535);customCfgs=new Map;//! 自定义的对象显示配置 textCfg;line2DCfg;constructor(){this.wrappedTriConfig=new Ir({color:new g(16711680),style:lr.Regular,side:ge}),this.wrappedLineConfig=new vr({color:new g(65280),config:new Sr(1),style:lr.Regular}),this.wrappedPntConfig=new Or({color:new g(255),shape:_r.Ball,style:lr.Regular,size:1}),this.textCfg=new nr({color:new g(0,0,1),font:"Microsoft YaHei",size:20,alignment:Gs.BottomMiddle}),this.line2DCfg=new Qs({color:new g(0),width:2,arrow:{length:20,width:5}})}get lineConfig(){return this.wrappedLineConfig}get pntConfig(){return this.wrappedPntConfig}get triConfig(){return this.wrappedTriConfig}get textConfig(){return this.textCfg}}class Ro{eles=[];//! 组内的渲染元素 config;//! group的渲染设置 wrappedObject;//! group所属的object constructor(e=null){this.wrappedObject=e,this.config=new _o}get visible(){return 0!==this.eles.length&&this.eles[0].visible}set visible(e){this.eles.forEach((t=>{t.visible=e}))}transform(e){this.eles.forEach((t=>{t.transform(e)}))}getRenderItem(e){for(const t of this.eles)if(t.isGeomEle()){const i=t.getRenderItem(e);if(i)return i}}display(e){let t=!1;return this.eles.forEach((i=>{const n=i.display(e,this.config);n&&(t=n)})),t}remove(e,t=!1){let i=!0;return this.eles.forEach((t=>{t.remove(e)||(i=!1)})),t&&this.clearData(),i}removeElement(e,t,i=!1){return!!t.remove(e)&&(i&&this.clearElement(t),!0)}removeByOwner(e,t,i=!1){[...this.eles].forEach((n=>{n.removeByOwner(e,t,i),i&&n.isEmpty()&&this.clearElement(n)}))}clearData(){this.eles.splice(0,this.eles.length)}clearElement(e){const t=this.eles.indexOf(e);t>=0&&this.eles.splice(t,1)}hilight(e){this.eles.forEach((t=>{t.hilight(e)}))}unHilight(){this.eles.forEach((e=>{e.unHilight()}))}}!function(e){e[e.Redisplay=0]="Redisplay",e[e.ViewModeChanged=1]="ViewModeChanged",e[e.Update=2]="Update"}(Fa||(Fa={}));class Ao{updateEvent=new ht;wrappedGroup;//! 每个显示模式所对应的渲染对象 wrappedBox=new ea;//! 边界包围盒 wrappedVisible=!0;constructor(){this.wrappedGroup=new Ro(this)}get visible(){return this.wrappedVisible}set visible(e){this.wrappedVisible!==e&&(this.wrappedVisible=e,this.wrappedGroup.visible=e)}setFaceColor(e){this.wrappedGroup.config.triConfig.color=new g(e),this.setClippingColor(e)}setLineColor(e){this.wrappedGroup.config.lineConfig.color=new g(e)}setLineWidth(e){this.wrappedGroup.config.lineConfig.config.lineWidth=e}setPntColor(e){this.wrappedGroup.config.pntConfig.color=new g(e)}setPntSize(e){this.wrappedGroup.config.pntConfig.size=e}setPntShape(e){this.wrappedGroup.config.pntConfig.shape=e}setClippingColor(e){this.wrappedGroup.config.clippingColor=new g(e)}transform(e){this.wrappedGroup.transform(e)}get boundingBox(){return this.wrappedBox}updateBox(){this.wrappedBox=new ea,this.group.eles.forEach((e=>{if(e.isGeomEle()){const t=new ea;t.setFromBufferAttribute(e.posAttr()),this.boundingBox.union(t)}}))}setAllTransparent(e){this.wrappedGroup.config.triConfig.opacity=e,this.wrappedGroup.config.customCfgs.forEach((t=>{const i=t;i.opacity&&(i.opacity=e,e<.95&&(i.side=K))})),e<.95&&(this.wrappedGroup.config.triConfig.side=K)}setTransparent(e){this.wrappedGroup.config.triConfig.opacity=e,e<.95&&(this.wrappedGroup.config.triConfig.side=K)}setItemCustomCfg(e,t){this.wrappedGroup.config.customCfgs.set(e,t),e.element.displayItem(t,e)}unSetItemCustomCfg(e){let t=null;const i=e.element.type();i===La.Points?t=this.group.config.pntConfig:i===La.LineSegments?t=this.group.config.lineConfig:i===La.Mesh&&(t=this.group.config.triConfig),t&&(this.wrappedGroup.config.customCfgs.delete(e),e.element.displayItem(t,e))}unSetAllCustomCfg(){this.group.config.customCfgs.forEach(((e,t)=>{let i=null;const n=t.element.type();n===La.Points?i=this.group.config.pntConfig:n===La.LineSegments?i=this.group.config.lineConfig:n===La.Mesh&&(i=this.group.config.triConfig),i&&t.element.displayItem(i,t)})),this.group.config.customCfgs=new Map}get group(){return this.wrappedGroup}}class Po extends Ao{wrappedSelections;//! 每个显示模式所对应的拾取对象 wrappedActiveModes;//! 使能的拾取模式 constructor(){super(),this.wrappedSelections=new Map,this.wrappedActiveModes=[]}getSelects(e){if(!this.wrappedSelections.has(e)&&!this.computeSelects(e))throw Error("Unsupport view mode!");return this.wrappedSelections.get(e)||new Array}get activeModes(){return this.wrappedActiveModes}set activeModes(e){this.wrappedActiveModes=e}}class Oo extends Po{isBind=!1;//! 是否绑定到View,内部使用 wrappedViewMode=null;display(e,t){if(this.wrappedGroup.clearData(),!this.computeRenders(t))return!1;this.updateBox();const i=this.wrappedGroup.display(e);return!1===this.visible&&(this.wrappedVisible=!0,this.visible=!1),i}remove(e){return this.wrappedGroup.remove(e)}onViewModeChanged(e,t){this.wrappedGroup.remove(e,!0),this.display(e,t)}get viewMode(){return this.wrappedViewMode}set viewMode(e){this.wrappedViewMode!==e&&this.updateEvent.trigger({type:Fa.ViewModeChanged,arg:{object:this,mode:e}}),this.wrappedViewMode=e}clearData(){this.group.clearData(),this.wrappedSelections.clear()}}!function(e){e[e.Invalid=0]="Invalid",e[e.BRepType=1]="BRepType",e[e.CellMeshType=2]="CellMeshType",e[e.NodeMeshType=3]="NodeMeshType",e[e.VectorGraphType=4]="VectorGraphType",e[e.StreamLineType=5]="StreamLineType",e[e.TriangulationType=6]="TriangulationType",e[e.PlaneType=7]="PlaneType",e[e.PolyGeomType=8]="PolyGeomType",e[e.DatumPointType=9]="DatumPointType",e[e.DatumAxisType=10]="DatumAxisType",e[e.LengthDim3DType=11]="LengthDim3DType",e[e.AnnoPlaneType=12]="AnnoPlaneType",e[e.AnnoLabelType=13]="AnnoLabelType",e[e.CustomType=1e3]="CustomType"}(Na||(Na={}));class Lo extends Oo{wrappedBody;//! BRep对象 wrappedRenders=new Map;//! 显示对象枚举 constructor(e){super(),this.body=e,this.setFaceColor(12632256),this.setLineColor(0),this.setPntColor(0),this.wrappedGroup.config.lineConfig.polygonOffset=-1,this.wrappedGroup.config.pntConfig.polygonOffset=-2,this.wrappedGroup.config.triConfig.side=K}type(){return Na.BRepType}computeSelects(e){if(this.wrappedSelections.has(e))return!0;const t=[],i=e=>e===Da.SM_BRepEdge?this.wrappedRenders.get("edges"):e===Da.SM_BRepFace?this.wrappedRenders.get("faces"):e===Da.SM_BRepVertex?this.wrappedRenders.get("vertices"):void 0,n=(e,t,n)=>{e.forEach((e=>{const s=i(t)?.getRenderItem(e);if(!s)throw Error("Can't find render item of brep object!");const r=new Co(s,t,this);n.push(r)}))},s=(i,s)=>{const r=[];e!==Ba.Shaded&&e!==Ba.WireShaded||n(i.faces,Da.SM_BRepFace,r),e!==Ba.WireFrame&&e!==Ba.WireShaded||(n(i.edges,Da.SM_BRepEdge,r),n(i.vertices,Da.SM_BRepVertex,r)),s.push(...r);const a=new mo(i,Oa.OT_BRepOwner),o=new To(Da.SM_BRepShell,a,this);return o.subElements.push(...r),t.push(o),s.push(o),o},r=(e,t)=>{const i=[];e.shells.forEach((e=>{const n=s(e,t);i.push(n)}));const n=new mo(e,Oa.OT_BRepOwner),r=new To(Da.SM_BRepSolid,n,this);return r.subElements.push(...i),t.push(r),r},a=(e,i)=>{const s=[];n(e.edges,Da.SM_BRepEdge,s),n(e.vertices,Da.SM_BRepVertex,s),i.push(...s);const r=new mo(e,Oa.OT_BRepOwner),a=new To(Da.SM_BRepWire,r,this);return a.subElements.push(...s),t.push(a),a},o=e=>{const i=[];e.solids.forEach((e=>{i.push(r(e,t))})),e.shells.forEach((e=>{i.push(s(e,t))})),e.wires.forEach((e=>{i.push(a(e,t))}));const o=[];n(e.acorns,Da.SM_BRepVertex,o),i.push(...o),t.push(...o);const h=new mo(e,Oa.OT_Custom),d=new To(Da.SM_BRepWire,h,this);d.subElements.push(...i),t.push(d)};switch(this.body.bodyType()){case Gr.BT_SolidBody:p=this.body.toSolid(),r(p.solid,t);break;case Gr.BT_ShellBody:d=this.body.toShell(),s(d.shell,t);break;case Gr.BT_WireBody:h=this.body.toWire(),a(h.wire,t);break;case Gr.BT_AcornBody:(e=>{const i=[e.point];n(i,Da.SM_BRepVertex,t)})(this.body.toAcorn());break;case Gr.BT_CompoundBody:o(this.body.toCompound());break;default:throw Error("Not supported body type!")}var h,d,p;return this.wrappedSelections.set(e,t),!0}computeRenders(e){const t=this.wrappedGroup,i=(e,t)=>{if(0===e.length)return;if(this.wrappedRenders.has("faces"))return void t.eles.push(this.wrappedRenders.get("faces"));const i=new Mo(t);let n=0;const s=[],r=[],a=[];e.forEach((e=>{const t=e.triangulation;a.push(...la.toArray(t.triangleList,s.length/3)),s.push(...sa.toArray(t.nodeList)),r.push(...sa.toArray(t.normalList));const{length:o}=t.triangleList,h=new mo(e,Oa.OT_BRepOwner);i.createItem(h,n,o),n+=o})),i.fillData(s,r,a),this.wrappedRenders.set("faces",i)},n=(e,t)=>{if(0===e.length)return;if(this.wrappedRenders.has("edges"))return void t.eles.push(this.wrappedRenders.get("edges"));const i=new yo(t);let n=0;const s=[],r=[];e.forEach((e=>{const t=e.polygon,a=aa.createIndex(t.nodeList.length,s.length/3);s.push(...sa.toArray(t.nodeList)),r.push(...a);const o=a.length/2,h=new mo(e,Oa.OT_BRepOwner);i.createItem(h,n,o),n+=o})),i.fillData(s,r),this.wrappedRenders.set("edges",i)},s=(e,t)=>{if(0===e.length)return;if(this.wrappedRenders.has("vertices"))return void t.eles.push(this.wrappedRenders.get("vertices"));const i=new bo(t),n=[],s=[];e.forEach((e=>{n.push(e.point.x(),e.point.y(),e.point.z());const{length:t}=s;s.push(t);const r=new mo(e,Oa.OT_BRepOwner);i.createItem(r,t,1)})),i.fillData(n,s),this.wrappedRenders.set("vertices",i)};switch(this.body.bodyType()){case Gr.BT_SolidBody:((e,t,r)=>{const a=[],o=[],h=[];e.solid.shells.forEach((e=>{a.push(...e.faces),o.push(...e.edges),h.push(...e.vertices)})),t!==Ba.Shaded&&t!==Ba.WireShaded||i(a,r),t!==Ba.WireFrame&&t!==Ba.WireShaded||(n(o,r),s(h,r))})(this.body.toSolid(),e,t);break;case Gr.BT_ShellBody:r=this.body.toShell(),o=t,(a=e)!==Ba.Shaded&&a!==Ba.WireShaded||i(r.shell.faces,o),a!==Ba.WireFrame&&a!==Ba.WireShaded||(n(r.shell.edges,o),s(r.shell.vertices,o));break;case Gr.BT_WireBody:((e,t,i)=>{n(e.wire.edges,i),s(e.wire.vertices,i)})(this.body.toWire(),0,t);break;case Gr.BT_AcornBody:((e,t,i)=>{const n=[e.point];s(n,i)})(this.body.toAcorn(),0,t);break;case Gr.BT_CompoundBody:((e,t,r)=>{const a=[...e.shells];e.solids.forEach((e=>{a.push(...e.shells)}));const o=[...e.wires],h=[...e.acorns],d=[],p=[];a.forEach((e=>{t!==Ba.Shaded&&t!==Ba.WireShaded||d.push(...e.faces),t!==Ba.WireFrame&&t!==Ba.WireShaded||(p.push(...e.edges),h.push(...e.vertices))})),o.forEach((e=>{p.push(...e.edges),h.push(...e.vertices)})),s(h,r),n(p,r),i(d,r)})(this.body.toCompound(),e,t);break;default:throw Error("Not supported body type!")}var r,a,o;return!0}get body(){return this.wrappedBody}set body(e){this.wrappedBody=e}setBRepColor(e,t){const i=e.getAllFaces();if(i.length>0)return this.wrappedGroup.getRenderItem(i[0])?.element.shapes?.startBatchConfigUpdate(),i.forEach((e=>{const i=this.wrappedGroup.getRenderItem(e);if(i){const e=this.group.config.customCfgs.get(i);if(this.group.config.customCfgs.has(i)&&e){const n=new Ir(e);n.color=new g(t),this.setItemCustomCfg(i,n)}else{const e=new Ir(this.wrappedGroup.config.triConfig);e.color=new g(t),this.setItemCustomCfg(i,e)}}})),this.wrappedGroup.getRenderItem(i[0])?.element.shapes?.finishBatchConfigUpdate(),!0;const n=e.getAllEdges();if(n.length>0)return this.wrappedGroup.getRenderItem(n[0])?.element.shapes?.startBatchConfigUpdate(),n.forEach((e=>{const i=this.wrappedGroup.getRenderItem(e);if(i){const e=this.group.config.customCfgs.get(i);if(e){const n=new vr(e);n.color=new g(t),this.setItemCustomCfg(i,n)}else{const e=new vr(this.wrappedGroup.config.lineConfig);e.color=new g(t),this.setItemCustomCfg(i,e)}}})),this.wrappedGroup.getRenderItem(n[0])?.element.shapes?.finishBatchConfigUpdate(),!0;const s=e.getAllVertices();return s.length>0&&(this.wrappedGroup.getRenderItem(s[0])?.element.shapes?.startBatchConfigUpdate(),s.forEach((e=>{const i=this.wrappedGroup.getRenderItem(e);if(i){const e=this.group.config.customCfgs.get(i);if(e){const n=new Or(e);n.color=new g(t),this.setItemCustomCfg(i,n)}else{const e=new Or(this.wrappedGroup.config.pntConfig);e.color=new g(t),this.setItemCustomCfg(i,e)}}})),this.wrappedGroup.getRenderItem(s[0])?.element.shapes?.finishBatchConfigUpdate(),!0)}setBRepOpacity(e,t){const i=e.getAllFaces();return i.length>0&&(this.wrappedGroup.getRenderItem(i[0])?.element.shapes?.startBatchConfigUpdate(),i.forEach((e=>{const i=this.wrappedGroup.getRenderItem(e);if(i){const e=this.group.config.customCfgs.get(i);if(this.group.config.customCfgs.has(i)&&e){const n=new Ir(e);n.opacity=t,this.setItemCustomCfg(i,n)}else{const e=new Ir(this.wrappedGroup.config.triConfig);e.opacity=t,this.setItemCustomCfg(i,e)}}})),this.wrappedGroup.getRenderItem(i[0])?.element.shapes?.finishBatchConfigUpdate(),!0)}unSetBRepColor(e){const t=e.getAllFaces();if(t.length>0)return this.wrappedGroup.getRenderItem(t[0])?.element.shapes?.startBatchConfigUpdate(),t.forEach((e=>{const t=this.wrappedGroup.getRenderItem(e);if(t){this.group.config.customCfgs.get(t)&&this.unSetItemCustomCfg(t)}})),this.wrappedGroup.getRenderItem(t[0])?.element.shapes?.finishBatchConfigUpdate(),!0;const i=e.getAllEdges();if(i.length>0)return this.wrappedGroup.getRenderItem(i[0])?.element.shapes?.startBatchConfigUpdate(),i.forEach((e=>{const t=this.wrappedGroup.getRenderItem(e);if(t){this.group.config.customCfgs.get(t)&&this.unSetItemCustomCfg(t)}})),this.wrappedGroup.getRenderItem(i[0])?.element.shapes?.finishBatchConfigUpdate(),!0;const n=e.getAllVertices();return n.length>0&&(this.wrappedGroup.getRenderItem(n[0])?.element.shapes?.startBatchConfigUpdate(),n.forEach((e=>{const t=this.wrappedGroup.getRenderItem(e);if(t){this.group.config.customCfgs.get(t)&&this.unSetItemCustomCfg(t)}})),this.wrappedGroup.getRenderItem(n[0])?.element.shapes?.finishBatchConfigUpdate(),!0)}clearData(){super.clearData(),this.wrappedRenders.clear()}}!function(e){e[e.Colors=0]="Colors",e[e.Range=1]="Range",e[e.Type=2]="Type"}(Ua||(Ua={}));class Do extends ss{updateEvent=new ht;wrappedColors=[];wrappedRange=[0,1];constructor(){super(),this.setColorMap("rainbow"),this.type=ns.Gradient,this.titleFontSize=16,this.labelFontSize=14}updateLegend(){const e=new Gt(this.wrappedColors);e.updateRange(this.wrappedRange[0],this.wrappedRange[1]),this.lut=e.items.map((e=>({color:`#${e.color.getHexString()}`,value:e.anchorValue})))}setColorMap(e,t=void 0){if("string"==typeof e){const i=new Gt(new Ne(e,t&&t>1?t-1:void 0));this.wrappedColors=[],i.items.forEach((e=>{this.wrappedColors.push(e.color)}))}else this.wrappedColors=e;this.updateLegend(),this.updateEvent.trigger({type:Ua.Colors,arg:this})}get colors(){return this.wrappedColors}get range(){return{min:this.wrappedRange[0],max:this.wrappedRange[1]}}set range(e){this.wrappedRange[0]=e.min,this.wrappedRange[1]=e.max>e.min?e.max:e.min+.1,this.updateLegend(),this.updateEvent.trigger({type:Ua.Range,arg:this})}get type(){return super.type}set type(e){super.type=e,this.updateEvent.trigger({type:Ua.Type,arg:this})}}class zo extends Oo{wrappedLegend=null;//! 绑定的legend wrappedMesh;//! 网格对象 wrappedMeshBak=null;//! 备份网格对象(当使用2d->3d功能时此项用于备份原网格对象) wrappedRenders=new Map;//! 显示对象数组 wrappedCurProp="";//! 当前使能属性 wrappedDeformFactor=1;//! 变形因子 wrappedDeformOn=!1;//! 变形开始与否 wrappedDeformAttr="";//! 变形属性名 wrappedSolidColor=new g(12632256);wrappedLineColor=new g(0);wrappedNodeItemMap=new Map;//! node和item映射 wrappedFaceItemMap=new Map;//! face和item映射 wrappedEdgeItemMap=new Map;//! edge和item映射 wrappedShowNode=!1;wrappedLineContour=!1;constructor(e){super(),this.wrappedMesh=e,this.setLineColor(0),this.setPntColor(0),this.wrappedGroup.config.lineConfig.polygonOffset=-1,this.wrappedGroup.config.pntConfig.polygonOffset=-2,this.wrappedGroup.config.pntConfig.size=5,this.wrappedGroup.config.triConfig.side=K,this.updateProperty()}unbindLegend=e=>{this.legend&&this.legend.updateEvent.remove(this.onLegendUpdateCB),e===this.legend&&(this.wrappedLegend=null)};useLegend=!0;onLegendUpdateCB=e=>{e?.type!==Ua.Range&&e?.type!==Ua.Colors&&e?.type!==Ua.Type||this.updateProperty()};bindLegend=e=>{this.wrappedLegend=e,this.legend&&(this.legend.updateEvent.add(this.onLegendUpdateCB),this.updateProperty())};setNodesColor(e,t){const i=[];if(e.forEach((e=>{const t=this.mesh.nodes.get(e);if(t){const e=this.wrappedNodeItemMap.get(t);e&&i.push(e)}})),i.length>0){const e=new Or(this.group.config.pntConfig);e.color=new Jr(t),i[0].element.shapes?.startBatchConfigUpdate(),i.forEach((t=>{this.setItemCustomCfg(t,e)})),i[0].element.shapes?.finishBatchConfigUpdate()}}type(){return Na.NodeMeshType}computeSelects(e){if(this.wrappedSelections.has(e))return!0;const t=[],i=new Set,n=new Set,s=new Set,r=r=>{const a=new mo(r,Oa.OT_MeshElement),o=new To(Da.SM_MeshElement,a,this);t.push(o),e!==Ba.WireFrame&&e!==Ba.WireShaded||(r.nodes.forEach((e=>{if(i.has(e))return;i.add(e);const n=this.wrappedMesh.nodes.get(e);if(void 0===n)return;const s=this.wrappedNodeItemMap.get(n);if(void 0===s)return;const r=new Co(s,Da.SM_MeshNode,this);t.push(r),o.subElements.push(r)})),r.edges.forEach((e=>{const i=(e=>e.node1>e.node2?`${e.node2.toFixed(0)}-${e.node1.toFixed(0)}`:`${e.node1.toFixed(0)}-${e.node2.toFixed(0)}`)(e);if(n.has(i))return;n.add(i);const s=this.wrappedEdgeItemMap.get(e);if(!s)return;const r=new Co(s,Da.SM_MeshEdge,this);t.push(r),o.subElements.push(r)}))),e!==Ba.Shaded&&e!==Ba.WireShaded||r.faces.forEach((e=>{const i=(e=>{const t=e.nodes.map((e=>e));t.sort(((e,t)=>e-t));let i="";return t.forEach((e=>{i+=`-${e.toFixed(0)}`})),i})(e);if(s.has(i))return;s.add(i);const n=this.wrappedFaceItemMap.get(e);if(!n)return;const r=new Co(n,Da.SM_MeshFace,this);t.push(r),o.subElements.push(r)})),t.push(o)};return this.wrappedMesh.elements.forEach((e=>{r(e)})),this.wrappedSelections.set(e,t),!0}computeRenders(e){const t=new Map;//! 节点id和pos属性index映射,key为节点id,value为属性index let i=null;const s=this.mesh.getProperty(this.wrappedDeformAttr),r=e=>{const t=[0,0,0];if(this.wrappedDeformOn&&s){const i=s.data.get(e);i&&(t[0]=i[0]*this.wrappedDeformFactor,s.size>1&&(t[1]=i[1]*this.wrappedDeformFactor),s.size>2&&(t[2]=i[2]*this.wrappedDeformFactor))}return t},a=()=>{if(i)return;const e=[];let s=0;this.wrappedMesh.nodes.forEach((i=>{const n=r(i.id);e.push(i.coord[0]+n[0],i.coord[1]+n[1],i.coord[2]+n[2]),t.set(i.id,s),s+=1})),i=new n(e,3)},o=()=>{if(this.wrappedRenders.has("nodes"))return void this.wrappedGroup.eles.push(this.wrappedRenders.get("nodes"));a();const e=new bo(this.wrappedGroup),t=[];let n=0;this.wrappedMesh.nodes.forEach((i=>{t.push(n);const s=new mo(i,Oa.OT_MeshNode),r=e.createItem(s,n,1);this.wrappedNodeItemMap.set(i,r),n+=1})),e.fillData(i,t),this.wrappedRenders.set("nodes",e)},h=()=>{if(this.wrappedRenders.has("edges"))return void this.wrappedGroup.eles.push(this.wrappedRenders.get("edges"));a();const e=new yo(this.wrappedGroup),n=[];let s=0;this.wrappedMesh.elements.forEach((i=>{i.edges.forEach((i=>{const r=t.get(i.node1),a=t.get(i.node2);if(void 0!==r&&void 0!==a){n.push(r,a);const t=new mo(i,Oa.OT_MeshEdge),o=e.createItem(t,s,1);this.wrappedEdgeItemMap.set(i,o),s+=1}}))})),e.fillData(i,n),this.wrappedRenders.set("edges",e)},d=()=>{if(this.wrappedRenders.has("faces"))return void this.wrappedGroup.eles.push(this.wrappedRenders.get("faces"));const e=[];if(this.wrappedMesh.elements.forEach((t=>{t.faces.forEach((t=>{e.push(t)}))})),0===e.length)return;const t=new Mo(this.wrappedGroup),i=[],n=[];let s=0;e.forEach((e=>{const a=[];for(const t of e.nodes){const e=this.wrappedMesh.nodes.get(t);if(void 0===e)return;a.push(e)}const o=[];a.forEach((e=>{o.push(i.length/3);const t=r(e.id);i.push(e.coord[0]+t[0],e.coord[1]+t[1],e.coord[2]+t[2])})),e.triangles.forEach((e=>{n.push(o[e.node1],o[e.node2],o[e.node3])}));const h=new mo(e,Oa.OT_MeshFace),d=t.createItem(h,s,e.triangles.length);this.wrappedFaceItemMap.set(e,d),s+=e.triangles.length})),t.fillData(i,[],n),this.wrappedRenders.set("faces",t)};if(e!==Ba.Shaded&&e!==Ba.WireShaded||d(),e!==Ba.WireFrame&&e!==Ba.WireShaded||(h(),o(),this.updateNodeVisible()),""!==this.wrappedCurProp){const e=this.wrappedCurProp.slice(0,this.wrappedCurProp.lastIndexOf("-")),t=Number(this.wrappedCurProp.slice(this.wrappedCurProp.lastIndexOf("-")+1));this.attachProperty(e,t)}return!0}attachProperty(e,t){const i=this.wrappedMesh.getProperty(e);if(void 0===i)return!1;if(t>0&&t>i.size)return!1;const s=new Map;if(i.forNode)i.data.forEach(((e,i)=>{s.set(i,e[t])}));else{const e=new Map;i.data.forEach(((i,n)=>{this.wrappedMesh.elements.get(n)?.nodes.forEach((n=>{e.has(n)||e.set(n,[]),e.get(n)?.push(i[t])}))})),e.forEach(((e,t)=>{let i=0;e.forEach((e=>{i+=e}));const n=i/e.length;s.set(t,n)}))}const r=[];this.wrappedMesh.elements.forEach((e=>{e.faces.forEach((e=>{const t=[];for(const i of e.nodes){if(void 0===this.wrappedMesh.nodes.get(i))return;const e=s.get(i);if(void 0===e)throw Error(`Node prop is not exist! id: ${i}`);t.push(e)}r.push(...t)}))})),r.forEach((e=>{}));const a=[];this.wrappedMesh.nodes.forEach((e=>{const t=s.get(e.id);if(void 0===t)throw Error(`Node prop is not exist! id: ${e}`);a.push(t)}));const o=new n(r,1),h=new n(a,1),d=`${e}-${t}`;if(this.wrappedRenders.has("faces")){const e=this.wrappedRenders.get("faces").shapes;e&&(e.customAttributes.clear(),e.customAttributes.set(d,o))}if(this.wrappedRenders.has("edges")){const e=this.wrappedRenders.get("edges").shapes;e&&(e.customAttributes.clear(),e.customAttributes.set(d,h))}return!0}activeProperty(e,t=0){const i=`${e}-${t}`;if(this.wrappedCurProp===i)return!0;if(""===e)this.wrappedCurProp="";else if(this.wrappedCurProp=i,!this.attachProperty(e,t))return!1;return this.updateProperty(),!0}setFaceColor(e){this.wrappedSolidColor=new g(e),this.setClippingColor(e),this.updateProperty()}setLineColor(e){this.wrappedLineColor=new g(e),this.updateProperty()}updateProperty(){if(""===this.wrappedCurProp)this.group.config.triConfig.color=new hr(Vt.Fragment_Color_Map,[this.wrappedSolidColor],this.wrappedCurProp,dr.Liner,0,0),this.group.config.lineConfig.color=new hr(Vt.Fragment_Color_Map,[this.wrappedLineColor],this.wrappedCurProp,dr.Liner,0,0);else{const e=this.wrappedCurProp.slice(0,this.wrappedCurProp.lastIndexOf("-")),t=Number(this.wrappedCurProp.slice(this.wrappedCurProp.lastIndexOf("-")+1)),i=this.mesh.getProperty(e);if(void 0===i)return;const n=this.legend?.range;this.group.config.triConfig.color=new hr(Vt.Fragment_Color_Map,this.legend?this.legend.colors:[new g(1,0,0),new g(0,1,0),new g(0,0,1)],this.wrappedCurProp,this.legend?.type===ns.Nearest?dr.Nearest:dr.Liner,n?n.min:i.range.min[t],n?n.max:i.range.max[t]),this.group.config.triConfig.color.attributeName=this.wrappedCurProp;let s=this.legend?this.legend.colors:[new g(1,0,0),new g(0,1,0),new g(0,0,1)],r=this.wrappedCurProp;this.wrappedLineContour||(s=[this.wrappedLineColor],r=""),this.group.config.lineConfig.color=new hr(Vt.Fragment_Color_Map,s,r,this.legend?.type===ns.Nearest?dr.Nearest:dr.Liner,n?n.min:i.range.min[t],n?n.max:i.range.max[t]),this.wrappedLineContour&&(this.group.config.lineConfig.color.attributeName=r)}}get legend(){return this.wrappedLegend}updateNodeVisible(){super.visible&&this.wrappedRenders.has("nodes")&&(this.wrappedRenders.get("nodes").visible=this.showNode)}get showNode(){return this.wrappedShowNode}set showNode(e){this.showNode!==e&&(this.wrappedShowNode=e,this.updateNodeVisible())}get showLineContour(){return this.wrappedLineContour}set showLineContour(e){this.wrappedLineContour!==e&&(this.wrappedLineContour=e,this.updateProperty())}get deformOn(){return this.wrappedDeformOn}set deformOn(e){this.wrappedDeformOn!==e&&(this.wrappedDeformOn=e,this.updateEvent.trigger({type:Fa.Redisplay,arg:this}))}get deformAttr(){return this.wrappedDeformAttr}set deformAttr(e){this.wrappedDeformAttr=e}get deformFactor(){return this.wrappedDeformFactor}set deformFactor(e){e!==this.wrappedDeformFactor&&(this.wrappedDeformFactor=e,this.deformOn&&this.updateEvent.trigger({type:Fa.Redisplay,arg:this}))}get mesh(){return this.wrappedMesh}set mesh(e){this.wrappedMesh=e,this.updateEvent.trigger({type:Fa.Redisplay,arg:this})}get visible(){return super.visible}set visible(e){this.wrappedVisible!==e&&(this.wrappedVisible=e,this.group.eles.forEach((t=>{t===this.wrappedRenders.get("nodes")?t.visible=e?this.showNode:e:t.visible=e})))}extrudeMesh(e,t){const i=this.mesh.to3DMeshByExtrude(e,t);null!==i&&(null===this.wrappedMeshBak&&(this.wrappedMeshBak=this.mesh),this.mesh=i)}revolveMesh(e,t,i){const n=this.mesh.to3DMeshByRevolve(e,t,i);null!==n&&(null===this.wrappedMeshBak&&(this.wrappedMeshBak=this.mesh),this.mesh=n)}to2dMesh(){const e=this.wrappedMeshBak;this.wrappedMeshBak=null,e&&(this.mesh=e)}clearData(){super.clearData(),this.wrappedRenders.clear(),this.wrappedEdgeItemMap.clear(),this.wrappedFaceItemMap.clear(),this.wrappedNodeItemMap.clear()}}function Io(e,t,i){if(e.owner.type===Oa.OT_MeshNode){const n=e.owner.owner,s=e.object,r=s.mesh.getNodesFromFace(n,i),a=new Set;r.forEach((e=>a.add(e)));const o=s.getSelects(s.viewMode??t),h=[];return o.forEach((e=>{e.owner.type===Oa.OT_MeshNode&&a.has(e.owner.owner)&&h.push(e)})),h}return[]}function Bo(e,t){if(e.owner.type===Oa.OT_MeshNode){const i=e.object,n=i.getSelects(i.viewMode??t),s=[];return n.forEach((e=>{e.owner.type===Oa.OT_MeshNode&&s.push(e)})),s}return[]}function Fo(e,t,i){if(e.owner.type===Oa.OT_MeshFace){const n=e.owner.owner,s=e.object,r=s.mesh.getMeshFaces(n,i),a=new Set;r.forEach((e=>a.add(e)));const o=s.getSelects(s.viewMode??t),h=[];return o.forEach((e=>{e.owner.type===Oa.OT_MeshFace&&a.has(e.owner.owner)&&h.push(e)})),h}return[]}function No(e,t){if(e.owner.type===Oa.OT_MeshFace){const i=e.object,n=i.getSelects(i.viewMode??t),s=[];return n.forEach((e=>{e.owner.type===Oa.OT_MeshFace&&s.push(e)})),s}return[]}function Uo(e,t,i){if(e.owner.type===Oa.OT_MeshEdge){const n=e.owner.owner,s=e.object,r=s.mesh.getMeshEdgesByFeat(i,n),a=new Set;r.forEach((e=>a.add(e)));const o=s.getSelects(s.viewMode??t),h=[];return o.forEach((e=>{e.owner.type===Oa.OT_MeshEdge&&a.has(e.owner.owner)&&h.push(e)})),h}return[]}class Go{filters=[];//! 拾取过滤器 wrappedSelInfos=[];//! 拾取信息数组 wrappedEngine=null;//! 底层显示引擎 wrappedShapeSelMap=new Map;//! shape和拾取元素的映射 wrappedHitInfos=new Map;//! 记录hit信息 loadSelectObj(e,t){if(!this.engine)return!1;return e.getSelects(t).forEach((e=>{if(!e.enable)return;e.getRelatedRenders().forEach((t=>{if(!t.isGeomEle())return;const i=t.shapes;this.wrappedShapeSelMap.has(i)||this.wrappedShapeSelMap.set(i,new Set),this.wrappedShapeSelMap.get(i)?.add(e)}))})),this.engine.selectableShapes=Array.from(this.wrappedShapeSelMap.keys()),!0}removeSelectObj(e,t){return!!this.engine&&(e.group.eles.forEach((e=>{if(e.isGeomEle()){const t=e.shapes;if(!this.wrappedShapeSelMap.get(t))return;this.wrappedShapeSelMap.delete(t)}})),this.engine.selectableShapes=Array.from(this.wrappedShapeSelMap.keys()),!0)}select(e){return!!this.engine&&(this.wrappedSelInfos=e,!0)}boxSelect(e,t){return!0}getSelectEles(){const e=[];return this.wrappedHitInfos.clear(),this.infos.forEach((t=>{const i=t;i.shape&&this.wrappedShapeSelMap.get(i.shape)?.forEach((i=>{if(!i.enable)return;let n;this.filters.forEach((e=>{e.func(i)?void 0===n&&(n=!0):e.force&&(n=!1)})),n&&i.isSelected(t)&&(e.push(i),this.wrappedHitInfos.set(i,t))}))})),e}getHitInfo(e){return this.wrappedHitInfos.get(e)}get selTol(){return this.engine?this.engine.selectTol:1}set selTol(e){this.engine&&(this.engine.selectTol=e)}get infos(){return this.wrappedSelInfos}get engine(){return this.wrappedEngine}set engine(e){this.wrappedEngine=e}}class Ho{legend=new Do;legendPanel=new rs;constructor(){this.legendPanel.addLegend(this.legend)}bindObject(e){e.useLegend&&e.bindLegend(this.legend)}unbindObject(e){e.useLegend&&e.unbindLegend(this.legend)}}class ko extends wo{owner=null;isAnnotation(){return!0}}class jo extends ko{wrappedText=null;constructor(e,t,i=null){super(t),this.createText(e,i||t.config.textCfg)}get text(){return this.wrappedText?this.wrappedText.text:""}set text(e){this.wrappedText&&(this.wrappedText.text=e)}createText(e,t){"3D"===t.type?this.wrappedText=new sr(t,e,new $r(1,1,1),new $r(1,1,0),new $r(0,1,1)):"2D"===t.type&&(this.wrappedText=new Js(t,e,new $r,0))}get anchorPnt(){return this.wrappedText?.anchorPoint}set anchorPnt(e){this.wrappedText&&(this.wrappedText.anchorPoint=e)}get direction(){if("2D"===this.wrappedText?.type)return this.wrappedText.direction;if("3D"===this.wrappedText?.type)return this.wrappedText.textDirection;throw Error("Unsupported text type!")}set direction(e){if("2D"===this.wrappedText?.type)this.wrappedText.direction=e;else{if("3D"!==this.wrappedText?.type)throw Error("Unsupported text type!");if("number"==typeof e)throw Error("Direction must be an vector for 3D text!");this.wrappedText.textDirection=e}}get facing(){return"3D"===this.wrappedText?.type?this.wrappedText.facingDirection:new $r}set facing(e){"3D"===this.wrappedText?.type&&(this.wrappedText.facingDirection=e)}get visible(){return!0}set visible(e){console.log(e)}transform(e){if(this.wrappedText){const t=this.wrappedText.anchorPoint.applyMatrix4(e);this.wrappedText.anchorPoint=t}}type(){return La.Text}display(e,t){return!!this.wrappedText&&(this.wrappedText.config=t.textCfg,e.addText(this.wrappedText),!0)}remove(e){return this.wrappedText&&e.removeText(this.wrappedText),!0}removeByOwner(e,t,i){return this.owner===t&&(this.remove(e),i&&(this.wrappedText=null),!0)}isEmpty(){return null===this.wrappedText}copyData(e){return new jo(this.text,e)}hilight(e){this.wrappedText&&(this.wrappedText.config.color=e.textCfg.color,this.wrappedText.config.size=e.textCfg.size)}}!function(e){e[e.AddSelect=0]="AddSelect",e[e.DelSelect=1]="DelSelect"}(Ga||(Ga={})),function(e){e[e.Top=0]="Top",e[e.Bottom=1]="Bottom",e[e.Front=2]="Front",e[e.Back=3]="Back",e[e.Left=4]="Left",e[e.Right=5]="Right",e[e.TopFrontLeft=6]="TopFrontLeft"}(Ha||(Ha={})),function(e){e[e.Dynamic=0]="Dynamic",e[e.XAxis=1]="XAxis",e[e.YAxis=2]="YAxis",e[e.ZAxis=3]="ZAxis",e[e.Custom=4]="Custom"}(ka||(ka={})),function(e){e[e.Normal=0]="Normal",e[e.CreateLine=1]="CreateLine"}(ja||(ja={})),function(e){e[e.SelectStart=0]="SelectStart",e[e.SelectEnd=1]="SelectEnd"}(Va||(Va={}));class Vo{selectMode=Da.SM_BRepFace;//! 拾取模式 selectEvent=new ht;interEvent=new ht;legendMgr=new Ho;extendSelMode=za.ESM_Undefined;extendSelParam=[];wrappedEngine=void 0;//! render engine wrappedObjects=[];//! view objects wrappedViewMode=Ba.WireShaded;//! 显示模式 wrappedSelManager=new Go;//! 拾取管理器 wrappedSelectGroup;//! 拾取显示节点 wrappedDynSelGroup;//! 高亮显示节点 wrappedDetectedEle=null;//! 检测到的拾取对象 wrappedSelectedEles=[];//! 拾取到的拾取对象 wrappedEnableClipping=!1;wrappedEnableDynSel=!1;wrappedInterMode=ja.Normal;wrappedCLPS=null;//! 两点连线首点 wrappedCLPE=null;//! 两点连线末点 wrappedCLRender=null;//! 两点连线显示数据 get dynSelCfg(){return this.wrappedDynSelGroup.config}get selConfig(){return this.wrappedSelectGroup.config}constructor(){this.wrappedSelectGroup=new Ro,this.wrappedSelectGroup.config.lineConfig.color=new g(16776960),this.wrappedSelectGroup.config.pntConfig.color=new g(16776960),this.wrappedSelectGroup.config.pntConfig.size=10,this.wrappedSelectGroup.config.lineConfig.config.lineWidth=6,this.wrappedSelectGroup.config.triConfig.color=new g(16776960),this.wrappedSelectGroup.config.triConfig.side=K,this.wrappedSelectGroup.config.clippingMethod=Br.NoSeal,this.wrappedSelectGroup.config.triConfig.polygonOffset=-1,this.wrappedSelectGroup.config.lineConfig.polygonOffset=-2,this.wrappedSelectGroup.config.pntConfig.polygonOffset=-3,this.wrappedDynSelGroup=new Ro,this.wrappedDynSelGroup.config.lineConfig.color=new g(65535),this.wrappedDynSelGroup.config.pntConfig.color=new g(65535),this.wrappedDynSelGroup.config.pntConfig.size=10,this.wrappedDynSelGroup.config.triConfig.color=new g(65535),this.wrappedDynSelGroup.config.triConfig.side=K,this.wrappedDynSelGroup.config.clippingMethod=Br.NoSeal,this.wrappedDynSelGroup.config.triConfig.polygonOffset=-2,this.wrappedDynSelGroup.config.lineConfig.polygonOffset=-3,this.wrappedDynSelGroup.config.pntConfig.polygonOffset=-4,this.wrappedSelManager.filters.push({func:e=>e.selectMode===this.selectMode||this.selectMode===Da.SM_None,force:!1})}bindEngine(e){if(this.wrappedEngine=e,this.wrappedSelManager.engine=e,this.wrappedEngine.enableClipping=this.wrappedEnableClipping,this.wrappedEngine.enableDynSel=this.wrappedEnableDynSel,e.selectionEvent.add((e=>{this.wrappedInterMode===ja.Normal?(e?.type===Nr.MoveOn&&this.detect(e.info),e?.type===Nr.ClickOn&&(e.info?this.select(e.info):this.selectDetected())):this.wrappedInterMode===ja.CreateLine&&(e?.info?this.createLineEvent(e.info[0]):e?.pos2&&this.createLineEvent(e.pos2))})),this.wrappedEngine.engine){const e=new a(-100,-100,-100),t=new a(100,100,100);this.wrappedEngine.engine.userDefinedAdaptRange=new q(e,t)}}get enableClipping(){return this.wrappedEnableClipping}set enableClipping(e){this.wrappedEnableClipping!==e&&(this.wrappedEngine&&(this.wrappedEngine.enableClipping=e),this.wrappedEnableClipping=e)}get enableDynSel(){return this.wrappedEnableDynSel}set enableDynSel(e){this.wrappedEnableDynSel=e,this.wrappedEngine&&(this.wrappedEngine.enableDynSel=e)}set selectTol(e){this.wrappedSelManager.selTol=e}get selectTol(){return this.wrappedSelManager.selTol}fitRange(){const e=this.engine?.engine;e&&(e.userDefinedAdaptRange=e.domainRange)}fitRotCenter(e){const t=this.engine?.engine;if(!t)return;let i;if(e?i=e:(i=new Array,this.wrappedObjects.forEach((e=>{e.visible&&i.push(e)}))),0===i.length)t.rotationCenter=new a(0,0,0);else{const e=new q;i.forEach((t=>{e.union(t.boundingBox)})),t.rotationCenter=e.getCenter(new a)}}fitAll(){this.fitRange(),this.fitRotCenter();const e=[];this.wrappedObjects.forEach((t=>{t.visible&&e.push(t)})),this.fitObjects(e)}fitObjects(e){const t=[];e.forEach((e=>{e.group.eles.forEach((e=>{if(!e.isGeomEle())return;const i=e.shapes?.meshes();if(!i)return;let n=i.next();for(;!n.done;)t.push(n.value),n=i.next()}))})),t.length>0&&this.wrappedEngine?.focus(t)}updateCB=e=>{if(void 0!==e){if(e.type===Fa.Redisplay&&this.reDisplay(e.arg),e.type===Fa.ViewModeChanged){const t=e.arg;this.updateObjViewMode(t.object,null===t.mode?this.viewMode:t.mode)}if(e.type===Fa.Update){const t=e.arg,i=t.viewMode??this.viewMode;this.updateObject(t,i,i)}}};display(e){if(!this.wrappedEngine||this.wrappedObjects.indexOf(e)>=0)return!1;if(e.isBind)throw Error("This object has been displayed on another view!");const t=null!==e.viewMode?e.viewMode:this.viewMode;return!!e.display(this.wrappedEngine,t)&&(this.wrappedSelManager.loadSelectObj(e,t),e.updateEvent.add(this.updateCB),this.legendMgr.bindObject(e),this.wrappedObjects.push(e),e.isBind=!0,!0)}reDisplay(e){return this.remove(e),this.display(e)}remove(e){return!(!this.wrappedEngine||this.wrappedObjects.indexOf(e)<0)&&(!!e.remove(this.wrappedEngine)&&(!!this.wrappedSelManager.removeSelectObj(e,e.viewMode??this.viewMode)&&(e.getSelects(e.viewMode??this.viewMode).forEach((e=>{this.removeSelect(e)})),this.wrappedObjects.splice(this.wrappedObjects.indexOf(e),1),e.isBind=!1,e.updateEvent.remove(this.updateCB),this.legendMgr.unbindObject(e),e.clearData(),!0)))}removeAll(){this.wrappedEngine&&(this.wrappedObjects.forEach((e=>{e.remove(this.wrappedEngine)&&(this.wrappedSelManager.removeSelectObj(e,e.viewMode||this.viewMode),e.updateEvent.remove(this.updateCB),this.legendMgr.unbindObject(e),e.isBind=!1,e.clearData())})),this.wrappedObjects.splice(0,this.wrappedObjects.length),this.clearSelect())}detect(e){if(!this.wrappedEngine)return;if(!e)return void this.clearDetected();this.wrappedSelManager.select(e);const t=this.wrappedSelManager.getSelectEles();this.wrappedDetectedEle&&(0!==t.length&&t[0]===this.wrappedDetectedEle||this.clearDetected()),t.length>0&&!this.wrappedDetectedEle&&(this.wrappedDetectedEle=t[0],this.wrappedDetectedEle.getSelRender(this.wrappedDynSelGroup,this.wrappedDetectedEle),this.wrappedDynSelGroup.display(this.wrappedEngine))}clearDetected(){this.wrappedDetectedEle=null,this.wrappedEngine&&this.wrappedDynSelGroup.remove(this.wrappedEngine,!0)}selectElement(e){if(!this.wrappedEngine)return;const t=this.wrappedSelectedEles.indexOf(e);t<0?(this.wrappedSelectedEles.push(e),this.wrappedSelectGroup.remove(this.wrappedEngine),e.getSelRender(this.wrappedSelectGroup,e),this.wrappedSelectGroup.display(this.wrappedEngine),this.selectEvent.trigger({event:Ga.AddSelect,arg:[e]})):this.removeSelectByIndex(t)}selectElements(e){if(!this.wrappedEngine)return;const t=[];e.forEach((e=>{const i=this.wrappedSelectedEles.indexOf(e);i<0?(this.wrappedSelectedEles.push(e),e.getSelRender(this.wrappedSelectGroup,e),t.push(e)):this.removeSelectByIndex(i)})),this.wrappedSelectGroup.remove(this.wrappedEngine),this.wrappedSelectGroup.display(this.wrappedEngine),this.selectEvent.trigger({event:Ga.AddSelect,arg:t})}selectAllNodes(e){const t=e.getSelects(e.viewMode??this.viewMode),i=t.findIndex((e=>e.owner.type===Oa.OT_MeshNode));if(i<0)return;const n=Bo(t[i],this.viewMode);this.selectElements(n)}getHitPoint(e){const t=this.selManager.getHitInfo(e);if(t&&void 0!==t.shape)return new a(t.x,t.y,t.z)}selectDetected(){const e=this.wrappedDetectedEle;e?(this.clearDetected(),this.selectElement(e)):this.clearSelect()}removeSelect(e){if(!this.wrappedEngine)return;const t=this.wrappedSelectedEles.indexOf(e);this.removeSelectByIndex(t)}removeSelectByIndex(e){if(e<0||e>=this.wrappedSelectedEles.length)return;const t=this.wrappedSelectedEles[e];this.wrappedSelectedEles.splice(e,1),this.wrappedSelectGroup.removeByOwner(this.wrappedEngine,t,!0),this.selectEvent.trigger({event:Ga.DelSelect,arg:[t]})}clearSelect(){const e=this.wrappedSelectedEles;this.wrappedSelectedEles.splice(0,this.wrappedSelectedEles.length),this.wrappedSelectGroup.remove(this.wrappedEngine,!0),this.selectEvent.trigger({event:Ga.DelSelect,arg:e})}select(e){this.wrappedSelManager.select(e);const t=this.wrappedSelManager.getSelectEles();if(t.length>0){const e=[];if(this.extendSelMode===za.ESM_Undefined&&e.push(t[0]),this.extendSelMode===za.ESM_MeshSurfNodes){const i=this.extendSelParam.length>0?this.extendSelParam[0]:Math.PI/18;Io(t[0],this.viewMode,i).forEach((t=>e.push(t)))}if(this.extendSelMode===za.ESM_MeshAllNodes&&Bo(t[0],this.viewMode).forEach((t=>e.push(t))),this.extendSelMode===za.ESM_MeshSurfFaces){const i=this.extendSelParam.length>0?this.extendSelParam[0]:Math.PI/18;Fo(t[0],this.viewMode,i).forEach((t=>e.push(t)))}if(this.extendSelMode===za.ESM_MeshAllFaces&&No(t[0],this.viewMode).forEach((t=>e.push(t))),this.extendSelMode===za.ESM_MeshCurveEdges){const i=this.extendSelParam.length>0?this.extendSelParam[0]:Math.PI/18;Uo(t[0],this.viewMode,i).forEach((t=>e.push(t)))}this.selectElements(e)}else this.clearSelect()}updateObjViewMode(e,t){let i=this.viewMode;null!==e.viewMode&&(i=e.viewMode),this.updateObject(e,i,t)}updateObject(e,t,i){this.wrappedSelManager.removeSelectObj(e,t),this.wrappedEngine&&e.onViewModeChanged(this.wrappedEngine,i),this.wrappedSelManager.loadSelectObj(e,i)}get viewMode(){return this.wrappedViewMode}set viewMode(e){this.wrappedObjects.forEach((t=>{null===t.viewMode&&this.updateObjViewMode(t,e)})),this.wrappedViewMode=e}get selects(){return this.wrappedSelectedEles}get selManager(){return this.wrappedSelManager}viewAt(e){const t=new a(0,0,0),i=new a(0,0,1);switch(e){case Ha.Top:t.set(0,0,1),i.set(0,1,0);break;case Ha.Bottom:t.set(0,0,-1),i.set(0,-1,0);break;case Ha.Front:t.set(0,-1,0),i.set(0,0,1);break;case Ha.Back:t.set(0,1,0),i.set(0,0,1);break;case Ha.Left:t.set(-1,0,0),i.set(0,0,1);break;case Ha.Right:t.set(1,0,0),i.set(0,0,1);break;case Ha.TopFrontLeft:t.set(1,-1,1),i.set(0,0,1)}this.lookAt(t,new a(0,0,0),i)}lookAt(e,t,i){if(void 0===this.wrappedEngine?.engine?.rotationMatrix)return;const n=new ta;n.lookAt(e,t,i),n.invert(),this.wrappedEngine.engine.rotationMatrix=n}setBgColor(e){this.wrappedEngine?.engine?.updateBackground(e)}activeLegend(){this.legendMgr.legendPanel.bind(this.wrappedEngine?.engine)}deactiveLegend(){this.legendMgr.legendPanel.bind(void 0)}screenToWorld(e){if(!this.wrappedEngine)throw Error("Engine is not binded!");const t=rn.screenToWorld(e,this.wrappedEngine?.engine);return{pos:t.near,dir:t.dir}}worldToScreen(e){if(!this.wrappedEngine)throw Error("Engine is not binded!");return rn.worldToScreen(e,this.wrappedEngine?.engine)}get engine(){return this.wrappedEngine}get detectedElement(){return this.wrappedDetectedEle}setRotMode(e,t=void 0){let i;switch(e){case ka.Dynamic:i=void 0;break;case ka.XAxis:i={pos:new a,dir:new a(1,0,0)};break;case ka.YAxis:i={pos:new a,dir:new a(0,1,0)};break;case ka.ZAxis:i={pos:new a,dir:new a(0,0,1)};break;case ka.Custom:t&&(i={pos:t.pos.clone(),dir:t.dir.clone()});break;default:i=void 0}this.engine&&this.engine.engine&&(i?this.engine.engine.rotationCenter=new we(i?.pos,i?.dir):this.fitRotCenter())}get enableRuler(){return void 0!==this.engine&&this.engine?.enableRuler}set enableRuler(e){this.engine&&(this.engine.enableRuler=e)}set2DMode(e){void 0!==this.engine&&(e?(this.engine.enable2DMode=!0,this.viewAt(Ha.Top)):(this.engine.enable2DMode=!1,this.viewAt(Ha.TopFrontLeft)))}getLabelTextAnchor(e,t){const i=this.worldToScreen(e).clone().add(t||new na(-40,-40)),n=this.screenToWorld(i);return e.clone().sub(n.pos).angleTo(n.dir)>Math.PI/2&&n.dir.negate(),new we(n.pos,n.dir).closestPointToPoint(e,new $r)}enableInterMode(e){if(this.wrappedInterMode===e)return!0;if(this.wrappedInterMode===ja.CreateLine&&(this.wrappedCLRender?.remove(this.engine),this.wrappedCLRender=null,this.wrappedCLPS=null,this.wrappedCLPE=null),this.wrappedInterMode=e,this.wrappedInterMode===ja.CreateLine){this.wrappedCLRender=new Ro(null);const e=this.wrappedCLRender.config;e.textCfg.color=new Jr(0),e.pntConfig.color=new Jr(16711680),e.pntConfig.size=10,e.lineConfig.color=new Jr(0)}return!0}get interMode(){return this.wrappedInterMode}createLineEvent(e){const t=new $r;if(e.z)t.set(e.x,e.y,e.z);else{const i=new ea;if(this.wrappedObjects.forEach((e=>{e.visible&&(i.expandByPoint(e.boundingBox.min),i.expandByPoint(e.boundingBox.max))})),i.min.x===1/0||i.min.y===1/0||i.min.z===1/0)return;const n=this.screenToWorld(new na(e.x,e.y));let s=null,r=null;const a=e=>{const t=e.clone().sub(n.pos).dot(n.dir);(null===s||tr)&&(r=t)};if(a(new $r(i.min.x,i.min.y,i.min.z)),a(new $r(i.max.x,i.max.y,i.max.z)),a(new $r(i.min.x,i.min.y,i.max.z)),a(new $r(i.min.x,i.max.y,i.min.z)),a(new $r(i.max.x,i.min.y,i.min.z)),a(new $r(i.max.x,i.max.y,i.min.z)),a(new $r(i.max.x,i.min.y,i.max.z)),a(new $r(i.min.x,i.max.y,i.max.z)),null===s||null===r)return;const o=n.pos.clone().add(n.dir.clone().multiplyScalar((s+r)/2));t.set(o.x,o.y,o.z)}if(this.wrappedCLPS&&this.wrappedCLPE&&(this.wrappedCLRender?.remove(this.engine),this.wrappedCLRender?.clearData(),this.wrappedCLPS=null,this.wrappedCLPE=null),null===this.wrappedCLRender)return;this.wrappedCLRender?.remove(this.engine);let i,n="";null===this.wrappedCLPS?(this.wrappedCLPS=t,n="PS",i=Va.SelectStart):(this.wrappedCLPE=t,n="PE",i=Va.SelectEnd);const s=new bo(this.wrappedCLRender);s.createItem(new mo(null,Oa.OT_Custom),0,1),s.fillData([t.x,t.y,t.z],[0]);if(new jo(n,this.wrappedCLRender).anchorPnt=t,this.wrappedCLPE&&this.wrappedCLPS){const e=new yo(this.wrappedCLRender);e.createItem(new mo(null,Oa.OT_Custom),0,1),e.fillData([this.wrappedCLPS.x,this.wrappedCLPS.y,this.wrappedCLPS.z,this.wrappedCLPE.x,this.wrappedCLPE.y,this.wrappedCLPE.z],[0,1])}this.wrappedCLRender.display(this.engine),this.interEvent.trigger({type:i,args:t})}get createLineStart(){return this.wrappedCLPS}get createLineEnd(){return this.wrappedCLPE}hilightObject(e,t){return!(this.wrappedObjects.indexOf(e)<0)&&(e.group.hilight(t),!0)}unHilight(e){return!(this.wrappedObjects.indexOf(e)<0)&&(e.group.unHilight(),!0)}hilightOwner(e,t,i){e.getSelects(e.viewMode??this.viewMode).forEach((e=>{e.owner.owner===t&&e.hilight(i)}))}unHilightOwner(e,t){e.getSelects(e.viewMode??this.viewMode).forEach((e=>{e.owner.owner===t&&e.unHiligth()}))}}class Wo extends Oo{wrappedTriangles;wrappedRenders=new Map;//! 显示对象枚举 wrappedPos=null;//! 位置信息 constructor(e){super(),this.wrappedTriangles=e}get triangulation(){return this.wrappedTriangles}set triangulation(e){this.wrappedTriangles=e,this.updateEvent.trigger({type:Fa.Redisplay,arg:this})}type(){return Na.TriangulationType}computeSelects(e){if(this.wrappedSelections.has(e))return!0;const t=[];if(e===Ba.WireFrame){const e=this.wrappedRenders.get("edges")?.items[0];if(!e)return!1;const i=new Co(e,Da.SM_None,this);t.push(i)}if(e===Ba.WireShaded||e===Ba.Shaded){const e=this.wrappedRenders.get("faces")?.items[0];if(!e)return!1;const i=new Co(e,Da.SM_None,this);t.push(i)}return this.wrappedSelections.set(e,t),!0}computeRenders(e){if(0===this.triangulation.triangleList.length)return!1;const t=()=>{if(this.wrappedPos)return;const e=[],t=this.triangulation;sa.toArray(t.nodeList).forEach((t=>{e.push(t)})),this.wrappedPos=new n(e,3)},i=()=>{if(this.wrappedRenders.has("faces"))this.group.eles.push(this.wrappedRenders.get("faces"));else{t();const e=new Mo(this.group),i=[],n=[],s=this.triangulation;la.toArray(s.triangleList).forEach((e=>{n.push(e)})),sa.toArray(s.normalList).forEach((e=>{i.push(e)}));const r=new mo(s,Oa.OT_Triangulation);e.createItem(r,0,s.triangleList.length),e.fillData(this.wrappedPos,i,n),this.wrappedRenders.set("faces",e)}},s=()=>{if(this.wrappedRenders.has("edges"))this.group.eles.push(this.wrappedRenders.get("edges"));else{t();const e=new yo(this.group),i=[],n=this.triangulation;n.triangleList.forEach((e=>{i.push(e.node1,e.node2,e.node2,e.node3,e.node3,e.node1)}));const s=new mo(n,Oa.OT_Triangulation);e.createItem(s,0,i.length/2),e.fillData(this.wrappedPos,i),this.wrappedRenders.set("edges",e)}};return e!==Ba.Shaded&&e!==Ba.WireShaded||i(),e!==Ba.WireFrame&&e!==Ba.WireShaded||s(),!0}clearData(){super.clearData(),this.wrappedRenders.clear(),this.wrappedPos=null}}class Ko extends Oo{origin=new $r(0,0,0);normal=new $r(0,0,1);xdir=new $r(1,0,0);uMin=-10;uMax=10;vMin=-10;vMax=10;wrappedRenders=new Map;//! 显示对象枚举 wrappedRenderTexts=[];constructor(e,t,i){super(),e&&this.origin.copy(e),t&&this.normal.copy(t),i&&this.xdir.copy(i),this.setTransparent(0),this.setLineColor(11184810),this.setLineWidth(.5),this.setFaceColor(16777215),this.group.config.triConfig.side=K,this.group.config.textConfig.alignment=Gs.TopLeft,this.group.config.textConfig.color=new g(0),this.group.config.textConfig.size=14}type(){return Na.PlaneType}computeSelects(e){if(this.wrappedSelections.has(e))return!0;const t=[],i=new To(Da.SM_None,new mo(this,Oa.OT_Custom),this);if(e===Ba.WireFrame||e===Ba.WireShaded){const e=this.wrappedRenders.get("edges")?.items[0];if(!e)return!1;const t=new Co(e,Da.SM_None,this);t.enable=!1,i.subElements.push(t)}if(e===Ba.Shaded||e===Ba.WireShaded){const e=this.wrappedRenders.get("faces")?.items[0];if(!e)return!1;const t=new Co(e,Da.SM_None,this);t.enable=!1,i.subElements.push(t)}return t.push(i),this.wrappedSelections.set(e,t),!0}computeRenders(e){const t=this.normal.clone().cross(this.xdir).normalize(),i=this.normal.normalize(),n=this.xdir.normalize();if(i.length()<1e-4||n.length()<1e-4||t.length()<1e-4)return console.error("Plane attr is not valid!"),!1;const s=n.clone().multiplyScalar(this.uMin),r=n.clone().multiplyScalar(this.uMax),a=t.clone().multiplyScalar(this.vMin),o=t.clone().multiplyScalar(this.vMax),h=this.origin.clone().add(s).add(a),d=this.origin.clone().add(s).add(o),p=this.origin.clone().add(r).add(o),l=this.origin.clone().add(r).add(a),c=()=>{if(this.wrappedRenders.has("faces"))this.group.eles.push(this.wrappedRenders.get("faces"));else{const e=new Mo(this.group),t=[],n=[];[h,d,p,l].forEach((e=>{t.push(e.x,e.y,e.z),n.push(i.x,i.y,i.z)}));const s=[0,1,2,2,3,0],r=new mo(this,Oa.OT_Custom);e.createItem(r,0,2),e.fillData(t,n,s),this.wrappedRenders.set("faces",e)}},u=()=>{if(this.wrappedRenders.has("edge"))this.group.eles.push(this.wrappedRenders.get("edges"));else{const e=new yo(this.group),t=[0,1,1,2,2,3,3,0],i=this.wrappedRenders.get("faces"),n=new mo(this,Oa.OT_Custom);e.createItem(n,0,t.length/2),e.fillData(i.posAttr(),t),this.wrappedRenders.set("edges",e)}};return e!==Ba.Shaded&&e!==Ba.WireShaded||c(),e!==Ba.WireFrame&&e!==Ba.WireShaded||u(),this.wrappedRenderTexts.length>0&&this.wrappedRenderTexts.forEach((e=>this.group.eles.push(e))),!0}appendText(e,t){const i=new jo(e,this.group);i.anchorPnt=new $r(t[0],t[1],t[2]),this.wrappedRenderTexts.push(i)}clearData(){super.clearData(),this.wrappedRenders.clear()}}class Yo extends Oo{wrappedLegend=null;//! 绑定的legend wrappedMesh;//! 网格对象 wrappedRenders=new Map;//! 显示对象数组 wrappedProperties=new Map;//! 属性列表 wrappedCurProp="";//! 当前使能属性 wrappedSolidColor=new g(12632256);wrappedLevelStates=new Map;constructor(e){super(),this.wrappedMesh=e,e.meshes.forEach((e=>this.wrappedLevelStates.set(e.level,!0))),this.setLineColor(0),this.setPntColor(0),this.wrappedGroup.config.lineConfig.polygonOffset=-1,this.wrappedGroup.config.pntConfig.polygonOffset=-2,this.wrappedGroup.config.pntConfig.size=5,this.wrappedGroup.config.triConfig.side=K,this.updateProperty()}onLegendUpdateCB=e=>{e?.type!==Ua.Range&&e?.type!==Ua.Colors&&e?.type!==Ua.Type||this.updateProperty()};unbindLegend=e=>{this.legend&&this.legend.updateEvent.remove(this.onLegendUpdateCB),e===this.legend&&(this.wrappedLegend=null)};useLegend=!0;bindLegend=e=>{this.wrappedLegend=e,this.legend&&(this.legend.updateEvent.add(this.onLegendUpdateCB),this.updateProperty())};type(){return Na.CellMeshType}computeSelects(e){return!0}computeRenders(e){const t=(t,i)=>{this.wrappedRenders.has(t.level)||this.wrappedRenders.set(t.level,new Map);const s=this.wrappedRenders.get(t.level);let r=null;if(s){const e=s.get("edges");e&&(r=e.posAttr());const t=s.get("faces");t&&(r=t.posAttr())}if(null===r){const e=[];1===i?t.cells.forEach((i=>{const n=t.xCoords[i.i],s=t.xCoords[i.i+1];e.push(n,0,0,s,0,0)})):2===i?t.cells.forEach((i=>{const n=t.xCoords[i.i],s=t.xCoords[i.i+1],r=t.yCoords[i.j],a=t.yCoords[i.j+1];e.push(n,r,0),e.push(s,r,0),e.push(s,a,0),e.push(n,a,0)})):3===i&&t.cells.forEach((i=>{const n=t.xCoords[i.i],s=t.xCoords[i.i+1],r=t.yCoords[i.j],a=t.yCoords[i.j+1],o=t.zCoords[i.k],h=t.zCoords[i.k+1];e.push(n,r,o),e.push(s,r,o),e.push(s,a,o),e.push(n,a,o),e.push(n,r,h),e.push(s,r,h),e.push(s,a,h),e.push(n,a,h),e.push(n,r,o),e.push(s,r,o),e.push(s,r,h),e.push(n,r,h),e.push(n,a,o),e.push(n,a,h),e.push(s,a,h),e.push(s,a,o),e.push(n,r,o),e.push(n,r,h),e.push(n,a,h),e.push(n,a,o),e.push(s,r,o),e.push(s,a,o),e.push(s,a,h),e.push(s,r,h)})),r=new n(e,3)}const a=()=>{if(s&&s.has("edges"))return void this.wrappedGroup.eles.push(s.get("edges"));const e=new yo(this.wrappedGroup),n=[];let a=0;1===i?t.cells.forEach((t=>{n.push(2*a,2*a+1);const i=new mo(t,Oa.OT_MeshElement);e.createItem(i,a,1),a+=1})):2===i?t.cells.forEach((t=>{n.push(a,a+1),n.push(a+1,a+2),n.push(a+2,a+3),n.push(a+3,a);const i=new mo(t,Oa.OT_MeshElement);e.createItem(i,a,4),a+=4})):3===i&&t.cells.forEach((t=>{n.push(2*a,2*a+1),n.push(2*a+1,2*a+2),n.push(2*a+2,2*a+3),n.push(2*a+3,2*a),n.push(2*a+4,2*a+5),n.push(2*a+5,2*a+6),n.push(2*a+6,2*a+7),n.push(2*a+7,2*a+4),n.push(2*a,2*a+4),n.push(2*a+1,2*a+5),n.push(2*a+2,2*a+6),n.push(2*a+3,2*a+7);const i=new mo(t,Oa.OT_MeshElement);e.createItem(i,a,12),a+=12})),e.fillData(r,n),s&&s.set("edges",e)},o=()=>{if(s&&s.has("faces"))return void this.wrappedGroup.eles.push(s.get("faces"));const e=new Mo(this.wrappedGroup),n=[];let a=0;2===i?t.cells.forEach((t=>{n.push(a,a+1,a+2),n.push(a+2,a+3,a);const i=new mo(t,Oa.OT_MeshElement);e.createItem(i,a,2),a+=2})):3===i&&t.cells.forEach((t=>{n.push(2*a,2*a+1,2*a+2),n.push(2*a+2,2*a+3,2*a),n.push(2*a+4,2*a+5,2*a+6),n.push(2*a+6,2*a+7,2*a+4),n.push(2*a+8,2*a+9,2*a+10),n.push(2*a+10,2*a+11,2*a+8),n.push(2*a+12,2*a+13,2*a+14),n.push(2*a+14,2*a+15,2*a+12),n.push(2*a+16,2*a+17,2*a+18),n.push(2*a+18,2*a+19,2*a+16),n.push(2*a+20,2*a+21,2*a+22),n.push(2*a+22,2*a+23,2*a+20);const i=new mo(t,Oa.OT_MeshElement);e.createItem(i,a,12),a+=12}));const o=[];if(this.wrappedProperties.has(t.level)){const e=this.wrappedProperties.get(t.level);e&&e.forEach(((e,t)=>{o.push({name:t,attr:e.attr})}))}e.fillData(r,[],n,o),s&&s.set("faces",e)};e!==Ba.WireFrame&&e!==Ba.WireShaded||a(),e!==Ba.Shaded&&e!==Ba.WireShaded||i>1&&o()},i=this.wrappedMesh.dimension;return this.wrappedLevelStates.forEach(((e,n)=>{if(!1===e)return;const s=this.mesh.meshes.find((e=>e.level===n));s&&t(s,i)})),!0}attachProperty(e,t,i){const s=this.wrappedMesh.meshes.find((t=>t.level===e));if(void 0===s)return!1;const r=this.wrappedMesh.dimension;this.wrappedProperties.has(e)||this.wrappedProperties.set(e,new Map);const a=new Map;let o=0;for(;o{const t=a.get(e.index);if(void 0===t)throw Error(`Node prop is not exist! id: ${e.index}`);2===r?h.push(t,t,t,t):3===r&&(h.push(t,t,t,t,t,t,t,t),h.push(t,t,t,t,t,t,t,t),h.push(t,t,t,t,t,t,t,t)),t>p&&(p=t),t{if(!0!==this.levelVisible(n))return;const s=i.get(this.wrappedCurProp);s&&(s.mint&&(t=s.max))}));const i=this.legend?.range;this.group.config.triConfig.color=new hr(Vt.Fragment_Color_Map,this.legend?this.legend.colors:[new g(1,0,0),new g(0,1,0),new g(0,0,1)],this.wrappedCurProp,this.legend?.type===ns.Nearest?dr.Nearest:dr.Liner,i?i.min:e,i?i.max:t),this.group.config.triConfig.color.attributeName=this.wrappedCurProp}}get legend(){return this.wrappedLegend}levelVisible(e){return this.wrappedLevelStates.get(e)}setLevelVisible(e,t){this.levelVisible(e)!==t&&(this.wrappedLevelStates.set(e,t),this.updateEvent.trigger({type:Fa.Update,arg:this}))}get mesh(){return this.wrappedMesh}get props(){return this.wrappedProperties}clearData(){super.clearData(),this.wrappedRenders.clear()}}class Xo extends Oo{arrowCfg;wrappedLegend=null;//! 绑定的legend wrappedData;//! 网格对象 wrappedRenders=new Map;//! 显示对象数组 wrappedProperty=null;//! 属性 wrappedUseProp=!1;//! 使能属性 wrappedScaled=!0;//! 使能放缩 wrappedOrigin=0;//! 属性放缩原点 wrappedFactor=5;//! 放缩系数 wrappedSolidColor=new g(12632256);constructor(e){super(),this.wrappedData=e,this.setLineColor(0),this.setPntColor(0),this.wrappedGroup.config.lineConfig.polygonOffset=-1,this.wrappedGroup.config.pntConfig.polygonOffset=-2,this.wrappedGroup.config.pntConfig.size=5,this.wrappedGroup.config.triConfig.side=K,this.updateProperty(),this.arrowCfg={scale:!0,tailLen:1,tailRad:.04,headLen:.3,headRad:.1}}onLegendUpdateCB=e=>{e?.type!==Ua.Range&&e?.type!==Ua.Colors&&e?.type!==Ua.Type||this.updateProperty()};unbindLegend=e=>{this.legend&&this.legend.updateEvent.remove(this.onLegendUpdateCB),e===this.legend&&(this.wrappedLegend=null)};useLegend=!0;bindLegend=e=>{this.wrappedLegend=e,this.legend&&(this.legend.updateEvent.add(this.onLegendUpdateCB),this.updateProperty())};type(){return Na.VectorGraphType}computeSelects(e){return!0}computeRenders(e){const t=()=>{if(this.wrappedRenders.has("faces"))return void this.wrappedGroup.eles.push(this.wrappedRenders.get("faces"));const e=new Mo(this.group),t=[],i=[],s=[],r=[],o=[],h=new q;let d=Number.MAX_VALUE,p=-Number.MAX_VALUE;const l=this.wrappedData.vectors;for(let e=0;ep&&(p=n),n{const n=new _a(e.pos,e.vec),a=(this.scaled?e.prop:g)*this.wrappedFactor/100*f,o=Qa.arrow(a*this.arrowCfg.tailRad,a*this.arrowCfg.tailLen,a*this.arrowCfg.headRad,a*this.arrowCfg.headLen,n);if(!o)return;const h=o;la.toArray(h.triangleList,t.length/3).forEach((e=>{s.push(e)})),sa.toArray(h.nodeList).forEach((e=>{t.push(e)})),h.nodeList.forEach((()=>r.push(e.prop+this.wrappedOrigin))),sa.toArray(h.normalList).forEach((e=>{i.push(e)}))}));const m=new mo(this,Oa.OT_Custom);e.createItem(m,0,s.length/3);const w=new n(r,1);e.fillData(t,i,s,[{name:"property",attr:w}]),p+=this.wrappedOrigin,d+=this.wrappedOrigin,this.wrappedProperty={attr:w,max:p,min:d},this.updateProperty(),this.wrappedRenders.set("faces",e)};return e!==Ba.Shaded&&e!==Ba.WireShaded&&e!==Ba.WireFrame||t(),!0}get useProperty(){return this.wrappedUseProp}set useProperty(e){e!==this.useProperty&&(this.wrappedUseProp=e,this.updateProperty())}setFaceColor(e){this.wrappedSolidColor=new g(e),this.setClippingColor(e)}updateProperty(){if(this.useProperty){if(null===this.wrappedProperty)return;const e=this.legend?.range;this.group.config.triConfig.color=new hr(Vt.Fragment_Color_Map,this.legend?this.legend.colors:[this.wrappedSolidColor],"property",this.legend?.type===ns.Nearest?dr.Nearest:dr.Liner,e?e.min:this.wrappedProperty.min,e?e.max:this.wrappedProperty.max),this.group.config.triConfig.color.attributeName="property"}else this.group.config.triConfig.color=new hr(Vt.Fragment_Color_Map,[this.wrappedSolidColor],"",dr.Liner,0,0)}get legend(){return this.wrappedLegend}get data(){return this.wrappedData}get factor(){return this.wrappedFactor}set factor(e){this.wrappedFactor=e,this.updateEvent.trigger({type:Fa.Redisplay,arg:this})}get origin(){return this.wrappedOrigin}set origin(e){this.wrappedOrigin=e,this.updateEvent.trigger({type:Fa.Redisplay,arg:this})}get scaled(){return this.wrappedScaled}set scaled(e){this.wrappedScaled=e,this.updateEvent.trigger({type:Fa.Redisplay,arg:this})}get prop(){return this.wrappedProperty}clearData(){super.clearData(),this.wrappedRenders.clear()}}class qo extends Oo{wrappedGeom;wrappedRenders=new Map;//! 显示对象枚举 wrappedPos=null;//! 位置信息 wrappedShowTriangles=!1;//! 是否显示平面 wrappedTrianglesCfg=new vr({color:new g(11184810),config:new Sr(1),style:lr.Regular});constructor(e){super(),this.wrappedGeom=e,this.setLineColor(0),this.setLineWidth(3),this.setFaceColor(16777215),this.group.config.triConfig.side=K,this.group.config.textConfig.alignment=Gs.TopLeft,this.group.config.textConfig.color=new g(0),this.group.config.textConfig.size=14,this.group.config.lineConfig.polygonOffset=-1,this.wrappedTrianglesCfg.polygonOffset=-1}setTrianglesLineColor(e){this.wrappedTrianglesCfg.color=new g(e)}setTrianglesLineWidth(e){this.wrappedTrianglesCfg.config.lineWidth=e}type(){return Na.PolyGeomType}computeSelects(e){if(this.wrappedSelections.has(e))return!0;const t=[];return e===Ba.WireFrame&&this.wrappedRenders.get("edges")?.items?.forEach((e=>{const i=new Co(e,Da.SM_None,this);t.push(i)})),e!==Ba.WireShaded&&e!==Ba.Shaded||this.wrappedRenders.get("faces")?.items?.forEach((e=>{const i=new Co(e,Da.SM_None,this);t.push(i)})),this.wrappedRenders.get("lines")?.items?.forEach((e=>{const i=new Co(e,Da.SM_None,this);t.push(i)})),this.wrappedSelections.set(e,t),!0}computeRenders(e){if(0===this.geom.lines.length&&0===this.geom.surfs.length)return console.error("Poly geometry is not valid!"),!1;const t=()=>{if(this.wrappedPos)return;const e=[];sa.toArrayVec(this.geom.nodes).forEach((t=>{e.push(t)})),this.wrappedPos=new n(e,3)},i=()=>{if(this.wrappedRenders.has("faces"))this.group.eles.push(this.wrappedRenders.get("faces"));else{t();const e=new Mo(this.group),i=[],n=[];this.geom.surfs.forEach((t=>{const n=i.length/3;la.toArray(t.triangles,0).forEach((e=>{i.push(e)}));const s=new mo(t,Oa.OT_PolyGeometry);e.createItem(s,n,t.triangles.length)})),e.fillData(this.wrappedPos,n,i),this.wrappedRenders.set("faces",e)}},s=()=>{if(this.wrappedRenders.has("edges"))this.group.eles.push(this.wrappedRenders.get("edges"));else{t();const e=new yo(this.group),i=[];this.geom.surfs.forEach((t=>{const n=i.length/2;t.triangles.forEach((e=>{i.push(e.node1,e.node2,e.node2,e.node3,e.node3,e.node1)}));const s=new mo(t,Oa.OT_PolyGeometry);e.createItem(s,n,3*t.triangles.length)})),e.fillData(this.wrappedPos,i),this.wrappedRenders.set("edges",e),e.items.forEach((e=>this.group.config.customCfgs.set(e,this.wrappedTrianglesCfg)))}},r=()=>{if(this.wrappedRenders.has("lines"))this.group.eles.push(this.wrappedRenders.get("lines"));else{t();const e=new yo(this.group),i=[];this.geom.lines.forEach((t=>{const n=i.length/2;Za.createIndex(t).forEach((e=>i.push(e)));const s=new mo(t,Oa.OT_PolyGeometry);e.createItem(s,n,i.length/2-n)})),e.fillData(this.wrappedPos,i),this.wrappedRenders.set("lines",e)}};return e!==Ba.Shaded&&e!==Ba.WireShaded||(i(),s()),e!==Ba.WireFrame&&e!==Ba.WireShaded||r(),this.updateVisibility(),!0}updateVisibility(){const e=this.wrappedRenders.get("edges");e&&(e.visible=this.showTriangles)}get geom(){return this.wrappedGeom}set geom(e){this.wrappedGeom=e,this.updateEvent.trigger({type:Fa.Redisplay,arg:this})}get showTriangles(){return this.wrappedShowTriangles}set showTriangles(e){e!==this.wrappedShowTriangles&&(this.wrappedShowTriangles=e,this.updateVisibility())}get visible(){return this.wrappedVisible}set visible(e){this.wrappedVisible!==e&&(this.wrappedVisible=e,this.wrappedGroup.visible=e,this.updateVisibility())}clearData(){super.clearData(),this.wrappedRenders.clear(),this.wrappedPos=null}}class Zo extends ko{wrappedLine;constructor(e,t,i,n=!0,s=!0){super(t),this.wrappedLine=new Hs(i,e,n,s)}get points(){return this.wrappedLine.points}set points(e){this.wrappedLine.points=e}get headArrow(){return this.wrappedLine.headArrow||!1}set headArrow(e){this.wrappedLine.headArrow=e}get tailArrow(){return this.wrappedLine.tailArrow||!1}set tailArrow(e){this.wrappedLine.tailArrow=e}get visible(){return!0}set visible(e){console.log(e)}get config(){return this.wrappedLine.config}set config(e){this.wrappedLine.config=e}transform(e){const t=[];this.points.forEach((i=>{t.push(new ia(i.x,i.y,i.z).applyMatrix4(e))})),this.points=t}type(){return La.AnnoLine}display(e,t){return e.addLine2D(this.wrappedLine),!0}remove(e){return e.removeLine2D(this.wrappedLine),!0}removeByOwner(e,t,i){return this.owner===t&&(this.remove(e),!0)}copyData(e){const t=[];this.points.forEach((e=>{t.push(new $r(e.x,e.y,e.z))}));const i=new Qs(this.config);return new Zo(t,e,i,this.headArrow,this.tailArrow)}isEmpty(){return!1}hilight(e){this.config.color=e.line2DCfg.color,this.config.width=e.line2DCfg.width,this.config.dashPattern=e.line2DCfg.dashPattern}}class Qo extends Oo{wrappedGeom;wrappedRenders=new Map;//! 显示对象枚举 wrappedPos=null;//! 位置信息 wrappedShowTriangles=!1;//! 是否显示平面 wrappedTrianglesCfg=new vr({color:new g(11184810),config:new Sr(1),style:lr.Regular});constructor(e){super(),this.wrappedGeom=e,this.setLineColor(0),this.setLineWidth(3),this.setFaceColor(16777215),this.group.config.triConfig.side=K,this.group.config.textConfig.alignment=Gs.TopLeft,this.group.config.textConfig.color=new g(0),this.group.config.textConfig.size=14,this.group.config.lineConfig.polygonOffset=-1,this.wrappedTrianglesCfg.polygonOffset=-1,this.group.config.line2DCfg.color=new g(16711680),this.group.config.line2DCfg.dashPattern=[20,2,2,2]}setTrianglesLineColor(e){this.wrappedTrianglesCfg.color=new g(e)}setTrianglesLineWidth(e){this.wrappedTrianglesCfg.config.lineWidth=e}type(){return Na.PolyGeomType}computeSelects(e){if(this.wrappedSelections.has(e))return!0;const t=[];return e===Ba.WireFrame&&this.wrappedRenders.get("edges")?.items?.forEach((e=>{const i=new Co(e,Da.SM_None,this);t.push(i)})),e!==Ba.WireShaded&&e!==Ba.Shaded||this.wrappedRenders.get("faces")?.items?.forEach((e=>{const i=new Co(e,Da.SM_None,this);t.push(i)})),this.wrappedRenders.get("lines")?.items?.forEach((e=>{const i=new Co(e,Da.SM_None,this);t.push(i)})),this.wrappedSelections.set(e,t),!0}computeRenders(e){if(0===this.geom.lines.length&&0===this.geom.surfs.length)return console.error("Poly geometry is not valid!"),!1;const t=()=>{if(this.wrappedPos)return;const e=[];sa.toArrayVec(this.geom.nodes).forEach((t=>{e.push(t)})),this.wrappedPos=new n(e,3)},i=()=>{if(this.wrappedRenders.has("faces"))this.group.eles.push(this.wrappedRenders.get("faces"));else{t();const e=new Mo(this.group),i=[],n=[];this.geom.surfs.forEach((t=>{const n=i.length/3;la.toArray(t.triangles,0).forEach((e=>{i.push(e)}));const s=new mo(t,Oa.OT_PolyGeometry);e.createItem(s,n,t.triangles.length)})),e.fillData(this.wrappedPos,n,i),this.wrappedRenders.set("faces",e)}},s=()=>{if(this.wrappedRenders.has("edges"))this.group.eles.push(this.wrappedRenders.get("edges"));else{t();const e=new yo(this.group),i=[];this.geom.surfs.forEach((t=>{const n=i.length/2;t.triangles.forEach((e=>{i.push(e.node1,e.node2,e.node2,e.node3,e.node3,e.node1)}));const s=new mo(t,Oa.OT_PolyGeometry);e.createItem(s,n,3*t.triangles.length)})),e.fillData(this.wrappedPos,i),this.wrappedRenders.set("edges",e),e.items.forEach((e=>this.group.config.customCfgs.set(e,this.wrappedTrianglesCfg)))}};return e!==Ba.Shaded&&e!==Ba.WireShaded||(i(),s()),(()=>{if(this.wrappedRenders.has("lines"))this.group.eles.push(this.wrappedRenders.get("lines"));else{t();const e=new yo(this.group),i=[];this.geom.lines.forEach((t=>{const n=i.length/2;Za.createIndex(t).forEach((e=>i.push(e)));const s=new mo(t,Oa.OT_PolyGeometry);e.createItem(s,n,i.length/2-n)})),e.fillData(this.wrappedPos,i),this.wrappedRenders.set("lines",e)}})(),(()=>{const e=this.geom.bndBox(),t=e.max.y-e.min.y,i=e.min.y-.2*t,n=e.max.y+.2*t;new Zo([new a(0,i,0),new a(0,n,0)],this.group,this.group.config.line2DCfg,!1,!1).visible=!0})(),this.updateVisibility(),!0}updateVisibility(){const e=this.wrappedRenders.get("edges");e&&(e.visible=this.showTriangles)}get geom(){return this.wrappedGeom}set geom(e){this.wrappedGeom=e,this.updateEvent.trigger({type:Fa.Redisplay,arg:this})}get showTriangles(){return this.wrappedShowTriangles}set showTriangles(e){e!==this.wrappedShowTriangles&&(this.wrappedShowTriangles=e,this.updateVisibility())}get visible(){return this.wrappedVisible}set visible(e){this.wrappedVisible!==e&&(this.wrappedVisible=e,this.wrappedGroup.visible=e,this.updateVisibility())}clearData(){super.clearData(),this.wrappedRenders.clear(),this.wrappedPos=null}}class $o extends Oo{wrappedLegend=null;//! 绑定的legend wrappedGeom;//! 流线几何对象 wrappedRenders=new Map;//! 显示对象数组 wrappedProperties=new Map;//! 属性列表 wrappedCurProp="";//! 当前使能属性 wrappedLineColor=new g(16711935);constructor(e){super(),this.wrappedGeom=e,this.setLineWidth(3),this.updateProperty()}onLegendUpdateCB=e=>{e?.type!==Ua.Range&&e?.type!==Ua.Colors&&e?.type!==Ua.Type||this.updateProperty()};unbindLegend=e=>{this.legend&&this.legend.updateEvent.remove(this.onLegendUpdateCB),e===this.legend&&(this.wrappedLegend=null)};useLegend=!0;bindLegend=e=>{this.wrappedLegend=e,this.legend&&(this.legend.updateEvent.add(this.onLegendUpdateCB),this.updateProperty())};type(){return Na.StreamLineType}computeSelects(e){return!0}computeRenders(e){return(()=>{if(this.wrappedRenders.has("lines"))return void this.wrappedGroup.eles.push(this.wrappedRenders.get("lines"));const e=new yo(this.wrappedGroup),t=[],i=[];let n=0;this.wrappedGeom.lines.forEach((e=>{t.push(...e);for(let t=1;t{s.push({name:t,attr:e.attr})})),e.fillData(t,i,s),e.createItem(new mo(null,Oa.OT_Custom),0,i.length/2),this.wrappedRenders.set("edges",e)})(),!0}attachProperty(e){const t=[];for(let i=0;i{e>s&&(s=e),e{void 0!==e&&(e.type!==Ua.Colors&&e.type!==Ua.Range||this.updateProperty())};get legend(){return this.wrappedLegend}get geom(){return this.wrappedGeom}get props(){return this.wrappedProperties}clearData(){super.clearData(),this.wrappedRenders.clear()}}class Jo extends Oo{wrappedStart;wrappedEnd;wrappedTxt;wrappedEles=new Map;constructor(e,t,i){super(),this.wrappedStart=new $r(e.x,e.y,e.z),this.wrappedEnd=new $r(t.x,t.y,t.z),this.wrappedTxt=i,this.group.config.textCfg.color=new Jr(0),this.group.config.line2DCfg.arrow={length:20,width:10}}get start(){return this.wrappedStart}set start(e){const t=new $r(e.x,e.y,e.z);t.equals(this.wrappedStart)||(this.wrappedStart=t,this.updatePnts())}get end(){return this.wrappedEnd}set end(e){const t=new $r(e.x,e.y,e.z);t.equals(this.wrappedEnd)||(this.wrappedEnd=t,this.updatePnts())}get customTxt(){return this.wrappedTxt}set customTxt(e){e!==this.customTxt&&(this.wrappedTxt=e,this.updateTxt())}get length(){return this.start.distanceTo(this.end)}updatePnts(){const e=this.wrappedEles.get("line");if(e){const t=[this.start,this.end];e.points=t,this.updateTxt()}}updateTxt(){const e=this.wrappedEles.get("label");if(e){const t=e;t.anchorPnt=this.start.clone().add(this.end).divideScalar(2);const i=this.customTxt||this.length.toFixed(2);t.text=i,t.direction=this.end.clone().sub(this.start)}}type(){return Na.LengthDim3DType}computeSelects(e){return!0}computeRenders(e){if(0===this.wrappedEles.size){const e=new Zo([this.start,this.end],this.group,this.group.config.line2DCfg,!0,!0);this.wrappedEles.set("line",e);const t=new jo("",this.group,this.group.config.textCfg);return this.wrappedEles.set("label",t),this.updateTxt(),!0}return!0}clearData(){super.clearData(),this.wrappedEles.clear()}}const eh=(e,t)=>{const i=[new $r(0,-t.tail.width/2,0),new $r(t.tail.length,-t.tail.width/2,0),new $r(t.tail.length,-t.head.width/2,0),new $r(t.tail.length+t.head.length,0,0),new $r(t.tail.length,t.head.width/2,0),new $r(t.tail.length,t.tail.width/2,0),new $r(0,t.tail.width/2,0)],n=e.toMatrix4();i.forEach((e=>e.applyMatrix4(n)));const s=new Za(i);return s.lines.push({indices:[0,1,2,3,4,5,6,0],isSegment:!1}),s};class th extends qo{wrappedCSys;wrappedParam;wrappedTxt;wrappedTxtEle;constructor(e,t,i){super(eh(e,t)),this.wrappedCSys=e,this.wrappedParam=t,this.wrappedTxt=i,this.group.config.textCfg=new or(this.group.config.textCfg),this.group.config.textCfg.alignment=Gs.Center}get csys(){return this.wrappedCSys}set csys(e){e!==this.wrappedCSys&&(this.wrappedCSys=e,this.updateGeom())}get param(){return this.wrappedParam}set param(e){e!==this.wrappedParam&&(this.wrappedParam=e,this.updateGeom())}get text(){return this.wrappedTxt}set text(e){e!==this.wrappedTxt&&(this.wrappedTxt=e,this.updateTxt())}updateGeom(){this.geom=eh(this.csys,this.param)}updateTxt(){const e=this.text||"";this.wrappedTxtEle||(this.wrappedTxtEle=new jo(e,this.group,this.group.config.textCfg));const t=this.wrappedTxtEle;t.text=e,t.direction=this.csys.xDir.clone(),t.facing=this.csys.zDir.clone();const i=new $r((this.param.head.length+this.param.tail.length)/2).applyMatrix4(this.csys.toMatrix4());t.anchorPnt=i,void 0===this.group.eles.find((e=>e===this.wrappedTxtEle))&&this.group.eles.push(this.wrappedTxtEle)}computeRenders(e){return!!super.computeRenders(e)&&(this.updateTxt(),!0)}type(){return Na.AnnoPlaneType}clearData(){super.clearData(),this.wrappedTxtEle=void 0}}class ih extends Oo{wrappedText;//! label文本内容 wrappedAnchor;//! label锚定位置 wrappedTextAnchor;//! 文本锚定位置 wrappedTxtEle=null;//! 文本单元 wrappedLinEle=null;//! 引线单元 wrappedAnchorEle=null;//! 锚定点单元 constructor(e,t,i){super(),this.wrappedAnchor=t,this.wrappedText=e,this.wrappedTextAnchor=i,this.group.config.pntConfig.color=new g(16711680),this.group.config.pntConfig.size=20}type(){return Na.AnnoLabelType}get text(){return this.wrappedText}set text(e){this.wrappedText=e,this.updateText()}computeSelects(e){return!0}updateAnnoLine(){this.wrappedAnchorEle||(this.wrappedAnchorEle=new bo(this.group),this.wrappedAnchorEle.createItem(new mo(null,Oa.OT_Custom),0,1),this.wrappedAnchorEle.fillData([this.wrappedAnchor.x,this.wrappedAnchor.y,this.wrappedAnchor.z],[0])),void 0===this.group.eles.find((e=>e===this.wrappedAnchorEle))&&this.group.eles.push(this.wrappedAnchorEle),this.wrappedLinEle||(this.wrappedLinEle=new Zo([this.wrappedAnchor,this.wrappedTextAnchor],this.group,this.group.config.line2DCfg,!1,!1)),void 0===this.group.eles.find((e=>e===this.wrappedLinEle))&&this.group.eles.push(this.wrappedLinEle)}updateText(){const e=this.wrappedText;this.wrappedTxtEle||(this.wrappedTxtEle=new jo(e,this.group,this.group.config.textCfg));const t=this.wrappedTxtEle;t.text=e,t.anchorPnt=this.wrappedTextAnchor,void 0===this.group.eles.find((e=>e===this.wrappedTxtEle))&&this.group.eles.push(this.wrappedTxtEle)}computeRenders(e){return this.updateAnnoLine(),this.updateText(),!0}clearData(){super.clearData(),this.wrappedTxtEle=null,this.wrappedLinEle=null}}const nh=globalThis;if(nh.poseidonEngineCoreLoaded)throw new Error("multiple instances of poseidon-engine-core to load");nh.poseidonEngineCoreLoaded=!0;export{xr as ABOVE_ALL_SCENE,yr as ABOVE_ALL_SCENE_ORDER,Sn as ActionHandlerBase,Tt as ActivePlaneBoundaryBufferGeometry,Ct as AggregateMesh,ji as AnimationHelper,th as AnnoArrow,ih as AnnoLabel,js as AnnotationGroup,Wr as AnnotationHitInfo,ys as AnnotationLayer,Ys as AnnotationLine,Ks as AnnotationLineConfig,ks as AnnotationObject,Ws as AnnotationText,Vs as AnnotationTextConfig,Xs as Annotations,Cr as ArrowConfig,Rt as ArrowsMesh,Ki as AsyncDebouncer,ln as AxisMesh,dn as AxisMode,Ea as BRepAcornBody,Ca as BRepAssembly,xa as BRepBody,Sa as BRepCompoundBody,ha as BRepEdge,ga as BRepFace,ca as BRepHalfEdge,ua as BRepLoop,oa as BRepObject,ma as BRepShell,Ma as BRepShellBody,wa as BRepSolid,ya as BRepSolidBody,So as BRepTypeToSelectType,fa as BRepVertex,Lo as BRepViewObject,va as BRepWire,ba as BRepWireBody,jt as BasicMapMaterial,Gr as BodyType,Cn as BoxActionHandler,An as BoxBoundaryHelper,Un as CLIPPING_SEALING_GROUP,On as CLIPPING_TRAIT_NAME,Pn as CLIPPING_UNIVERSAL_GROUP,fn as CURSOR_TYPE,Zr as CadComponents,Qr as CadView,zt as CallbackStack,mn as CameraType,Vi as CancelError,fo as CellBasedMesh,Yo as CellBasedMeshVO,Xi as ClashDetectHelper,Ln as ClippingDetectMaterialFactory,Hn as ClippingManager,ts as ClippingManagerWithSections,Br as ClippingMethod,hr as ColorMapColoring,Kt as ColorMapExLambertMaterial,ei as ColorMapLambertMaterial,ss as ColorMapLegend,ns as ColorMapLegendType,oi as ColorMapLineMaterial,fr as ColorMapLineMeshFactory,Ti as ColorMapMaterial,Vt as ColorMapMode,ti as ColorMapPhongMaterial,jr as ColorMapTriangleMeshFactory,Kr as ContentManager,sa as Coord,_a as Coordinate,Nn as CopyWithDepthShader,as as CrossRulerManager,Ra as CurveType,zn as CustomSealingSurfaceCreateMethod,Gn as DEBOUNCE_DELAY,Ot as DEFAULT_SCENE,kn as DEFAULT_SECTION_CONFIG,bi as DagDwtMaterial,ii as DagMapLambertMaterial,yi as DagMapMaterial,xi as DagMapShader,si as DagThresholdMaterial,ni as DagWireFrameMaterial,Ci as DefaultDetectMaterialFactory,is as DefaultSealingSurfaceFactory,ai as DetectMaterial,ri as DetectMode,da as Direct,wn as Direction,Fn as DirectionMaps,$i as EffectComposerHelper,gn as EngineActionState,Qi as EngineRenderPass,za as ExtendSelMode,vi as GBufferMaterial,Qa as GeometryBuilder,Ms as GeometryFactoryBase,bs as GeometryFactoryHub,_o as GroupConfig,Ai as GroupHelper,so as HexOrder2N20Ele,ro as HexOrder2N27Ele,Ja as HexahedronEle,cn as IdentityBoxBoundaryBufferGeometry,xn as IdentityBoxBufferGeometry,yn as IdentityPlaneBufferGeometry,Fr as InitStatus,Va as InterEventType,ja as InteractiveMode,dr as InterpreterMode,rs as LegendPanel,Jo as LengthDim3D,Rr as LightingModel,Hs as Line2D,Zs as Line2DCollection,Qs as Line2DConfig,no as Line2Ele,vr as LineConfig,mr as LineMeshFactory,Sr as LineStyleConfig,pr as LineType,gr as Lines,Er as LinesCollection,Tr as LinesRayCastResultConverter,ht as LiteEvent,Ut as LookupMode,Gt as LutEx,$a as MeshElement,Mr as MeshFactoryHub,Pa as MeshType,ds as NavigatorHandler,ps as NavigatorHandler2D,go as NodeBasedMesh,zo as NodeBasedMeshVO,dt as ORTHO_CAMERA_RATING,pt as OrthographicCameraEx,on as OutlineRenderAction,mo as Owner,Oa as OwnerType,lt as PerspectiveCameraEx,oo as PlanePolygonEle,Ko as PlaneViewObject,Mn as PlyExLoader,ra as Point,Or as PointConfig,Lr as PointMeshFactory,_r as PointShape,Ar as Points,Pr as PointsCollection,Qo as PolyGeom2DVO,qo as PolyGeomVO,Za as PolyGeometry,aa as Polygon,Fi as PositionDetectHelper,eo as QuadrangleEle,Lt as ROOT_GROUP,Ui as RayCastResultConverterHub,Zo as RenderAnnoLine,jo as RenderAnnoText,La as RenderEleType,wo as RenderElement,Ro as RenderGroup,yo as RenderLineSegments,Mo as RenderMesh,bo as RenderPoints,Ts as RenderingEngine,zi as RenderingScenes,gs as RotationHandler,ka as RotationMode,fs as RulerManager,un as STATE_NONE,bn as STLExLoader,sn as ScaleRevertAction,rn as ScreenHelper,Dn as SealingSurfaceFactoryHub,Bn as SealingSurfaceGeometry,In as SealingSurfaceUpdateResult,Zn as SectionActionHandler,es as SectionSealingSurfaceGeometry,$n as SectionViews,Jn as SectionsManager,Ia as SelectEleType,Eo as SelectElement,To as SelectGroupEle,Go as SelectManager,Da as SelectMode,Co as SelectSingleEle,Vr as SelectionActionHandler,Nr as SelectionTypes,wr as ShapeConfig,cr as ShapeGroups,Ur as ShapeType,ur as ShapesBase,br as ShapesCollection,Xr as ShapesHitInfo,ki as StartTransparentAction,$o as StreamLineVO,qt as StressAttrMode,ea as SupBox,Jr as SupColor,ta as SupMat4,na as SupVec2,ia as SupVec4,$r as SupVector,Aa as SurfaceType,Dt as TARGET_GROUP,pn as TOPMOST_SCENE,ao as TetOrder2Ele,to as TetrahedronEle,Js as Text2D,tr as Text2DCollection,nr as Text2DConfig,sr as Text3D,ar as Text3DCollection,or as Text3DConfig,Gs as TextAlignment,$s as TextBase,ir as TextConfig,ws as TextMesh,xs as TextTexture,vs as TextTextureGenerator,En as TextureExLoader,Si as TextureFactory,pa as Triangle,Ir as TriangleConfig,io as TriangleEle,kr as TriangleMeshFactory,Dr as Triangles,zr as TrianglesCollection,Hr as TrianglesSealingSurfaceFactory,la as Triangulation,Wo as TriangulationVO,Fa as UpdateEventType,Xo as VectorGraphVO,Vo as View,Ba as ViewMode,Na as ViewObjType,Oo as ViewObject,Ha as ViewOrientation,Ao as ViewRenderObject,Po as ViewSelectObject,lr as VisualStyle,mi as applyWboidToMaterial,Zi as arrayEquals,It as bind,Wn as calculateSectionSquareTransformMatrix,Yn as calculateShift,vt as concatFloatAttribute,xt as concatInt16Attribute,Yi as convertProgressEvent,Ta as createBRepBody,Ds as createEngine,jn as createIdentitySquare,Vn as createIdentitySquareBoundary,nn as disposeRenderingObject,mt as edges,wt as edgesOnSurface,Ga as enSelectEvent,en as encode,$t as enumStressDistanceDeformation,Zt as enumStressShrinkMode,Qt as enumStressTransformMode,qi as equals,At as expendAttributeByIndex,Pt as expendLineToSegment,Wt as extendColorMapShaderChunk,Jt as extendStressShaderChunk,Ns as fireKeyDown,Us as fireKeyUp,zs as firePointerDown,Bs as firePointerMove,Is as firePointerUp,Fs as fireWheel,St as generateArrow,No as getMeshAllFacesSel,Bo as getMeshAllNodesSel,Uo as getMeshCurveEdgesSel,Fo as getMeshSurfFacesSel,Io as getMeshSurfNodesSel,Mt as getNormalOfSurface,bt as getUVOfSurface,yt as getVerticesOfSurface,ot as isCameraEx,Wi as isCancel,Ri as isInstanceofGroupType,_i as isInstanceofRenderingType,vn as isRaycastExtend,Li as iteratorBreakableForEach,Pi as iteratorFind,Oi as iteratorForEach,Di as iteratorToArray,Ft as move,ut as normals,ui as patchWboitToMeshBasicMaterial,di as patchWboitToMeshLambertMaterial,li as patchWboitToMeshPhongMaterial,fi as patchWboitToPointsMaterial,tn as resetInstanceGeometryMaxInstanceCount,Kn as rotateMatrix,Xt as toUniform,gt as triangles,wi as unApplyWboidToMaterial,Bt as unbind,ct as vertices,Ls as zoomCamera};