@xeokit/xeokit-sdk 2.6.87-renderers-refactor-v3 → 2.6.87-renderers-refactor-v4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/xeokit-sdk.cjs.js +19 -5
- package/dist/xeokit-sdk.es.js +19 -5
- package/dist/xeokit-sdk.es5.js +197 -195
- package/dist/xeokit-sdk.min.cjs.js +5 -5
- package/dist/xeokit-sdk.min.es.js +5 -5
- package/dist/xeokit-sdk.min.es5.js +5 -5
- package/package.json +1 -1
- package/src/viewer/scene/model/SceneModel.js +13 -1
- package/src/viewer/scene/model/layer/Layer.js +3 -1
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* xeokit-sdk v2.6.87-renderers-refactor-
|
|
3
|
-
* Commit:
|
|
4
|
-
* Built: 2025-08-
|
|
2
|
+
* xeokit-sdk v2.6.87-renderers-refactor-v4
|
|
3
|
+
* Commit: 5caed07165a5e87253766624958029a6267642df
|
|
4
|
+
* Built: 2025-08-04T16:36:05.420Z
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class n{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._parentNode=e.parentNode||document.body,this._offsetParent=this._parentNode instanceof ShadowRoot?this._parentNode.host:this._parentNode,this._eventSubs={},!1!==e.hideOnMouseDown&&(this._parentNode.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),this._parentNode.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}set items(e){this._clear(),this._itemsCfg=e||[],this._parseItems(e),this._createUI()}get items(){return this._itemsCfg}set enabled(e){(e=!!e)!==this._enabled&&(this._enabled=e,this._enabled||this.hide())}get enabled(){return this._enabled}set context(e){this._context=e}get context(){return this._context}show(e,t){this._context?this._enabled&&(this._shown||(this._hideAllMenus(),this._updateItemsTitles(),this._updateItemsEnabledStatus(),this._showMenu(this._rootMenu.id,e,t),this._updateSubMenuInfo(),this._shown=!0,this.fire("shown",{}))):console.error("ContextMenu cannot be shown without a context - set context first")}get shown(){return this._shown}hide(){this._enabled&&this._shown&&(this._hideAllMenus(),this._shown=!1,this.fire("hidden",{}))}destroy(){this._context=null,this._clear(),null!==this._id&&(t.removeItem(this._id),this._id=null)}_clear(){for(let e=0,t=this._menuList.length;e<t;e++){this._menuList[e].menuElement.remove()}this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={}}_parseItems(e){const t=e=>{const n=this._getNextId(),A=new i(n);for(let i=0,n=e.length;i<n;i++){const n=e[i],o=new s;A.groups.push(o);for(let e=0,i=n.length;e<i;e++){const i=n[e],s=i.items,a=s&&s.length>0,l=this._getNextId(),c=i.getTitle||(()=>i.title||""),h=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),f=new r(l,c,h,u,d);if(f.parentMenu=A,o.items.push(f),a){const e=t(s);f.subMenu=e,e.parentItem=f}this._itemList.push(f),this._itemMap[f.id]=f}}return this._menuList.push(A),this._menuMap[A.id]=A,A};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t<s;t++){const s=i[t].items;for(let t=0,i=s.length;t<i;t++){const i=s[t].subMenu;i&&e(i)}}};e(this._rootMenu)}_createMenuUI(e){const t=e.groups,i=[],s=document.createElement("div");if(s.classList.add("xeokit-context-menu",e.id),s.style.zIndex=3e5,s.style.position="absolute",i.push("<ul>"),t)for(let e=0,s=t.length;e<s;e++){const r=e,n=s,A=t[e].items;if(A)for(let e=0,t=A.length;e<t;e++){const s=A[e],o=s.subMenu,a=s.title||"";o?(i.push('<li id="'+s.id+'" class="xeokit-context-menu-item xeokit-context-menu-submenu">'+a+"</li>"),r===n-1||e<t-1||i.push('<li id="'+s.id+'" class="xeokit-context-menu-item-separator"></li>')):(i.push('<li id="'+s.id+'" class="xeokit-context-menu-item">'+a+"</li>"),r===n-1||e<t-1||i.push('<li id="'+s.id+'" class="xeokit-context-menu-item-separator"></li>'))}}i.push("</ul>");const r=i.join("");s.innerHTML=r,this._parentNode.appendChild(s),e.menuElement=s,s.style["border-radius"]="4px",s.style.display="none",s.style["z-index"]=3e5,s.style.background="white",s.style.border="1px solid black",s.style["box-shadow"]="0 4px 5px 0 gray",s.oncontextmenu=e=>{e.preventDefault()};const n=this;let A=null;if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e].items;if(i)for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.subMenu;t.itemElement=this._parentNode.querySelector(`#${t.id}`),t.itemElement?(t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault();const i=t.subMenu;if(!i)return void(A&&(n._hideMenu(A.id),A=null));if(A&&A.id!==i.id&&(n._hideMenu(A.id),A=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,o=s.getBoundingClientRect();r.getBoundingClientRect();const a=n._offsetParent.getBoundingClientRect(),l=200,c=o.right+l<a.right,h=o.left-l>a.left;if(c)n._showMenu(i.id,o.right+window.scrollX-5,o.top+window.scrollY-1);else if(h)n._showMenu(i.id,o.left-l+window.scrollX,o.top+window.scrollY-1);else{const e=o.left-a.left,t=a.right-o.right;t>e?n._showMenu(i.id,o.right-5-(l-t),o.top+window.scrollY-1):n._showMenu(i.id,o.left-e,o.top+window.scrollY-1)}A=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),n._context&&!1!==t.enabled&&(t.doAction&&t.doAction(n._context),this._hideOnAction?n.hide():(n._updateItemsTitles(),n._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),n._context&&!1!==t.enabled&&(t.doAction&&t.doAction(n._context),this._hideOnAction?n.hide():(n._updateItemsTitles(),n._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(n._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;e<t;e++){const t=this._itemList[e],i=t.itemElement;if(!i)continue;const s=t.getShown;if(!s||!s(this._context))continue;const r=t.getTitle(this._context);t.subMenu,i.innerText=r}}_updateItemsEnabledStatus(){if(this._context)for(let e=0,t=this._itemList.length;e<t;e++){const t=this._itemList[e],i=t.itemElement;if(!i)continue;const s=t.getEnabled;if(!s)continue;const r=t.getShown;if(!r)continue;const n=r(this._context);if(t.shown=n,!n){i.style.display="none";continue}i.style.display="";const A=s(this._context);t.enabled=A,A?i.classList.remove("disabled"):i.classList.add("disabled")}}_updateSubMenuInfo(){if(!this._context)return;let e,t,i,s,r,n;this._itemList.forEach((A=>{A.subMenu&&(e=A.itemElement,t=e.getBoundingClientRect(),i=A.subMenu.menuElement,s={visibility:i.style.visibility,display:i.style.display},i.style.display="block",i.style.visibility="hidden",n=A.subMenu.menuElement.getBoundingClientRect().width,i.style.visibility=s.visibility,i.style.display=s.display,r=t.right+n>window.innerWidth,e.setAttribute("data-submenuposition",r?"left":"right"))}))}_showMenu(e,t,i){const s=this._menuMap[e];if(!s)return void console.error("Menu not found: "+e);if(s.shown)return;const r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.shown=!0)}_hideMenu(e){const t=this._menuMap[e];if(!t)return void console.error("Menu not found: "+e);if(!t.shown)return;const i=t.menuElement;i&&(this._hideMenuElement(i),t.shown=!1)}_hideAllMenus(){for(let e=0,t=this._menuList.length;e<t;e++){const t=this._menuList[e];this._hideMenu(t.id)}}_showMenuElement(e,t,i){e.style.display="block";const s=e.offsetHeight,r=e.offsetWidth,n=this._offsetParent.getBoundingClientRect(),A=this._offsetParent===window.document.body&&0===n.bottom?window.innerHeight:n.bottom+window.scrollY,o=n.right+window.scrollX;i+s>A&&(i=A-s),t+r>o&&(t=o-r),e.style.left=t-n.left-window.scrollX+"px",e.style.top=i-n.top-window.scrollY+"px"}_hideMenuElement(e){e.style.display="none"}}class A{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this._lensParams={canvasSize:300,cursorBorder:2,cursorSize:10},this._lensCursorDiv.style.borderRadius="50%",this._lensCursorDiv.style.width=this._lensParams.cursorSize+"px",this._lensCursorDiv.style.height=this._lensParams.cursorSize+"px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainerId=t.containerId||"xeokit-lens",this._lensContainer.setAttribute("id",this._lensContainerId),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width=this._lensParams.canvasSize+"px",this._lensContainer.style.height=this._lensParams.canvasSize+"px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.id=`${this._lensContainerId}-canvas`,this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width=this._lensParams.canvasSize+"px",this._lensCanvas.style.height=this._lensParams.canvasSize+"px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensContainer.appendChild(this._lensCursorDiv),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=t.lensPosToggle||!0,this._lensPosToggleAmount=t.lensPosToggleAmount||85,this._lensPosMarginLeft=t.lensPosMarginLeft||85,this._lensPosMarginTop=t.lensPosMarginTop||25,this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this.snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]<e.right&&this._canvasPos[0]>e.left&&this._canvasPos[1]<e.bottom&&this._canvasPos[1]>e.top;this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-this._lensPosToggleAmount+"px":this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=this._lensParams.canvasSize/2-this._lensParams.cursorSize/2-this._lensParams.cursorBorder,n=this._snappedCanvasPos?this._snappedCanvasPos[0]-this._canvasPos[0]:0,A=this._snappedCanvasPos?this._snappedCanvasPos[1]-this._canvasPos[1]:0;this._lensCursorDiv.style.left=`${r+n*this._zoomLevel}px`,this._lensCursorDiv.style.top=`${r+A*this._zoomLevel}px`}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e;const[t,i]=e?["greenyellow","green"]:["pink","red"];this._lensCursorDiv.style.background=t,this._lensCursorDiv.style.border=this._lensParams.cursorBorder+"px solid "+i}get snapped(){return this._snapped}_updateActiveVisible(){this._lensContainer.style.visibility=this._active&&this._visible?"visible":"hidden",this.update()}set active(e){this._active=e,this._updateActiveVisible()}get active(){return this._active}set visible(e){this._visible=e,this._updateActiveVisible()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}let o=!0,a=o?Float64Array:Float32Array;const l=new a(3),c=new a(16),h=new a(16),u=new a(4),d={setDoublePrecisionEnabled(e){o=e,a=o?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new a(e||2),vec3:e=>new a(e||3),vec4:e=>new a(e||4),mat3:e=>new a(e||9),mat3ToMat4:(e,t=new a(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new a(e||16),mat4ToMat3:(e,t=new a(9))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t),doublesToFloats(e,t,i){const s=new a(2);for(let r=0,n=e.length;r<n;r++)d.splitDouble(e[r],s),t[r]=s[0],i[r]=s[1]},splitDouble(e,t){const i=a.from([e])[0],s=e-i;t[0]=i,t[1]=s},createUUID:(()=>{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],compareVec4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new a(e[0]);for(let i=1;i<e.length;i++)t[0]+=e[i][0],t[1]+=e[i][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],n=t[0],A=t[1],o=t[2];return[s*o-r*A,r*n-i*o,i*A-s*n,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],n=e[2],A=t[0],o=t[1],a=t[2];return i[0]=r*a-n*o,i[1]=n*A-s*a,i[2]=s*o-r*A,i},sqLenVec4:e=>d.dotVec4(e,e),lenVec4:e=>Math.sqrt(d.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>d.dotVec3(e,e),sqLenVec2:e=>d.dotVec2(e,e),lenVec3:e=>Math.sqrt(d.sqLenVec3(e)),distVec3:(()=>{const e=new a(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new a(2);return(t,i)=>d.lenVec2(d.subVec2(t,i,e))})(),rcpVec3:(e,t)=>d.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/d.lenVec4(e);return d.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/d.lenVec3(e);return d.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/d.lenVec2(e);return d.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=d.dotVec3(e,t)/Math.sqrt(d.sqLenVec3(e)*d.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new a(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=d.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=d.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=d.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i<s;i++)t[i]=e(t[i]);return t}})(),xyzArrayToObject:e=>({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||d.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>d.m4s(0),setMat4ToOnes:()=>d.m4s(1),diagonalMat4v:e=>new a([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>d.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>d.diagonalMat4c(e,e,e,e),identityMat4:(e=new a(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new a(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>d.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],n=e[2],A=e[3],o=e[4],a=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],f=e[11],p=e[12],g=e[13],m=e[14],_=e[15],b=t[0],y=t[1],w=t[2],v=t[3],B=t[4],C=t[5],M=t[6],E=t[7],F=t[8],U=t[9],x=t[10],I=t[11],T=t[12],P=t[13],S=t[14],D=t[15];return i[0]=b*s+y*o+w*h+v*p,i[1]=b*r+y*a+w*u+v*g,i[2]=b*n+y*l+w*d+v*m,i[3]=b*A+y*c+w*f+v*_,i[4]=B*s+C*o+M*h+E*p,i[5]=B*r+C*a+M*u+E*g,i[6]=B*n+C*l+M*d+E*m,i[7]=B*A+C*c+M*f+E*_,i[8]=F*s+U*o+x*h+I*p,i[9]=F*r+U*a+x*u+I*g,i[10]=F*n+U*l+x*d+I*m,i[11]=F*A+U*c+x*f+I*_,i[12]=T*s+P*o+S*h+D*p,i[13]=T*r+P*a+S*u+D*g,i[14]=T*n+P*l+S*d+D*m,i[15]=T*A+P*c+S*f+D*_,i},mulMat3(e,t,i){i||(i=new a(9));const s=e[0],r=e[3],n=e[6],A=e[1],o=e[4],l=e[7],c=e[2],h=e[5],u=e[8],d=t[0],f=t[3],p=t[6],g=t[1],m=t[4],_=t[7],b=t[2],y=t[5],w=t[8];return i[0]=s*d+r*g+n*b,i[3]=s*f+r*m+n*y,i[6]=s*p+r*_+n*w,i[1]=A*d+o*g+l*b,i[4]=A*f+o*m+l*y,i[7]=A*p+o*_+l*w,i[2]=c*d+h*g+u*b,i[5]=c*f+h*m+u*y,i[8]=c*p+h*_+u*w,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=d.vec4()){const s=t[0],r=t[1],n=t[2],A=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*A,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*A,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*A,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*A,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],n=e[13],A=e[12],o=e[9];if(!t||e===t){const t=e[1],a=e[2],l=e[3],c=e[6],h=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=A,e[4]=t,e[6]=o,e[7]=n,e[8]=a,e[9]=c,e[11]=s,e[12]=l,e[13]=h,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=A,t[4]=e[1],t[5]=e[5],t[6]=o,t[7]=n,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],A=e[5],o=e[6],a=e[7],l=e[8],c=e[9],h=e[10],u=e[11],d=e[12],f=e[13],p=e[14],g=e[15];return d*c*o*r-l*f*o*r-d*A*h*r+n*f*h*r+l*A*p*r-n*c*p*r-d*c*s*a+l*f*s*a+d*i*h*a-t*f*h*a-l*i*p*a+t*c*p*a+d*A*s*u-n*f*s*u-d*i*o*u+t*f*o*u+n*i*p*u-t*A*p*u-l*A*s*g+n*c*s*g+l*i*o*g-t*c*o*g-n*i*h*g+t*A*h*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],n=e[3],A=e[4],o=e[5],a=e[6],l=e[7],c=e[8],h=e[9],u=e[10],d=e[11],f=e[12],p=e[13],g=e[14],m=e[15],_=i*o-s*A,b=i*a-r*A,y=i*l-n*A,w=s*a-r*o,v=s*l-n*o,B=r*l-n*a,C=c*p-h*f,M=c*g-u*f,E=c*m-d*f,F=h*g-u*p,U=h*m-d*p,x=u*m-d*g,I=1/(_*x-b*U+y*F+w*E-v*M+B*C);return t[0]=(o*x-a*U+l*F)*I,t[1]=(-s*x+r*U-n*F)*I,t[2]=(p*B-g*v+m*w)*I,t[3]=(-h*B+u*v-d*w)*I,t[4]=(-A*x+a*E-l*M)*I,t[5]=(i*x-r*E+n*M)*I,t[6]=(-f*B+g*y-m*b)*I,t[7]=(c*B-u*y+d*b)*I,t[8]=(A*U-o*E+l*C)*I,t[9]=(-i*U+s*E-n*C)*I,t[10]=(f*v-p*y+m*_)*I,t[11]=(-c*v+h*y-d*_)*I,t[12]=(-A*F+o*M-a*C)*I,t[13]=(i*F-s*M+r*C)*I,t[14]=(-f*w+p*b-g*_)*I,t[15]=(c*w-h*b+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||d.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||d.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new a(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.translationMat4v(e,r))})(),translationMat4s:(e,t)=>d.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>d.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const n=s[7];s[4]+=n*e,s[5]+=n*t,s[6]+=n*i;const A=s[11];s[8]+=A*e,s[9]+=A*t,s[10]+=A*i;const o=s[15];return s[12]+=o*e,s[13]+=o*t,s[14]+=o*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=d.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),n=Math.cos(e),A=1-n,o=s[0],a=s[1],l=s[2];let c,h,u,f,p,g;return c=o*a,h=a*l,u=l*o,f=o*r,p=a*r,g=l*r,(i=i||d.mat4())[0]=A*o*o+n,i[1]=A*c+g,i[2]=A*u-p,i[3]=0,i[4]=A*c-g,i[5]=A*a*a+n,i[6]=A*h+f,i[7]=0,i[8]=A*u+p,i[9]=A*h-f,i[10]=A*l*l+n,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>d.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=d.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=d.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new a(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>d.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=d.mat4()){const s=e[0],r=e[1],n=e[2],A=e[3],o=s+s,a=r+r,l=n+n,c=s*o,h=s*a,u=s*l,f=r*a,p=r*l,g=n*l,m=A*o,_=A*a,b=A*l;return i[0]=1-(f+g),i[1]=h+b,i[2]=u-_,i[3]=0,i[4]=h-b,i[5]=1-(c+g),i[6]=p+m,i[7]=0,i[8]=u+_,i[9]=p-m,i[10]=1-(c+f),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=d.vec4()){const s=d.clamp,r=e[0],n=e[4],A=e[8],o=e[1],a=e[5],l=e[9],c=e[2],h=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(A,-1,1)),Math.abs(A)<.99999?(i[0]=Math.atan2(-l,u),i[2]=Math.atan2(-n,r)):(i[0]=Math.atan2(h,a),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(l,-1,1)),Math.abs(l)<.99999?(i[1]=Math.atan2(A,u),i[2]=Math.atan2(o,a)):(i[1]=Math.atan2(-c,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(h,-1,1)),Math.abs(h)<.99999?(i[1]=Math.atan2(-c,u),i[2]=Math.atan2(-n,a)):(i[1]=0,i[2]=Math.atan2(o,r))):"ZYX"===t?(i[1]=Math.asin(-s(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(h,u),i[2]=Math.atan2(o,r)):(i[0]=0,i[2]=Math.atan2(-n,a))):"YZX"===t?(i[2]=Math.asin(s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-l,a),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(A,u))):"XZY"===t&&(i[2]=Math.asin(-s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(h,a),i[1]=Math.atan2(A,r)):(i[0]=Math.atan2(-l,u),i[1]=0)),i[0]*=d.RADTODEG,i[1]*=d.RADTODEG,i[2]*=d.RADTODEG,i},composeMat4:(e,t,i,s=d.mat4())=>(d.quaternionToRotationMat4(t,s),d.scaleMat4v(i,s),d.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new a(3),t=new a(16);return function(i,s,r,n){e[0]=i[0],e[1]=i[1],e[2]=i[2];let A=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const o=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const a=d.lenVec3(e);d.determinantMat4(i)<0&&(A=-A),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const l=1/A,c=1/o,h=1/a;return t[0]*=l,t[1]*=l,t[2]*=l,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=h,t[9]*=h,t[10]*=h,d.mat4ToQuaternion(t,r),n[0]=A,n[1]=o,n[2]=a,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=d.mat4());const r=e[0],n=e[1],A=e[2],o=i[0],a=i[1],l=i[2],c=t[0],h=t[1],u=t[2];if(r===c&&n===h&&A===u)return d.identityMat4();let f,p,g,m,_,b,y,w,v,B;return f=r-c,p=n-h,g=A-u,B=1/Math.sqrt(f*f+p*p+g*g),f*=B,p*=B,g*=B,m=a*g-l*p,_=l*f-o*g,b=o*p-a*f,B=Math.sqrt(m*m+_*_+b*b),B?(B=1/B,m*=B,_*=B,b*=B):(m=0,_=0,b=0),y=p*b-g*_,w=g*m-f*b,v=f*_-p*m,B=Math.sqrt(y*y+w*w+v*v),B?(B=1/B,y*=B,w*=B,v*=B):(y=0,w=0,v=0),s[0]=m,s[1]=y,s[2]=f,s[3]=0,s[4]=_,s[5]=w,s[6]=p,s[7]=0,s[8]=b,s[9]=v,s[10]=g,s[11]=0,s[12]=-(m*r+_*n+b*A),s[13]=-(y*r+w*n+v*A),s[14]=-(f*r+p*n+g*A),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,n,A,o,a)=>d.lookAtMat4v([e,t,i],[s,r,n],[A,o,a],[]),orthoMat4c(e,t,i,s,r,n,A){A||(A=d.mat4());const o=t-e,a=s-i,l=n-r;return A[0]=2/o,A[1]=0,A[2]=0,A[3]=0,A[4]=0,A[5]=2/a,A[6]=0,A[7]=0,A[8]=0,A[9]=0,A[10]=-2/l,A[11]=0,A[12]=-(e+t)/o,A[13]=-(s+i)/a,A[14]=-(n+r)/l,A[15]=1,A},frustumMat4v(e,t,i){i||(i=d.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];d.addVec4(r,s,c),d.subVec4(r,s,h);const n=2*s[2],A=h[0],o=h[1],a=h[2];return i[0]=n/A,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=n/o,i[6]=0,i[7]=0,i[8]=c[0]/A,i[9]=c[1]/o,i[10]=-c[2]/a,i[11]=-1,i[12]=0,i[13]=0,i[14]=-n*r[2]/a,i[15]=0,i},frustumMat4(e,t,i,s,r,n,A){A||(A=d.mat4());const o=t-e,a=s-i,l=n-r;return A[0]=2*r/o,A[1]=0,A[2]=0,A[3]=0,A[4]=0,A[5]=2*r/a,A[6]=0,A[7]=0,A[8]=(t+e)/o,A[9]=(s+i)/a,A[10]=-(n+r)/l,A[11]=-1,A[12]=0,A[13]=0,A[14]=-n*r*2/l,A[15]=0,A},perspectiveMat4(e,t,i,s,r){const n=[],A=[];return n[2]=i,A[2]=s,A[1]=n[2]*Math.tan(e/2),n[1]=-A[1],A[0]=A[1]*t,n[0]=-A[0],d.frustumMat4v(n,A,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=d.vec3()){const s=t[0],r=t[1],n=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12],i[1]=e[1]*s+e[5]*r+e[9]*n+e[13],i[2]=e[2]*s+e[6]*r+e[10]*n+e[14],i},transformPoint4:(e,t,i=d.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let n,A,o,a;const l=e[0],c=e[1],h=e[2],u=e[3],d=e[4],f=e[5],p=e[6],g=e[7],m=e[8],_=e[9],b=e[10],y=e[11],w=e[12],v=e[13],B=e[14],C=e[15];let M;for(let e=0;e<r;++e)a=t[e],n=a[0],A=a[1],o=a[2],M=s[e]||(s[e]=[0,0,0]),M[0]=l*n+d*A+m*o+w,M[1]=c*n+f*A+_*o+v,M[2]=h*n+p*A+b*o+B,M[3]=u*n+g*A+y*o+C;return s.length=r,s},transformPositions3(e,t,i=t){let s;const r=t.length;let n,A,o;const a=e[0],l=e[1],c=e[2];e[3];const h=e[4],u=e[5],d=e[6];e[7];const f=e[8],p=e[9],g=e[10];e[11];const m=e[12],_=e[13],b=e[14];for(e[15],s=0;s<r;s+=3)n=t[s+0],A=t[s+1],o=t[s+2],i[s+0]=a*n+h*A+f*o+m,i[s+1]=l*n+u*A+p*o+_,i[s+2]=c*n+d*A+g*o+b;return i},transformPositions4(e,t,i=t){let s;const r=t.length;let n,A,o;const a=e[0],l=e[1],c=e[2],h=e[3],u=e[4],d=e[5],f=e[6],p=e[7],g=e[8],m=e[9],_=e[10],b=e[11],y=e[12],w=e[13],v=e[14],B=e[15];for(s=0;s<r;s+=4)n=t[s+0],A=t[s+1],o=t[s+2],i[s+0]=a*n+u*A+g*o+y,i[s+1]=l*n+d*A+m*o+w,i[s+2]=c*n+f*A+_*o+v,i[s+3]=h*n+p*A+b*o+B;return i},transformVec3(e,t,i){const s=t[0],r=t[1],n=t[2];return(i=i||this.vec3())[0]=e[0]*s+e[4]*r+e[8]*n,i[1]=e[1]*s+e[5]*r+e[9]*n,i[2]=e[2]*s+e[6]*r+e[10]*n,i},transformVec4(e,t,i){const s=t[0],r=t[1],n=t[2],A=t[3];return(i=i||d.vec4())[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*A,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*A,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*A,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*A,i},rotateVec2(e,t,i,s=e){const r=Math.cos(i),n=Math.sin(i),A=e[0]-t[0],o=e[1]-t[1];return s[0]=A*r-o*n+t[0],s[1]=A*n+o*r+t[1],e},rotateVec3X(e,t,i,s){const r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0],n[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),n[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Y(e,t,i,s){const r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),n[1]=r[1],n[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Z(e,t,i,s){const r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),n[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),n[2]=r[2],s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},projectVec4(e,t){const i=1/e[3];return(t=t||d.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(()=>{const e=new a(16),t=new a(16),i=new a(16);return function(s,r,n,A){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(n,t),i),s,A)}})(),lerpVec3(e,t,i,s,r,n){const A=n||d.vec3(),o=(e-t)/(i-t);return A[0]=s[0]+o*(r[0]-s[0]),A[1]=s[1]+o*(r[1]-s[1]),A[2]=s[2]+o*(r[2]-s[2]),A},lerpMat4(e,t,i,s,r,n){const A=n||d.mat4(),o=(e-t)/(i-t);return A[0]=s[0]+o*(r[0]-s[0]),A[1]=s[1]+o*(r[1]-s[1]),A[2]=s[2]+o*(r[2]-s[2]),A[3]=s[3]+o*(r[3]-s[3]),A[4]=s[4]+o*(r[4]-s[4]),A[5]=s[5]+o*(r[5]-s[5]),A[6]=s[6]+o*(r[6]-s[6]),A[7]=s[7]+o*(r[7]-s[7]),A[8]=s[8]+o*(r[8]-s[8]),A[9]=s[9]+o*(r[9]-s[9]),A[10]=s[10]+o*(r[10]-s[10]),A[11]=s[11]+o*(r[11]-s[11]),A[12]=s[12]+o*(r[12]-s[12]),A[13]=s[13]+o*(r[13]-s[13]),A[14]=s[14]+o*(r[14]-s[14]),A[15]=s[15]+o*(r[15]-s[15]),A},flatten(e){const t=[];let i,s,r,n,A;for(i=0,s=e.length;i<s;i++)for(A=e[i],r=0,n=A.length;r<n;r++)t.push(A[r]);return t},identityQuaternion:(e=d.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=d.vec4()){const s=e[0]*d.DEGTORAD/2,r=e[1]*d.DEGTORAD/2,n=e[2]*d.DEGTORAD/2,A=Math.cos(s),o=Math.cos(r),a=Math.cos(n),l=Math.sin(s),c=Math.sin(r),h=Math.sin(n);return"XYZ"===t?(i[0]=l*o*a+A*c*h,i[1]=A*c*a-l*o*h,i[2]=A*o*h+l*c*a,i[3]=A*o*a-l*c*h):"YXZ"===t?(i[0]=l*o*a+A*c*h,i[1]=A*c*a-l*o*h,i[2]=A*o*h-l*c*a,i[3]=A*o*a+l*c*h):"ZXY"===t?(i[0]=l*o*a-A*c*h,i[1]=A*c*a+l*o*h,i[2]=A*o*h+l*c*a,i[3]=A*o*a-l*c*h):"ZYX"===t?(i[0]=l*o*a-A*c*h,i[1]=A*c*a+l*o*h,i[2]=A*o*h-l*c*a,i[3]=A*o*a+l*c*h):"YZX"===t?(i[0]=l*o*a+A*c*h,i[1]=A*c*a+l*o*h,i[2]=A*o*h-l*c*a,i[3]=A*o*a-l*c*h):"XZY"===t&&(i[0]=l*o*a-A*c*h,i[1]=A*c*a-l*o*h,i[2]=A*o*h+l*c*a,i[3]=A*o*a+l*c*h),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],n=e[1],A=e[5],o=e[9],a=e[2],l=e[6],c=e[10];let h;const u=i+A+c;return u>0?(h=.5/Math.sqrt(u+1),t[3]=.25/h,t[0]=(l-o)*h,t[1]=(r-a)*h,t[2]=(n-s)*h):i>A&&i>c?(h=2*Math.sqrt(1+i-A-c),t[3]=(l-o)/h,t[0]=.25*h,t[1]=(s+n)/h,t[2]=(r+a)/h):A>c?(h=2*Math.sqrt(1+A-i-c),t[3]=(r-a)/h,t[0]=(s+n)/h,t[1]=.25*h,t[2]=(o+l)/h):(h=2*Math.sqrt(1+c-i-A),t[3]=(n-s)/h,t[0]=(r+a)/h,t[1]=(o+l)/h,t[2]=.25*h),t},vec3PairToQuaternion(e,t,i=d.vec4()){const s=Math.sqrt(d.dotVec3(e,e)*d.dotVec3(t,t));let r=s+d.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):d.cross3Vec3(e,t,i),i[3]=r,d.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=d.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new a(16);return(t,i,s)=>(s=s||d.vec3(),d.quaternionToRotationMat4(t,e),d.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=d.vec4()){const s=e[0],r=e[1],n=e[2],A=e[3],o=t[0],a=t[1],l=t[2],c=t[3];return i[0]=A*o+s*c+r*l-n*a,i[1]=A*a+r*c+n*o-s*l,i[2]=A*l+n*c+s*a-r*o,i[3]=A*c-s*o-r*a-n*l,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],n=t[2],A=e[0],o=e[1],a=e[2],l=e[3],c=l*s+o*n-a*r,h=l*r+a*s-A*n,u=l*n+A*r-o*s,f=-A*s-o*r-a*n;return i[0]=c*l+f*-A+h*-a-u*-o,i[1]=h*l+f*-o+u*-A-c*-a,i[2]=u*l+f*-a+c*-o-h*-A,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],n=e[3],A=2*i,o=2*s,a=2*r,l=A*n,c=o*n,h=a*n,u=A*i,f=o*i,p=a*i,g=o*s,m=a*s,_=a*r;return t[0]=1-(g+_),t[1]=f+h,t[2]=p-c,t[4]=f-h,t[5]=1-(u+_),t[6]=m+l,t[8]=p+c,t[9]=m-l,t[10]=1-(u+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],n=e[3],A=i+i,o=s+s,a=r+r,l=i*A,c=i*o,h=i*a,u=s*o,d=s*a,f=r*a,p=n*A,g=n*o,m=n*a;return t[0]=1-(u+f),t[4]=c-m,t[8]=h+g,t[1]=c+m,t[5]=1-(l+f),t[9]=d-p,t[2]=h-g,t[6]=d+p,t[10]=1-(l+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=d.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>d.normalizeQuaternion(d.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=d.vec4()){const i=(e=d.normalizeQuaternion(e,u))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new a(e||6),AABB2:e=>new a(e||4),OBB3:e=>new a(e||32),OBB2:e=>new a(e||16),Sphere3:(e,t,i,s)=>new a([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let n,A,o;const a=e[0],l=e[1],c=e[2],h=e[3],u=e[4],d=e[5],f=e[6],p=e[7],g=e[8],m=e[9],_=e[10],b=e[11],y=e[12],w=e[13],v=e[14],B=e[15];for(s=0;s<r;s+=4)n=t[s+0],A=t[s+1],o=t[s+2],i[s+0]=a*n+u*A+g*o+y,i[s+1]=l*n+d*A+m*o+w,i[s+2]=c*n+f*A+_*o+v,i[s+3]=h*n+p*A+b*o+B;return i},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:(()=>{const e=new a(3),t=new a(3),i=new a(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],d.subVec3(t,e,i),Math.abs(d.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new a(3),t=new a(3),i=new a(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const n=d.subVec3(t,e,i),A=r[0]-s[0],o=s[3]-r[0],a=r[1]-s[1],l=s[4]-r[1],c=r[2]-s[2],h=s[5]-r[2];return n[0]+=A>o?A:o,n[1]+=a>l?a:l,n[2]+=c>h?c:h,Math.abs(d.lenVec3(n))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||d.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||d.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=d.AABB3())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MAX_DOUBLE,e[3]=d.MIN_DOUBLE,e[4]=d.MIN_DOUBLE,e[5]=d.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=d.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new a(3);return(t,i,s)=>{i=i||d.AABB3();let r,n,A,o=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,c=d.MIN_DOUBLE,h=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,f=t.length;i<f;i+=3)s?(e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2],d.decompressPosition(e,s,e),r=e[0],n=e[1],A=e[2]):(r=t[i+0],n=t[i+1],A=t[i+2]),r<o&&(o=r),n<a&&(a=n),A<l&&(l=A),r>c&&(c=r),n>h&&(h=n),A>u&&(u=A);return i[0]=o,i[1]=a,i[2]=l,i[3]=c,i[4]=h,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,n=d.MAX_DOUBLE,A=d.MAX_DOUBLE,o=d.MAX_DOUBLE,a=d.MIN_DOUBLE,l=d.MIN_DOUBLE,c=d.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t+=4)i=e[t+0],s=e[t+1],r=e[t+2],i<n&&(n=i),s<A&&(A=s),r<o&&(o=r),i>a&&(a=i),s>l&&(l=s),r>c&&(c=r);return t[0]=n,t[1]=A,t[2]=o,t[3]=a,t[4]=l,t[5]=c,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,n=d.MAX_DOUBLE,A=d.MAX_DOUBLE,o=d.MAX_DOUBLE,a=d.MIN_DOUBLE,l=d.MIN_DOUBLE,c=d.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t++)i=e[t][0],s=e[t][1],r=e[t][2],i<n&&(n=i),s<A&&(A=s),r<o&&(o=r),i>a&&(a=i),s>l&&(l=s),r>c&&(c=r);return t[0]=n,t[1]=A,t[2]=o,t[3]=a,t[4]=l,t[5]=c,t},points3ToSphere3:(()=>{const e=new a(3);return(t,i)=>{i=i||d.vec4();let s,r=0,n=0,A=0;const o=t.length;for(s=0;s<o;s++)r+=t[s][0],n+=t[s][1],A+=t[s][2];i[0]=r/o,i[1]=n/o,i[2]=A/o;let a,l=0;for(s=0;s<o;s++)a=Math.abs(d.lenVec3(d.subVec3(t[s],i,e))),a>l&&(l=a);return i[3]=l,i}})(),positions3ToSphere3:(()=>{const e=new a(3),t=new a(3);return(i,s)=>{s=s||d.vec4();let r,n=0,A=0,o=0;const a=i.length;let l=0;for(r=0;r<a;r+=3)n+=i[r],A+=i[r+1],o+=i[r+2];const c=a/3;let h;for(s[0]=n/c,s[1]=A/c,s[2]=o/c,r=0;r<a;r+=3)e[0]=i[r],e[1]=i[r+1],e[2]=i[r+2],h=Math.abs(d.lenVec3(d.subVec3(e,s,t))),h>l&&(l=h);return s[3]=l,s}})(),OBB3ToSphere3:(()=>{const e=new a(3),t=new a(3);return(i,s)=>{s=s||d.vec4();let r,n=0,A=0,o=0;const a=i.length,l=a/4;for(r=0;r<a;r+=4)n+=i[r+0],A+=i[r+1],o+=i[r+2];s[0]=n/l,s[1]=A/l,s[2]=o/l;let c,h=0;for(r=0;r<a;r+=4)e[0]=i[r+0],e[1]=i[r+1],e[2]=i[r+2],c=Math.abs(d.lenVec3(d.subVec3(e,s,t))),c>h&&(h=c);return s[3]=h,s}})(),getSphere3Center:(e,t=d.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=d.vec3()){let i=0,s=0,r=0;for(var n=0,A=e.length;n<A;n+=3)i+=e[n+0],s+=e[n+1],r+=e[n+2];const o=e.length/3;return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},expandAABB3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e),expandAABB3Point3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e),expandAABB3Points3(e,t){for(var i,s,r,n=0,A=t.length;n<A;n+=3)i=t[n],s=t[n+1],r=t[n+2],e[0]>i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]<i&&(e[3]=i),e[4]<s&&(e[4]=s),e[5]<r&&(e[5]=r);return e},collapseAABB2:(e=d.AABB2())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MIN_DOUBLE,e[3]=d.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2],point3AABB3AbsoluteIntersect:(e,t)=>e[0]<=t[0]&&e[3]>=t[0]&&e[1]<=t[1]&&e[4]>=t[1]&&e[2]<=t[2]&&e[5]>=t[2],planeAABB3Intersect(e,t,i){let s,r;e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=d.AABB2()){let i,s,r,n,A=d.MAX_DOUBLE,o=d.MAX_DOUBLE,a=d.MIN_DOUBLE,l=d.MIN_DOUBLE;for(let t=0,c=e.length;t<c;t+=4)i=e[t+0],s=e[t+1],r=e[t+3]||1,n=1/r,i*=n,s*=n,i<A&&(A=i),s<o&&(o=s),i>a&&(a=i),s>l&&(l=s);return t[0]=A,t[1]=o,t[2]=a,t[3]=l,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e),expandAABB2Point2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e),AABB2ToCanvas(e,t,i,s=e){const r=.5*(e[0]+1),n=.5*(e[1]+1),A=.5*(e[2]+1),o=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(o*i),s[2]=Math.floor(A*t),s[3]=i-Math.floor(n*i),s},tangentQuadraticBezier:(e,t,i,s)=>2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const n=.5*(i-e),A=.5*(s-t),o=r*r;return(2*t-2*i+n+A)*(r*o)+(-3*t+3*i-2*n-A)*o+n*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=d.vec3()){const r=t[0]-e[0],n=t[1]-e[1],A=t[2]-e[2],o=i[0]-e[0],a=i[1]-e[1],l=i[2]-e[2],c=n*l-A*a,h=A*o-r*l,u=r*a-n*o,f=Math.sqrt(c*c+h*h+u*u);return 0===f?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/f,s[1]=h/f,s[2]=u/f),s},rayTriangleIntersect:(()=>{const e=new a(3),t=new a(3),i=new a(3),s=new a(3),r=new a(3);return(n,A,o,a,l,c)=>{c=c||d.vec3();const h=d.subVec3(a,o,e),u=d.subVec3(l,o,t),f=d.cross3Vec3(A,u,i),p=d.dotVec3(h,f);if(p<1e-6)return null;const g=d.subVec3(n,o,s),m=d.dotVec3(g,f);if(m<0||m>p)return null;const _=d.cross3Vec3(g,h,r),b=d.dotVec3(A,_);if(b<0||m+b>p)return null;const y=d.dotVec3(u,_)/p;return c[0]=n[0]+y*A[0],c[1]=n[1]+y*A[1],c[2]=n[2]+y*A[2],c}})(),rayPlaneIntersect:(()=>{const e=new a(3),t=new a(3),i=new a(3),s=new a(3);return(r,n,A,o,a,l)=>{l=l||d.vec3(),n=d.normalizeVec3(n,e);const c=d.subVec3(o,A,t),h=d.subVec3(a,A,i),u=d.cross3Vec3(c,h,s);d.normalizeVec3(u,u);const f=-d.dotVec3(A,u),p=-(d.dotVec3(r,u)+f)/d.dotVec3(n,u);return l[0]=r[0]+p*n[0],l[1]=r[1]+p*n[1],l[2]=r[2]+p*n[2],l}})(),cartesianToBarycentric:(()=>{const e=new a(3),t=new a(3),i=new a(3);return(s,r,n,A,o)=>{const a=d.subVec3(A,r,e),l=d.subVec3(n,r,t),c=d.subVec3(s,r,i),h=d.dotVec3(a,a),u=d.dotVec3(a,l),f=d.dotVec3(a,c),p=d.dotVec3(l,l),g=d.dotVec3(l,c),m=h*p-u*u;if(0===m)return null;const _=1/m,b=(p*f-u*g)*_,y=(h*g-u*f)*_;return o[0]=1-b-y,o[1]=y,o[2]=b,o}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=d.vec3()){const n=e[0],A=e[1],o=e[2];return r[0]=t[0]*n+i[0]*A+s[0]*o,r[1]=t[1]*n+i[1]*A+s[1]*o,r[2]=t[2]*n+i[2]*A+s[2]*o,r},mergeVertices(e,t,i,s){const r={},n=[],A=[],o=t?[]:null,a=i?[]:null,l=[];let c,h,u,d;const f=1e4;let p,g,m=0;for(p=0,g=e.length;p<g;p+=3)c=e[p],h=e[p+1],u=e[p+2],d=`${Math.round(c*f)}_${Math.round(h*f)}_${Math.round(u*f)}`,void 0===r[d]&&(r[d]=A.length/3,A.push(c),A.push(h),A.push(u),t&&(o.push(t[p]),o.push(t[p+1]),o.push(t[p+2])),i&&(a.push(i[m]),a.push(i[m+1]))),n[p/3]=r[d],m+=2;for(p=0,g=s.length;p<g;p++)l[p]=n[s[p]];const _={positions:A,indices:l};return o&&(_.normals=o),a&&(_.uv=a),_},buildNormals:(()=>{const e=new a(3),t=new a(3),i=new a(3),s=new a(3),r=new a(3),n=new a(3);return(A,o,a)=>{let l,c;const h=new Array(A.length/3);let u,f,p,g,m,_,b;for(l=0,c=o.length;l<c;l+=3){u=o[l],f=o[l+1],p=o[l+2],e[0]=A[3*u],e[1]=A[3*u+1],e[2]=A[3*u+2],t[0]=A[3*f],t[1]=A[3*f+1],t[2]=A[3*f+2],i[0]=A[3*p],i[1]=A[3*p+1],i[2]=A[3*p+2],d.subVec3(t,e,s),d.subVec3(i,e,r);const a=d.vec3();d.normalizeVec3(d.cross3Vec3(s,r,n),a),h[u]||(h[u]=[]),h[f]||(h[f]=[]),h[p]||(h[p]=[]),h[u].push(a),h[f].push(a),h[p].push(a)}for(a=a&&a.length===A.length?a:new Float32Array(A.length),l=0,c=h.length;l<c;l++){g=h[l].length,m=0,_=0,b=0;for(let e=0;e<g;e++)m+=h[l][e][0],_+=h[l][e][1],b+=h[l][e][2];a[3*l]=m/g,a[3*l+1]=_/g,a[3*l+2]=b/g}return a}})(),buildTangents:(()=>{const e=new a(3),t=new a(3),i=new a(3),s=new a(3),r=new a(3),n=new a(3),A=new a(3);return(o,a,l)=>{const c=new Float32Array(o.length);for(let h=0;h<a.length;h+=3){let u=a[h];const f=o.subarray(3*u,3*u+3),p=l.subarray(2*u,2*u+2);u=a[h+1];const g=o.subarray(3*u,3*u+3),m=l.subarray(2*u,2*u+2);u=a[h+2];const _=o.subarray(3*u,3*u+3),b=l.subarray(2*u,2*u+2),y=d.subVec3(g,f,e),w=d.subVec3(_,f,t),v=d.subVec2(m,p,i),B=d.subVec2(b,p,s),C=1/(v[0]*B[1]-v[1]*B[0]),M=d.mulVec3Scalar(d.subVec3(d.mulVec3Scalar(y,B[1],r),d.mulVec3Scalar(w,v[1],n),A),C,n);let E;for(let e=0;e<3;e++)E=3*a[h+e],c[E]+=M[0],c[E+1]+=M[1],c[E+2]+=M[2]}return c}})(),buildPickTriangles(e,t,i){const s=t.length,r=i?new Uint16Array(9*s):new Float32Array(9*s),n=new Uint8Array(12*s);let A,o,a,l,c,h,u=0,d=0,f=0;for(let i=0;i<s;i+=3)h=u>>24&255,c=u>>16&255,l=u>>8&255,a=255&u,o=t[i],A=3*o,r[d++]=e[A],r[d++]=e[A+1],r[d++]=e[A+2],n[f++]=a,n[f++]=l,n[f++]=c,n[f++]=h,o=t[i+1],A=3*o,r[d++]=e[A],r[d++]=e[A+1],r[d++]=e[A+2],n[f++]=a,n[f++]=l,n[f++]=c,n[f++]=h,o=t[i+2],A=3*o,r[d++]=e[A],r[d++]=e[A+1],r[d++]=e[A+2],n[f++]=a,n[f++]=l,n[f++]=c,n[f++]=h,u++;return{positions:r,colors:n}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},n=[],A={};let o,a,l,c,h;const u=1e4;let f,p,g,m,_,b;for(p=0,m=e.length;p<m;p+=3){f=p/3,a=e[p],l=e[p+1],c=e[p+2],h=`${Math.round(a*u)}_${Math.round(l*u)}_${Math.round(c*u)}`,void 0===r[h]?r[h]=[f]:r[h].push(f);const i=d.normalizeVec3([t[p],t[p+1],t[p+2]]);n[f]=i,o=d.vec4([i[0],i[1],i[2],1]),A[f]=o}for(h in r)if(r.hasOwnProperty(h)){const e=r[h],t=e.length;for(p=0;p<t;p++){const i=e[p];for(o=A[i],g=0;g<t;g++){if(p===g)continue;const t=e[g];_=n[i],b=n[t];Math.abs(d.angleVec3(_,b)/d.DEGTORAD)<s&&(o[0]+=b[0],o[1]+=b[1],o[2]+=b[2],o[3]+=1)}}}for(p=0,m=t.length;p<m;p+=3)o=A[p/3],t[p+0]=o[0]/o[3],t[p+1]=o[1]/o[3],t[p+2]=o[2]/o[3]},transformRay:(()=>{const e=new a(4),t=new a(4);return(i,s,r,n,A)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),n[0]=t[0],n[1]=t[1],n[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),A[0]=t[0],A[1]=t[1],A[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new a(16),t=new a(4),i=new a(4),s=(t,i,s,r,n)=>{n[0]=t,n[1]=i,n[2]=s,n[3]=1,d.transformVec4(e,n,n),r||d.mulVec4Scalar(n,1/n[3])};return(r,n,A,o,a,l,c)=>{const h="ortho"===o;d.mulMat4(A,n,e),d.inverseMat4(e,e);const u=2*a[0]/r.clientWidth-1,f=1-2*a[1]/r.clientHeight;s(u,f,-1,h,t),s(u,f,1,h,i),l[0]=t[0],l[1]=t[1],l[2]=t[2],d.subVec3(i,t,c),d.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new a(3),t=new a(3);return(i,s,r,n,A,o,a,l)=>{d.canvasPosToWorldRay(i,s,r,n,o,e,t),d.worldRayToLocalRay(A,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new a(16),t=new a(4),i=new a(4);return(s,r,n,A,o)=>{const a=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(a,t,i),A[0]=i[0],A[1]=i[1],A[2]=i[2],d.transformVec3(a,n,o)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,n){const A=new a(6),o={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:A};let l,c;for(A[0]=A[1]=A[2]=Number.POSITIVE_INFINITY,A[3]=A[4]=A[5]=Number.NEGATIVE_INFINITY,l=0,c=i.length;l<c;++l){var h=3*i[l];for(let e=0;e<3;++e){const t=3*s[h+e];r[t]<A[0]&&(A[0]=r[t]),r[t]>A[3]&&(A[3]=r[t]),r[t+1]<A[1]&&(A[1]=r[t+1]),r[t+1]>A[4]&&(A[4]=r[t+1]),r[t+2]<A[2]&&(A[2]=r[t+2]),r[t+2]>A[5]&&(A[5]=r[t+2])}}if(i.length<20||n>10)return o.triangles=i,o.leaf=!0,o;e[0]=A[3]-A[0],e[1]=A[4]-A[1],e[2]=A[5]-A[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),o.splitDim=u;const d=(A[u]+A[u+3])/2,f=new Array(i.length);let p=0;const g=new Array(i.length);let m=0;for(l=0,c=i.length;l<c;++l){const e=s[h=3*i[l]],t=3*s[h+1],n=3*s[h+2];r[3*e+u]<=d||r[t+u]<=d||r[n+u]<=d?f[p++]=i[l]:g[m++]=i[l]}return f.length=p,g.length=m,o.left=t(f,s,r,n+1),o.right=t(g,s,r,n+1),o}return(e,i)=>{const s=e.length/3,r=new Array(s);for(let e=0;e<s;++e)r[e]=e;return t(r,e,i,0)}})(),decompressPosition(e,t,i){(i=i||e)[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressUV(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},octDecodeVec2(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],n=e[i+1];r=(2*r+1)/255,n=(2*n+1)/255;const A=1-Math.abs(r)-Math.abs(n);A<0&&(r=(1-Math.abs(n))*(r>=0?1:-1),n=(1-Math.abs(r))*(n>=0?1:-1));const o=Math.sqrt(r*r+n*n+A*A);t[s+0]=r/o,t[s+1]=n/o,t[s+2]=A/o,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let n=0;const A=new Uint16Array(3),o=new Uint16Array(3),a=new Uint16Array(3),l=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),f=d.vec3(),p=d.vec3(),g=d.vec3();return function(m,_,b,y){!function(r,n){const A={};let o,a,l,c;const h=Math.pow(10,4);let u,d,f=0;for(u=0,d=r.length;u<d;u+=3)o=r[u],a=r[u+1],l=r[u+2],c=Math.round(o*h)+"_"+Math.round(a*h)+"_"+Math.round(l*h),void 0===A[c]&&(A[c]=f/3,e[f++]=o,e[f++]=a,e[f++]=l),t[u/3]=A[c];for(u=0,d=n.length;u<d;u++)s[u]=t[n[u]],i[s[u]]=n[u]}(m,_),function(t,i){n=0;for(let m=0,_=t;m<_;m+=3){const t=3*s[m],_=3*s[m+1],b=3*s[m+2];i?(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],o[0]=e[_],o[1]=e[_+1],o[2]=e[_+2],a[0]=e[b],a[1]=e[b+1],a[2]=e[b+2],d.decompressPosition(A,i,l),d.decompressPosition(o,i,c),d.decompressPosition(a,i,h)):(l[0]=e[t],l[1]=e[t+1],l[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],h[0]=e[b],h[1]=e[b+1],h[2]=e[b+2]),d.subVec3(h,c,u),d.subVec3(l,c,f),d.cross3Vec3(u,f,p),d.normalizeVec3(p,g);const y=r[n]||(r[n]={normal:d.vec3()});y.normal[0]=g[0],y.normal[1]=g[1],y.normal[2]=g[2],n++}}(_.length,b);const w=[],v=Math.cos(d.DEGTORAD*y),B={};let C,M,E,F,U,x,I,T,P,S,D,k=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)C=s[e+i],M=s[e+(i+1)%3],E=Math.min(C,M),F=Math.max(C,M),U=E+","+F,void 0===B[U]?B[U]={index1:E,index2:F,face1:t,face2:void 0}:B[U].face2=t}for(U in B)x=B[U],void 0!==x.face2&&(I=r[x.face1].normal,T=r[x.face2].normal,P=d.dotVec3(I,T),P>v)||(S=i[x.index1],D=i[x.index2],(!k&&S>65535||D>65535)&&(k=!0),w.push(S),w.push(D));return k?new Uint32Array(w):new Uint16Array(w)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,n=i.length;r<n;r+=s){if(l[0]=i[r+0]-e[0],l[1]=i[r+1]-e[1],l[2]=i[r+2]-e[2],l[0]*t[0]+l[1]*t[1]+l[2]*t[2]<0)return!0}return!1};const f=new Float32Array(3);class p{constructor(e){if(!e)throw"Parameter expected: cfg";if(!e.viewer)throw"Parameter expected: cfg.viewer";this.viewer=e.viewer,this._maxTreeDepth=e.maxTreeDepth||15,this._root=null,this._needsRebuild=!0,this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&d.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&d.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;f[0]=r[3]-r[0],f[1]=r[4]-r[1],f[2]=r[5]-r[2];let n=0;if(f[1]>f[n]&&(n=1),f[2]>f[n]&&(n=2),!e.left){const A=r.slice();if(A[n+3]=(r[n]+r[n+3])/2,e.left={aabb:A},d.containsAABB3(A,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const A=r.slice();if(A[n]=(r[n]+r[n+3])/2,e.right={aabb:A},d.containsAABB3(A,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}class g{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const m={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var _=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r<s;++r)t.push(r);return String.fromCharCode.apply(null,t)})).join("");function b(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return _.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}const y=function(){for(var e={},t=window.location.search.substring(1).split("&"),i=0;i<t.length;i++){var s=t[i].split("=");if(void 0===e[s[0]])e[s[0]]=decodeURIComponent(s[1]);else if("string"==typeof e[s[0]]){var r=[e[s[0]],decodeURIComponent(s[1])];e[s[0]]=r}else e[s[0]].push(decodeURIComponent(s[1]))}return e}();const w={xmlToJson:function e(t,i){if(t.nodeType===t.TEXT_NODE){var s=t.nodeValue;if(null===s.match(/^\s+$/))return s}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var r={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var n=0;n<t.attributes.length;n++){var A=t.attributes[n];r[i[A.nodeName]||A.nodeName]=A.nodeValue}for(var o=0;o<t.childNodes.length;o++){(n=e(t.childNodes[o],i))&&r.children.push(n)}return r}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return b(t[0],2)+[1,4,7,10,13].map((function(e){return b((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var i=[],s=function(e){e.type===t&&i.push(e),(e.children||[]).forEach((function(e){s(e)}))};return s(e),i},timeout:function(e){return new Promise((function(t,i){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,i){var s=new XMLHttpRequest;s.open(e.method||"GET",e.url,!0),s.onload=function(e){4===s.readyState&&(200===s.status?t(s.responseXML):i(s.statusText))},s.send(null)}))},loadJSON:function(e,t,i){var s=e=>{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var n=r[3];n=window.decodeURIComponent(n),e&&(n=window.atob(n));try{const e=new ArrayBuffer(n.length),i=new Uint8Array(e);for(var A=0;A<n.length;A++)i[A]=n.charCodeAt(A);I.scheduleTask((()=>{t(e)}))}catch(e){I.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:y,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return w.isString(e)||w.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(w.isNumeric(e)||w.isString(e)?`${e}`:e.id)===(w.isNumeric(t)||w.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return w.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return w.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,n=s.length;r<n;r++){s[r].parent=i.id,e(s[r])}i.children=[]}(e),t}},v={},B=new e,C=new g,M={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},E=[];let F,U=0,x=0;const I=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(I.scenes[e.id])return void console.error(`[ERROR] Scene ${w.inQuotes(e.id)} already exists`)}else e.id=B.addItem({});I.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;v[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},m.components.scenes++,e.once("destroyed",(()=>{B.removeItem(e.id),delete I.scenes[e.id],delete v[e.id],m.components.scenes--}))},this.clear=function(){let e;for(const t in I.scenes)I.scenes.hasOwnProperty(t)&&(e=I.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete I.scenes[e.id]))},this.scheduleTask=function(e,t=null){C.push(e),C.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;C.length>0&&(e<0||s<e);)t=C.shift(),i=C.shift(),i?t.call(i):t(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return C.length}},T=function(){let e=Date.now();if(F=e-U,U>0&&F>0){var t=1e3/F;x+=t,E.push(t),E.length>=30&&(x-=E.shift()),m.frame.fps=Math.round(x/E.length)}for(let e in I.scenes)I.scenes[e].compile();S(e),U=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{T()}),100);const P=function(){let e=Date.now();if(F=e-U,U>0&&F>0){var t=1e3/F;x+=t,E.push(t),E.length>=30&&(x-=E.shift()),m.frame.fps=Math.round(x/E.length)}S(e),function(e){for(var t in M.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];M.sceneId=t,M.startTime=i.startTime,M.deltaTime=null!=M.prevTime?M.time-M.prevTime:0,i.fire("tick",M,!0)}M.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,n,A;for(A in e)e.hasOwnProperty(A)&&(i=e[A],s=v[A],s||(s=v[A]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),n=i.ticksPerRender,s.ticksPerRender!==n&&(s.ticksPerRender=n,s.renderCountdown=n),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=n))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(T):requestAnimationFrame(P)};function S(e){const t=I.runTasks(e+10),i=I.getNumTasks();m.frame.tasksRun=t,m.frame.tasksScheduled=i,m.frame.tasksBudget=10}P();class D{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof D))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const n=this._subIdMap.addItem();r[n]={callback:i,scope:s||this},this._subIdEvents[n]=t;const A=this._events[t];return void 0!==A&&i.call(s||this,A),n}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+w.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,n=e.type,A=e.on,o=!1!==e.recompiles;if(i&&(w.isNumeric(i)||w.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+w.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[n];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+w.inQuotes(i.id));if(n&&!i.isType(n))return void this.error("Expected a "+n+" type or subtype: "+i.type+" "+w.inQuotes(i.id))}this._attachments||(this._attachments={});const a=this._attached[t];let l,c,h;if(a){if(i&&a.id===i.id)return;const e=this._attachments[a.id];for(l=e.subs,c=0,h=l.length;c<h;c++)a.off(l[c]);delete this._attached[t],delete this._attachments[a.id];const s=e.params.onDetached;s&&(w.isFunction(s)?s(a):s.scope?s.callback.call(s.scope,a):s.callback(a)),e.managingLifecycle&&a.destroy()}if(i){const s={params:e,component:i,subs:[],managingLifecycle:false};s.subs.push(i.once("destroyed",(function(){s.params.component=null,this._attach(s.params)}),this)),o&&s.subs.push(i.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=i,this._attachments[i.id]=s;const r=e.onAttached;if(r&&(w.isFunction(r)?r(i):r.scope?r.callback.call(r.scope,i):r.callback(i)),A){let e,t,r,n;for(e in A)if(A.hasOwnProperty(e)){if(t=A[e],w.isFunction(t)?(r=t,n=null):(r=t.callback,n=t.scope),!r)continue;s.subs.push(i.on(e,r,n))}}}return o&&this.fire("dirty",this),this.fire(t,i),i}_checkComponent(e,t){if(!t.isComponent){if(!w.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}_checkComponent2(e,t){if(!t.isComponent){if(!w.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(t.scene.id===this.scene.id){for(var i=0,s=e.length;i<s;i++)if(e[i]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}_own(e){this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(()=>{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():I.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){I.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,n;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,n=s.length;r<n;r++)i.off(s[r]);t.managingLifecycle&&i.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(i=this._ownedComponents[e],i.destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}const k=d.vec3(),Q=d.vec3(),R=d.mat4();class O{constructor(){this.normal=d.vec3(),this.offset=0,this.testVertex=d.vec3()}set(e,t,i,s){const r=1/Math.sqrt(e*e+t*t+i*i);this.normal[0]=e*r,this.normal[1]=t*r,this.normal[2]=i*r,this.offset=s*r,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class V{constructor(){this.planes=[new O,new O,new O,new O,new O,new O]}}function L(e,t,i){const s=d.mulMat4(i,t,R),r=s[0],n=s[1],A=s[2],o=s[3],a=s[4],l=s[5],c=s[6],h=s[7],u=s[8],f=s[9],p=s[10],g=s[11],m=s[12],_=s[13],b=s[14],y=s[15];e.planes[0].set(o-r,h-a,g-u,y-m),e.planes[1].set(o+r,h+a,g+u,y+m),e.planes[2].set(o-n,h-l,g-f,y-_),e.planes[3].set(o+n,h+l,g+f,y+_),e.planes[4].set(o-A,h-c,g-p,y-b),e.planes[5].set(o+A,h+c,g+p,y+b)}function H(e,t){let i=V.INSIDE;const s=k,r=Q;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const n=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*n[s.testVertex[0]][0]+s.normal[1]*n[s.testVertex[1]][1]+s.normal[2]*n[s.testVertex[2]][2]+s.offset<0)return V.OUTSIDE;s.normal[0]*n[1-s.testVertex[0]][0]+s.normal[1]*n[1-s.testVertex[1]][1]+s.normal[2]*n[1-s.testVertex[2]][2]+s.offset<0&&(i=V.INTERSECT)}return i}V.INSIDE=0,V.INTERSECT=1,V.OUTSIDE=2;class N extends D{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=d.vec2(),this._canvasMarqueeCorner2=d.vec2(),this._canvasMarquee=d.AABB2(),this._marqueeFrustum=new V,this._marqueeFrustumProjMat=d.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=V.INTERSECT)=>{if(s===V.INTERSECT&&(s=H(this._marqueeFrustum,i.aabb)),s!==V.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i<s;i++){const s=t[i];if(!s.visible)continue;const r=s.aabb;if(this._pickMode===N.PICK_MODE_INSIDE){H(this._marqueeFrustum,r)===V.INSIDE&&e.push(s.id)}else{H(this._marqueeFrustum,r)!==V.OUTSIDE&&e.push(s.id)}}}i.left&&t(i.left,s),i.right&&t(i.right,s)}};return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,n=2/t,A=2/i,o=e.clientHeight/e.clientWidth,a=(this._canvasMarquee[0]-s)*n-1,l=(this._canvasMarquee[2]-s)*n-1,c=-(this._canvasMarquee[3]-r)*A+1,h=-(this._canvasMarquee[1]-r)*A+1,u=this.viewer.scene.camera.frustum.near*(17*o);d.frustumMat4(a,l,c*o,h*o,u,1e4,this._marqueeFrustumProjMat),L(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class G extends D{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,n,A,o,a,l,c=!1,h=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(l=setTimeout((function(){const n=t.viewer.scene.input;n.keyDown[n.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,o=e.offsetX,t.setMarqueeCorner1([s,r]),c=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),h=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!c&&!u)return;if(0!==e.button)return;clearTimeout(l),n=e.pageX,A=e.pageY;const i=Math.abs(n-s),o=Math.abs(A-r);c=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||o>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(l),c&&(t.setMarqueeVisible(!1),c=!1,h=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&h&&(clearTimeout(l),c&&(n=e.pageX,A=e.pageY,a=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([n,A]),t.setPickMode(o<a?N.PICK_MODE_INSIDE:N.PICK_MODE_INTERSECTS)))}))}setActive(e){this._active!==e&&(this._active=e,this.fire("active",this._active))}getActive(){return this._active}destroy(){}}class j{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==t.active,this._visible=!1,this._running=!1,this._destroyed=!1}start(e){if(this._destroyed)return;this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius+"px";const t=this._circleMaxRadius;let i;const s=e=>{if(!this._running)return;i||(i=e);const r=e-i,n=Math.min(r/300,1),A=t+(2-t)*n;this._circleRadius=A,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",n<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}class W{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=z(e,i);return s?t?X(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=z(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=X(r,[t]),i&&(r=X(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const n=this._events[t];return void 0!==n&&i(n),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function z(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e<t;e++){s=s[i[e]]}return s}function X(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}class K extends D{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),n=this.getPoint(s),A=d.subVec3(n,r,[]);return d.normalizeVec3(A,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),n=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),n+=d.lenVec3(d.subVec3(t,r,[])),s.push(n),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,n=s.length;i=t||e*s[n-1];for(var A,o=0,a=n-1;o<=a;)if((A=s[r=Math.floor(o+(a-o)/2)]-i)<0)o=r+1;else{if(!(A>0)){a=r;break}a=r-1}if(s[r=a]===i)return r/(n-1);var l=s[r];return(r+(i-l)/(s[r+1]-l))/(n-1)}}class Z extends K{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,n=t[0===s?s:s-1],A=t[s],o=t[s>t.length-2?t.length-1:s+1],a=t[s>t.length-3?t.length-1:s+2],l=d.vec3();return l[0]=d.catmullRomInterpolate(n[0],A[0],o[0],a[0],r),l[1]=d.catmullRomInterpolate(n[1],A[1],o[1],a[1],r),l[2]=d.catmullRomInterpolate(n[2],A[2],o[2],a[2],r),l}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const J=d.vec3();class Y extends D{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new Z(this),this._lookCurve=new Z(this),this._upCurve=new Z(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i<s;i++)t=e[i],this.addFrame(t.t||0,t.eye,t.look,t.up)}loadFrame(e){const t=this.scene.camera;e=(e/=this._frames[this._frames.length-1].t-this._frames[0].t)<0?0:e>1?1:e,t.eye=this._eyeCurve.getPoint(e,J),t.look=this._lookCurve.getPoint(e,J),t.up=this._upCurve.getPoint(e,J)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=d.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,n=this._frames.length;e<n;e++){var r=d.lenVec3(d.subVec3(this._frames[e].eye,this._frames[e-1].eye,t));s[e]=r,i+=r}for(let t=1,r=this._frames.length;t<r;t++){const r=s[t]/i*e;this._frames[t].t=this._frames[t-1].t+r}}clearFrames(){this._frames=[],this._eyeCurve.points=[],this._lookCurve.points=[],this._upCurve.points=[]}}const $=d.vec3(),q=d.vec3(),ee=d.vec3(),te=d.vec3(),ie=d.vec3();class se extends D{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=d.vec3(),this._eye1=d.vec3(),this._up1=d.vec3(),this._look2=d.vec3(),this._eye2=d.vec3(),this._up2=d.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let n,A,o,a,l;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)n=e.aabb;else if(6===e.length)n=e;else if(e.eye&&e.look||e.up)A=e.eye,o=e.look,a=e.up;else if(e.eye)A=e.eye;else if(e.look)o=e.look;else{let s=e;if((w.isNumeric(s)||w.isString(s))&&(l=s,s=this.scene.components[l],!s))return this.error("Component not found: "+w.inQuotes(l)),void(t&&(i?t.call(i):t()));r||(n=s.aabb||this.scene.aabb)}const c=e.poi;if(n){if(n[3]<n[0]||n[4]<n[1]||n[5]<n[2])return;if(n[3]===n[0]&&n[4]===n[1]&&n[5]===n[2])return;n=n.slice();const t=d.getAABB3Center(n);this._look2=c||t;const i=d.subVec3(this._eye1,this._look1,$),s=d.normalizeVec3(i),r=c?d.getAABB3DiagPoint(n,c):d.getAABB3Diag(n),A=e.fitFOV||this._fitFOV,o=Math.abs(r/Math.tan(A*d.DEGTORAD));this._orthoScale2=1.1*r,this._eye2[0]=this._look2[0]+s[0]*o,this._eye2[1]=this._look2[1]+s[1]*o,this._eye2[2]=this._look2[2]+s[2]*o,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(A||o||a)&&(this._flyingEyeLookUp=!!A&&!!o&&!!a,this._flyingEye=!!A&&!o,this._flyingLook=!!o&&!A,A&&(this._eye2[0]=A[0],this._eye2[1]=A[1],this._eye2[2]=A[2]),o&&(this._look2[0]=o[0],this._look2[1]=o[1],this._look2[2]=o[2]),a&&(this._up2[0]=a[0],this._up2[1]=a[1],this._up2[2]=a[2]));r?("ortho"===e.projection&&"ortho"!==s.projection&&(this._projection2="ortho",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.ortho.matrix.slice(),s.projection="customProjection"),"perspective"===e.projection&&"perspective"!==s.projection&&(this._projection2="perspective",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.perspective.matrix.slice(),s.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(Number.isFinite(e.duration)?1e3*e.duration:this._duration),this._flying=!0,I.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var i,s,r,n,A;if(e.aabb)i=e.aabb;else if(6===e.length)i=e;else if(e.eye||e.look||e.up)r=e.eye,n=e.look,A=e.up;else{let t=e;if((w.isNumeric(t)||w.isString(t))&&(s=t,t=this.scene.components[s],!t))return void this.error("Component not found: "+w.inQuotes(s));i=t.aabb||this.scene.aabb}const o=e.poi;if(i){if(i[3]<=i[0]||i[4]<=i[1]||i[5]<=i[2])return;var a=o?d.getAABB3DiagPoint(i,o):d.getAABB3Diag(i);let s;n=o||d.getAABB3Center(i,n),this._trail?d.subVec3(t.look,n,ie):d.subVec3(t.eye,t.look,ie),d.normalizeVec3(ie);s=(void 0!==e.fit?e.fit:this._fit)?Math.abs(a/Math.tan((e.fitFOV||this._fitFOV)*d.DEGTORAD)):d.lenVec3(d.subVec3(t.eye,t.look,$)),d.mulVec3Scalar(ie,s),t.eye=d.addVec3(n,ie,$),t.look=n,this.scene.camera.ortho.scale=1.1*a}else(r||n||A)&&(r&&(t.eye=r),n&&(t.look=n),A&&(t.up=A));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const i=this.easing?se._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(d.subVec3(s.eye,s.look,ie),s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,ee),s.look=d.subVec3(ee,ie,q)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,q),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,te)):this._flyingEyeLookUp&&(s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,ee),s.look=d.lerpVec3(i,0,1,this._look1,this._look2,q),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,te)),this._projection2){const t="ortho"===this._projection2?se._easeOutExpo(e,0,1,1):se._easeInCubic(e,0,1,1);s.customProjection.matrix=d.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();I.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=Number.isFinite(e)?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class re extends D{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new se(this),this._t=0,this.state=re.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case re.SCRUBBING:return;case re.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=re.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case re.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=re.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=re.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=re.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=re.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=re.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=re.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=re.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}re.STOPPED=0,re.SCRUBBING=1,re.PLAYING=2,re.PLAYING_TO=3;class ne extends D{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),m.memory.meshes++}destroy(){super.destroy(),m.memory.meshes--}}const Ae=new e({});class oe{constructor(e){this.id=Ae.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){Ae.removeItem(this.id)}}class ae{constructor(e,t,i,s,r,n,A,o,a){switch(this._gl=e,this.type=t,this.allocated=!1,i.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=n,this.length=0,this.dataLength=s,this.numItems=0,this.itemSize=r,this.normalized=!!A,this.stride=o||0,this.offset=a||0,this._allocate(i)}_allocate(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}bindAtLocation(e){this.bind(),this._gl.vertexAttribPointer(e,this.itemSize,this.itemType,this.normalized,0,0)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}var le=function(){const e=[],t=[],i=[],s=[],r=[];let n=0;const A=new Uint16Array(3),o=new Uint16Array(3),a=new Uint16Array(3),l=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),f=d.vec3(),p=d.vec3(),g=d.vec3();return function(m,_,b,y){!function(r,n){const A={};let o,a,l,c;const h=Math.pow(10,4);let u,d,f=0;for(u=0,d=r.length;u<d;u+=3)o=r[u],a=r[u+1],l=r[u+2],c=Math.round(o*h)+"_"+Math.round(a*h)+"_"+Math.round(l*h),void 0===A[c]&&(A[c]=f/3,e[f++]=o,e[f++]=a,e[f++]=l),t[u/3]=A[c];for(u=0,d=n.length;u<d;u++)s[u]=t[n[u]],i[s[u]]=n[u]}(m,_),function(t,i){n=0;for(let m=0,_=t;m<_;m+=3){const t=3*s[m],_=3*s[m+1],b=3*s[m+2];i?(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],o[0]=e[_],o[1]=e[_+1],o[2]=e[_+2],a[0]=e[b],a[1]=e[b+1],a[2]=e[b+2],d.decompressPosition(A,i,l),d.decompressPosition(o,i,c),d.decompressPosition(a,i,h)):(l[0]=e[t],l[1]=e[t+1],l[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],h[0]=e[b],h[1]=e[b+1],h[2]=e[b+2]),d.subVec3(h,c,u),d.subVec3(l,c,f),d.cross3Vec3(u,f,p),d.normalizeVec3(p,g);const y=r[n]||(r[n]={normal:d.vec3()});y.normal[0]=g[0],y.normal[1]=g[1],y.normal[2]=g[2],n++}}(_.length,b);const w=[],v=Math.cos(d.DEGTORAD*y),B={};let C,M,E,F,U,x,I,T,P,S,D,k=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)C=s[e+i],M=s[e+(i+1)%3],E=Math.min(C,M),F=Math.max(C,M),U=E+","+F,void 0===B[U]?B[U]={index1:E,index2:F,face1:t,face2:void 0}:B[U].face2=t}for(U in B)x=B[U],void 0!==x.face2&&(I=r[x.face1].normal,T=r[x.face2].normal,P=d.dotVec3(I,T),P>v)||(S=i[x.index1],D=i[x.index2],(!k&&S>65535||D>65535)&&(k=!0),w.push(S),w.push(D));return k?new Uint32Array(w):new Uint16Array(w)}}();const ce=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],n=i[1],A=i[2],o=i[3]-r,a=i[4]-n,l=i[5]-A,c=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([o/c,a/c,l/c],t),d.mulMat4(e,t,s),s}}();var he=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const n=new Uint16Array(i.length),A=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let o;for(o=0;o<i.length;o+=3)n[o+0]=Math.max(0,Math.min(65535,Math.floor((i[o+0]-s[0])*A[0]))),n[o+1]=Math.max(0,Math.min(65535,Math.floor((i[o+1]-s[1])*A[1]))),n[o+2]=Math.max(0,Math.min(65535,Math.floor((i[o+2]-s[2])*A[2])));d.identityMat4(e),d.translationMat4v(s,e),d.identityMat4(t),d.scalingMat4v([(r[0]-s[0])/65535,(r[1]-s[1])/65535,(r[2]-s[2])/65535],t);return{quantized:n,decodeMatrix:d.mulMat4(e,t,d.identityMat4())}}}();var ue=function(){const e=d.mat3(),t=d.mat3();return function(i,s,r){const n=new Uint16Array(i.length),A=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);let o;for(o=0;o<i.length;o+=2)n[o+0]=Math.max(0,Math.min(65535,Math.floor((i[o+0]-s[0])*A[0]))),n[o+1]=Math.max(0,Math.min(65535,Math.floor((i[o+1]-s[1])*A[1])));d.identityMat3(e),d.translationMat3v(s,e),d.identityMat3(t),d.scalingMat3v([(r[0]-s[0])/65535,(r[1]-s[1])/65535],t);return{quantized:n,decodeMatrix:d.mulMat3(e,t,d.identityMat3())}}}();function de(e,t,i,s){let r=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),n=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){let e=(1-Math.abs(n))*(r>=0?1:-1),t=(1-Math.abs(r))*(n>=0?1:-1);r=e,n=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*n+(n<0?-1:0))])}function fe(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function pe(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const ge={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=3)for(r=0;r<3;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},createPositionsDecodeMatrix:ce,compressPositions:he,compressPosition:function(e,t,i){const s=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);i[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*s[0]))),i[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*s[1]))),i[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*s[2])))},decompressPositions:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressPosition:function(e,t,i){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i},decompressAABB:function(e,t,i=e){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){const t=new Float32Array(2),i=new Float32Array(2);let s,r;for(s=0;s<2;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=2)for(r=0;r<2;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},compressUVs:ue,decompressUVs:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let i,s,r,n,A;for(let o=0;o<e.length;o+=3)r=i=de(e,o,"floor","floor"),s=fe(i),n=A=pe(e,o,s),i=de(e,o,"ceil","floor"),s=fe(i),n=pe(e,o,s),n>A&&(r=i,A=n),i=de(e,o,"floor","ceil"),s=fe(i),n=pe(e,o,s),n>A&&(r=i,A=n),i=de(e,o,"ceil","ceil"),s=fe(i),n=pe(e,o,s),n>A&&(r=i,A=n),t[o]=r[0],t[o+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],n=e[i+1];r=(2*r+1)/255,n=(2*n+1)/255;const A=1-Math.abs(r)-Math.abs(n);A<0&&(r=(1-Math.abs(n))*(r>=0?1:-1),n=(1-Math.abs(r))*(n>=0?1:-1));const o=Math.sqrt(r*r+n*n+A*A);t[s+0]=r/o,t[s+1]=n/o,t[s+2]=A/o,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t}},me=m.memory,_e=d.AABB3();class be extends ne{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new oe({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=ge.getPositionsBounds(t.positions),s=ge.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=ge.getUVBounds(t.uv),s=ge.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);if(t.normals&&(this._state.compressGeometry?i.normals=ge.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),me.meshes++,i.indices&&(i.indicesBuf=new ae(s,s.ELEMENT_ARRAY_BUFFER,i.indices,i.indices.length,1,s.STATIC_DRAW),me.indices+=i.indicesBuf.numItems),i.positions&&(i.positionsBuf=new ae(s,s.ARRAY_BUFFER,i.positions,i.positions.length,3,s.STATIC_DRAW),me.positions+=i.positionsBuf.numItems),i.normals){let e=i.compressGeometry;i.normalsBuf=new ae(s,s.ARRAY_BUFFER,i.normals,i.normals.length,3,s.STATIC_DRAW,e),me.normals+=i.normalsBuf.numItems}i.colors&&(i.colorsBuf=new ae(s,s.ARRAY_BUFFER,i.colors,i.colors.length,4,s.STATIC_DRAW),me.colors+=i.colorsBuf.numItems),i.uv&&(i.uvBuf=new ae(s,s.ARRAY_BUFFER,i.uv,i.uv.length,2,s.STATIC_DRAW),me.uvs+=i.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=le(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ae(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),me.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=d.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new ae(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ae(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),me.positions+=this._pickTrianglePositionsBuf.numItems,me.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),ge.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=ge.getPositionsBounds(e),s=ge.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),ge.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),ge.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=d.AABB3()),d.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=d.OBB3()),d.positions3ToAABB3(this._state.positions,_e,this._state.positionsDecodeMatrix),d.AABB3ToOBB3(_e,this._obb),this._obbDirty=!1),this._obb}_getMetrics(){if(!("_metrics"in this))switch(this._state.primitiveName){case"solid":case"surface":case"triangles":{const e=this._state.indices,t=this._state.positions,i=(i,s)=>{const r=3*e[i];for(let e=0;e<3;++e)s[e]=t[r+e];return s},s=[d.vec3(),d.vec3(),d.vec3(),d.vec3()];let r=0;const n=d.vec3([0,0,0]);for(let t=0;t<e.length;t+=3){const e=i(t,s[0]),A=i(t+1,s[1]),o=i(t+2,s[2]);d.addVec3(e,A,s[3]),d.addVec3(o,s[3],s[3]);const a=d.lenVec3(d.cross3Vec3(d.subVec3(A,e,s[1]),d.subVec3(o,e,s[2]),s[0]))/2;r+=a,d.mulVec3Scalar(s[3],a,s[3]),d.addVec3(n,s[3],n)}this._metrics={surfaceArea:r,centroid:d.mulVec3Scalar(n,1/r/3,n)};break}default:this._metrics={surfaceArea:0}}return this._metrics}get surfaceArea(){return this._getMetrics().surfaceArea}get centroid(){return this._getMetrics().centroid}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),me.meshes--}}const ye=m.memory,we=d.AABB3();class ve extends ne{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new oe({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=d.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=ge.getPositionsBounds(t.positions),n=ge.compressPositions(t.positions,e.min,e.max);r=n.quantized,i.positionsDecodeMatrix=n.decodeMatrix,i.positionsBuf=new ae(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),ye.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,we,i.positionsDecodeMatrix),d.AABB3ToOBB3(we,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new ae(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),ye.colors+=i.colorsBuf.numItems}if(t.uv){const e=ge.getUVBounds(t.uv),r=ge.compressUVs(t.uv,e.min,e.max),n=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new ae(s,s.ARRAY_BUFFER,n,n.length,2,s.STATIC_DRAW),ye.uvs+=i.uvBuf.numItems}if(t.normals){const e=ge.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new ae(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),ye.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new ae(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),ye.indices+=i.indicesBuf.numItems;const n=le(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ae(s,s.ELEMENT_ARRAY_BUFFER,n,n.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),ye.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),ye.meshes--}}var Be={};function Ce(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,w.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var n=Be.parse.from3DS(e).edit.objects[0].mesh,A=n.vertices,o=n.uvt,a=n.indices;r.processes--,i(w.apply(t,{primitive:"triangles",positions:A,normals:null,uv:o,indices:a}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function Me(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,w.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var n=Be.parse.fromOBJ(e),A=Be.edit.unwrap(n.i_verts,n.c_verts,3),o=Be.edit.unwrap(n.i_norms,n.c_norms,3),a=Be.edit.unwrap(n.i_uvt,n.c_uvt,2),l=new Int32Array(n.i_verts.length),c=0;c<n.i_verts.length;c++)l[c]=c;r.processes--,i(w.apply(t,{primitive:"triangles",positions:A,normals:o.length>0?o:null,autoNormals:0===o.length,uv:a,indices:l}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function Ee(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,n=r?r[0]:0,A=r?r[1]:0,o=r?r[2]:0,a=-t+n,l=-i+A,c=-s+o,h=t+n,u=i+A,d=s+o;return w.apply(e,{positions:[h,u,d,a,u,d,a,l,d,h,l,d,h,u,d,h,l,d,h,l,c,h,u,c,h,u,d,h,u,c,a,u,c,a,u,d,a,u,d,a,u,c,a,l,c,a,l,d,a,l,c,h,l,c,h,l,d,a,l,d,h,l,c,a,l,c,a,u,c,h,u,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}function Fe(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,n=r?r[0]:0,A=r?r[1]:0,o=r?r[2]:0,a=-t+n,l=-i+A,c=-s+o,h=t+n,u=i+A,d=s+o;return w.apply(e,{primitive:"lines",positions:[a,l,c,a,l,d,a,u,c,a,u,d,h,l,c,h,l,d,h,u,c,h,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Ue(e={}){return Fe({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function xe(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let n=e.heightSegments||1;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n<1&&(n=1);const A=!!e.openEnded;let o=e.center;const a=o?o[0]:0,l=o?o[1]:0,c=o?o[2]:0,h=s/2,u=s/n,d=2*Math.PI/r,f=1/r,p=(t-i)/n,g=[],m=[],_=[],b=[];let y,v,B,C,M,E,F,U,x,I,T;const P=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=n;y++)for(M=t-y*p,E=h-y*u,v=0;v<=r;v++)B=Math.sin(v*d),C=Math.cos(v*d),m.push(M*B),m.push(P),m.push(M*C),_.push(v*f),_.push(1*y/n),g.push(M*B+a),g.push(E+l),g.push(M*C+c);for(y=0;y<n;y++)for(v=0;v<=r;v++)F=y*(r+1)+v,U=F+r,b.push(F),b.push(U),b.push(U+1),b.push(F),b.push(U+1),b.push(F+1);if(!A&&t>0){for(x=g.length/3,m.push(0),m.push(1),m.push(0),_.push(.5),_.push(.5),g.push(0+a),g.push(h+l),g.push(0+c),v=0;v<=r;v++)B=Math.sin(v*d),C=Math.cos(v*d),I=.5*Math.sin(v*d)+.5,T=.5*Math.cos(v*d)+.5,m.push(t*B),m.push(1),m.push(t*C),_.push(I),_.push(T),g.push(t*B+a),g.push(h+l),g.push(t*C+c);for(v=0;v<r;v++)o=x,F=x+1+v,b.push(F),b.push(F+1),b.push(o)}if(!A&&i>0){for(x=g.length/3,m.push(0),m.push(-1),m.push(0),_.push(.5),_.push(.5),g.push(0+a),g.push(0-h+l),g.push(0+c),v=0;v<=r;v++)B=Math.sin(v*d),C=Math.cos(v*d),I=.5*Math.sin(v*d)+.5,T=.5*Math.cos(v*d)+.5,m.push(i*B),m.push(-1),m.push(i*C),_.push(I),_.push(T),g.push(i*B+a),g.push(0-h+l),g.push(i*C+c);for(v=0;v<r;v++)o=x,F=x+1+v,b.push(o),b.push(F+1),b.push(F)}return w.apply(e,{positions:g,normals:m,uv:_,indices:b})}function Ie(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,n=[],A=[];let o=0;for(let e=0,t=-r;e<=i;e++,t+=s)n.push(-r),n.push(0),n.push(t),n.push(r),n.push(0),n.push(t),n.push(t),n.push(0),n.push(-r),n.push(t),n.push(0),n.push(r),A.push(o++),A.push(o++),A.push(o++),A.push(o++);return w.apply(e,{primitive:"lines",positions:n,indices:A})}function Te(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const n=e.center,A=n?n[0]:0,o=n?n[1]:0,a=n?n[2]:0,l=t/2,c=i/2,h=Math.floor(s)||1,u=Math.floor(r)||1,d=h+1,f=u+1,p=t/h,g=i/u,m=new Float32Array(d*f*3),_=new Float32Array(d*f*3),b=new Float32Array(d*f*2);let y,v,B,C,M,E,F,U=0,x=0;for(y=0;y<f;y++){const e=y*g-c;for(v=0;v<d;v++)B=v*p-l,m[U]=B+A,m[U+1]=o,m[U+2]=-e+a,_[U+1]=1,b[x]=v/h,b[x+1]=(u-y)/u,U+=3,x+=2}U=0;const I=new(m.length/3>65535?Uint32Array:Uint16Array)(h*u*6);for(y=0;y<u;y++)for(v=0;v<h;v++)C=v+d*y,M=v+d*(y+1),E=v+1+d*(y+1),F=v+1+d*y,I[U]=F,I[U+1]=M,I[U+2]=C,I[U+3]=F,I[U+4]=E,I[U+5]=M,U+=6;return w.apply(e,{positions:m,normals:_,uv:b,indices:I})}function Pe(e={}){const t=e.lod||1,i=e.center?e.center[0]:0,s=e.center?e.center[1]:0,r=e.center?e.center[2]:0;let n=e.radius||1;n<0&&(console.error("negative radius not allowed - will invert"),n*=-1);let A=e.heightSegments||18;A<0&&(console.error("negative heightSegments not allowed - will invert"),A*=-1),A=Math.floor(t*A),A<18&&(A=18);let o=e.widthSegments||18;o<0&&(console.error("negative widthSegments not allowed - will invert"),o*=-1),o=Math.floor(t*o),o<18&&(o=18);const a=[],l=[],c=[],h=[];let u,d,f,p,g,m,_,b,y,v,B,C,M,E,F;for(u=0;u<=A;u++)for(f=u*Math.PI/A,p=Math.sin(f),g=Math.cos(f),d=0;d<=o;d++)m=2*d*Math.PI/o,_=Math.sin(m),b=Math.cos(m),y=b*p,v=g,B=_*p,C=1-d/o,M=u/A,l.push(y),l.push(v),l.push(B),c.push(C),c.push(M),a.push(i+n*y),a.push(s+n*v),a.push(r+n*B);for(u=0;u<A;u++)for(d=0;d<o;d++)E=u*(o+1)+d,F=E+o+1,h.push(E+1),h.push(F+1),h.push(F),h.push(E+1),h.push(F),h.push(E);return w.apply(e,{positions:a,normals:l,uv:c,indices:h})}function Se(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);let s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<4&&(s=4);let r=e.tubeSegments||24;r<0&&(console.error("negative tubeSegments not allowed - will invert"),r*=-1),r<4&&(r=4);let n=e.arc||2*Math.PI;n<0&&(console.warn("negative arc not allowed - will invert"),n*=-1),n>360&&(n=360);const A=e.center;let o=A?A[0]:0,a=A?A[1]:0;const l=A?A[2]:0,c=[],h=[],u=[],f=[];let p,g,m,_,b,y,v,B,C,M,E,F;for(B=0;B<=r;B++)for(v=0;v<=s;v++)p=v/s*n,g=.785398+B/r*Math.PI*2,o=t*Math.cos(p),a=t*Math.sin(p),m=(t+i*Math.cos(g))*Math.cos(p),_=(t+i*Math.cos(g))*Math.sin(p),b=i*Math.sin(g),c.push(m+o),c.push(_+a),c.push(b+l),u.push(1-v/s),u.push(B/r),y=d.normalizeVec3(d.subVec3([m,_,b],[o,a,l],[]),[]),h.push(y[0]),h.push(y[1]),h.push(y[2]);for(B=1;B<=r;B++)for(v=1;v<=s;v++)C=(s+1)*B+v-1,M=(s+1)*(B-1)+v-1,E=(s+1)*(B-1)+v,F=(s+1)*B+v,f.push(C),f.push(M),f.push(E),f.push(E),f.push(F),f.push(C);return w.apply(e,{positions:c,normals:h,uv:u,indices:f})}Be.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},Be.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(Be.parse._buffToStr(e));window.location.href=i},Be.clone=function(e){return JSON.parse(JSON.stringify(e))},Be.bin={},Be.bin.f=new Float32Array(1),Be.bin.fb=new Uint8Array(Be.bin.f.buffer),Be.bin.rf=function(e,t){for(var i=Be.bin.f,s=Be.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},Be.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Be.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Be.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},Be.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},Be.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},Be.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Be.parse={},Be.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;s<t.length;s++)i=i.concat(String.fromCharCode(t[s]));return i},Be.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),i=new Uint8Array(t),s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return t},Be.parse._readLine=function(e,t){for(var i="";10!=e[t];)i+=String.fromCharCode(e[t++]);return i},Be.parse.fromJSON=function(e){return JSON.parse(Be.parse._buffToStr(e))},Be.parse.toJSON=function(e){var t=JSON.stringify(e);return Be.parse._strToBuff(t)},Be.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},i={from:0,to:0},s=0,r=new Uint8Array(e);s<r.length;){var n=Be.parse._readLine(r,s);s+=n.length+1;var A=(n=(n=n.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==A[0]&&(i.to=t.i_verts.length,null==t.groups[A[1]]&&(t.groups[A[1]]={from:t.i_verts.length,to:0}),i=t.groups[A[1]]),"v"==A[0]){var o=parseFloat(A[1]),a=parseFloat(A[2]),l=parseFloat(A[3]);t.c_verts.push(o,a,l)}if("vt"==A[0]){o=parseFloat(A[1]),a=1-parseFloat(A[2]);t.c_uvt.push(o,a)}if("vn"==A[0]){o=parseFloat(A[1]),a=parseFloat(A[2]),l=parseFloat(A[3]);t.c_norms.push(o,a,l)}if("f"==A[0]){var c=A[1].split("/"),h=A[2].split("/"),u=A[3].split("/"),d=parseInt(c[0])-1,f=parseInt(h[0])-1,p=parseInt(u[0])-1,g=parseInt(c[1])-1,m=parseInt(h[1])-1,_=parseInt(u[1])-1,b=parseInt(c[2])-1,y=parseInt(h[2])-1,w=parseInt(u[2])-1,v=t.c_verts.length/3,B=t.c_uvt.length/2,C=t.c_norms.length/3;if(d<0&&(d=v+d+1),f<0&&(f=v+f+1),p<0&&(p=v+p+1),g<0&&(g=B+g+1),m<0&&(m=B+m+1),_<0&&(_=B+_+1),b<0&&(b=C+b+1),y<0&&(y=C+y+1),w<0&&(w=C+w+1),t.i_verts.push(d,f,p),t.i_uvt.push(g,m,_),t.i_norms.push(b,y,w),5==A.length){var M=A[4].split("/"),E=parseInt(M[0])-1,F=parseInt(M[1])-1,U=parseInt(M[2])-1;E<0&&(E=v+E+1),F<0&&(F=B+F+1),U<0&&(U=C+U+1),t.i_verts.push(d,p,E),t.i_uvt.push(g,_,F),t.i_norms.push(b,w,U)}}}return i.to=t.i_verts.length,t},Be.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},i={};i.ident=Be.bin.ril(e,0),i.version=Be.bin.ril(e,4),i.skinwidth=Be.bin.ril(e,8),i.skinheight=Be.bin.ril(e,12),i.framesize=Be.bin.ril(e,16),i.num_skins=Be.bin.ril(e,20),i.num_vertices=Be.bin.ril(e,24),i.num_st=Be.bin.ril(e,28),i.num_tris=Be.bin.ril(e,32),i.num_glcmds=Be.bin.ril(e,36),i.num_frames=Be.bin.ril(e,40),i.offset_skins=Be.bin.ril(e,44),i.offset_st=Be.bin.ril(e,48),i.offset_tris=Be.bin.ril(e,52),i.offset_frames=Be.bin.ril(e,56),i.offset_glcmds=Be.bin.ril(e,60),i.offset_end=Be.bin.ril(e,64);var s=i.offset_st;t.c_uvt=[];for(var r=0;r<i.num_st;r++){var n=Be.bin.rsl(e,s)/i.skinwidth,A=Be.bin.rsl(e,s+2)/i.skinheight;t.c_uvt.push(n,A),s+=4}s=i.offset_tris;var o=[],a=[];t.i_verts=o,t.i_uvt=a;for(r=0;r<i.num_tris;r++)o.push(Be.bin.rsl(e,s),Be.bin.rsl(e,s+2),Be.bin.rsl(e,s+4)),a.push(Be.bin.rsl(e,s+6),Be.bin.rsl(e,s+8),Be.bin.rsl(e,s+10)),s+=12;s=i.offset_skins;t.skins=[];for(r=0;r<i.num_skins;r++)t.skins.push(Be.bin.rASCII0(e,s)),s+=64;s=i.offset_frames;t.frames=[];var l=Be.parse.fromMD2._normals;for(r=0;r<i.num_frames;r++){var c={},h=Be.bin.rf(e,s),u=Be.bin.rf(e,s+4),d=Be.bin.rf(e,s+8);s+=12;var f=Be.bin.rf(e,s),p=Be.bin.rf(e,s+4),g=Be.bin.rf(e,s+8);s+=12,c.name=Be.bin.rASCII0(e,s),s+=16,c.verts=[],c.norms=[];for(var m=0;m<i.num_vertices;m++)c.verts.push(e[s]*h+f,e[s+1]*u+p,e[s+2]*d+g),c.norms.push(l[3*e[s+3]],l[3*e[s+3]+1],l[3*e[s+3]+2]),s+=4;t.frames.push(c)}return t},Be.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],Be.parse.fromCollada=function(e){var t=Be.parse._buffToStr(e),i=(new DOMParser).parseFromString(t,"text/xml"),s={},r=(i=i.childNodes[0]).getElementsByTagName("asset")[0],n=i.getElementsByTagName("library_geometries")[0],A=i.getElementsByTagName("library_images")[0],o=i.getElementsByTagName("library_materials")[0],a=i.getElementsByTagName("library_effects")[0];return r&&(s.asset=Be.parse.fromCollada._asset(r)),n&&(s.geometries=Be.parse.fromCollada._libGeometries(n)),A&&(s.images=Be.parse.fromCollada._libImages(A)),o&&(s.materials=Be.parse.fromCollada._libMaterials(o)),a&&(s.effects=Be.parse.fromCollada._libEffects(a)),s},Be.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},Be.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],i=0;i<e.length;i++){var s=e[i],r=Be.parse.fromCollada._getMesh(s.getElementsByTagName("mesh")[0]);t.push(r)}return t},Be.parse.fromCollada._getMesh=function(e){for(var t={},i=e.getElementsByTagName("source"),s=t.sources={},r=0;r<i.length;r++){for(var n=i[r].getElementsByTagName("float_array")[0].textContent.split(" "),A=n.length-(""==n[n.length-1]?1:0),o=new Array(A),a=0;a<A;a++)o[a]=parseFloat(n[a]);s[i[r].getAttribute("id")]=o}t.triangles=[];var l=e.getElementsByTagName("triangles");if(null==l)return t;for(r=0;r<l.length;r++){var c={},h=l[r];c.material=h.getAttribute("material");var u=h.getElementsByTagName("input"),d=[];for(a=0;a<u.length;a++){var f=u[a];o=[];d[parseInt(f.getAttribute("offset"))]=o;var p=f.getAttribute("semantic");c["s_"+p]="VERTEX"==p?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):f.getAttribute("source").substring(1),c["i_"+p]=o,s[c["s_"+p]]}var g=h.getElementsByTagName("p")[0].textContent.split(" "),m=3*Math.floor(g.length/3);for(a=0;a<m;a++)d[a%u.length].push(parseInt(g[a]));t.triangles.push(c)}return t},Be.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("id")]=e[i].getElementsByTagName("init_from")[0].textContent;return t},Be.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("name")]=e[i].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},Be.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},i=0;i<e.length;i++){for(var s={},r=e[i].getElementsByTagName("newparam"),n=0;n<r.length;n++){var A=r[n].getElementsByTagName("surface")[0];A&&(s.surface=A.getElementsByTagName("init_from")[0].textContent)}t[e[i].getAttribute("id")]=s}return t},Be.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=Be.bin.rsl(e,0))return null;for(var i=Be.bin.ril(e,2),s=6;s<i;){var r=Be.bin.rsl(e,s),n=Be.bin.ril(e,s+2);15677==r&&(t.edit=Be.parse.from3DS._edit3ds(e,s,n)),45056==r&&(t.keyf=Be.parse.from3DS._keyf3ds(e,s,n)),s+=n}return t},Be.parse.from3DS._edit3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);16384==n&&(null==s.objects&&(s.objects=[]),s.objects.push(Be.parse.from3DS._edit_object(e,r,A))),r+=A}return s},Be.parse.from3DS._keyf3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);45058==n&&(null==s.desc&&(s.desc=[]),s.desc.push(Be.parse.from3DS._keyf_objdes(e,r,A))),r+=A}return s},Be.parse.from3DS._keyf_objdes=function(e,t,i){for(var s={},r=t+6;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);45072==n&&(s.hierarchy=Be.parse.from3DS._keyf_objhierarch(e,r,A)),45073==n&&(s.dummy_name=Be.bin.rASCII0(e,r+6)),r+=A}return s},Be.parse.from3DS._keyf_objhierarch=function(e,t,i){var s={},r=t+6;return s.name=Be.bin.rASCII0(e,r),r+=s.name.length+1,s.hierarchy=Be.bin.rsl(e,r+4),s},Be.parse.from3DS._edit_object=function(e,t,i){var s={},r=t+6;for(s.name=Be.bin.rASCII0(e,r),r+=s.name.length+1;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);16640==n&&(s.mesh=Be.parse.from3DS._obj_trimesh(e,r,A)),r+=A}return s},Be.parse.from3DS._obj_trimesh=function(e,t,i){for(var s={},r=t+6;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);16656==n&&(s.vertices=Be.parse.from3DS._tri_vertexl(e,r,A)),16672==n&&(s.indices=Be.parse.from3DS._tri_facel1(e,r,A)),16704==n&&(s.uvt=Be.parse.from3DS._tri_mappingcoors(e,r,A)),16736==n&&(s.local=Be.parse.from3DS._tri_local(e,r,A)),r+=A}return s},Be.parse.from3DS._tri_vertexl=function(e,t,i){var s=[],r=t+6,n=Be.bin.rsl(e,r);r+=2;for(var A=0;A<n;A++)s.push(Be.bin.rf(e,r)),s.push(Be.bin.rf(e,r+4)),s.push(Be.bin.rf(e,r+8)),r+=12;return s},Be.parse.from3DS._tri_facel1=function(e,t,i){var s=[],r=t+6,n=Be.bin.rsl(e,r);r+=2;for(var A=0;A<n;A++)s.push(Be.bin.rsl(e,r)),s.push(Be.bin.rsl(e,r+2)),s.push(Be.bin.rsl(e,r+4)),r+=8;return s},Be.parse.from3DS._tri_mappingcoors=function(e,t,i){var s=[],r=t+6,n=Be.bin.rsl(e,r);r+=2;for(var A=0;A<n;A++)s.push(Be.bin.rf(e,r)),s.push(1-Be.bin.rf(e,r+4)),r+=8;return s},Be.parse.from3DS._tri_local=function(e,t,i){var s={},r=t+6;return s.X=[Be.bin.rf(e,r),Be.bin.rf(e,r+4),Be.bin.rf(e,r+8)],r+=12,s.Y=[Be.bin.rf(e,r),Be.bin.rf(e,r+4),Be.bin.rf(e,r+8)],r+=12,s.Z=[Be.bin.rf(e,r),Be.bin.rf(e,r+4),Be.bin.rf(e,r+8)],r+=12,s.C=[Be.bin.rf(e,r),Be.bin.rf(e,r+4),Be.bin.rf(e,r+8)],r+=12,s},Be.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},i={};return i.id=Be.bin.ril(e,0),i.verS=Be.bin.ril(e,4),i.texS=Be.bin.ril(e,8),i.indS=Be.bin.ril(e,12),i.verO=Be.bin.ril(e,16),i.verL=Be.bin.ril(e,20),i.texO=Be.bin.ril(e,24),i.texL=Be.bin.ril(e,28),i.indO=Be.bin.ril(e,32),i.indL=Be.bin.ril(e,36),0!=i.verO&&(t.vertices=Be.parse.fromBIV._readFloats(e,i.verO,i.verL)),0!=i.texO&&(t.uvt=Be.parse.fromBIV._readFloats(e,i.texO,i.texL)),0!=i.indO&&(t.indices=Be.parse.fromBIV._readInts(e,i.indO,i.indL,i.indS)),t},Be.parse.toBIV=function(e){for(var t=0,i=0;i<e.indices.length;i++)t=Math.max(t,e.indices[i]);var s=32;t<=65535&&(s=16);var r=40;e.vertices&&(r+=4*e.vertices.length),e.uvt&&(r+=4*e.uvt.length),e.indices&&(r+=e.indices.length*s/8);var n=new Uint8Array(r);Be.bin.wil(n,0,1769365870),Be.bin.wil(n,4,32),Be.bin.wil(n,8,32),Be.bin.wil(n,12,s);var A=40;return e.vertices&&(Be.bin.wil(n,16,A),Be.bin.wil(n,20,4*e.vertices.length),Be.parse.fromBIV._writeFloats(n,A,e.vertices),A+=4*e.vertices.length),e.uvt&&(Be.bin.wil(n,24,A),Be.bin.wil(n,28,4*e.uvt.length),Be.parse.fromBIV._writeFloats(n,A,e.uvt),A+=4*e.uvt.length),e.indices&&(Be.bin.wil(n,32,A),Be.bin.wil(n,36,4*e.indices.length),Be.parse.fromBIV._writeInts(n,A,e.indices,s)),n.buffer},Be.parse.fromBIV._readFloats=function(e,t,i){for(var s=[],r=0;r<i/4;r++)s.push(Be.bin.rf(e,t+4*r));return s},Be.parse.fromBIV._writeFloats=function(e,t,i){for(var s=0;s<i.length;s++)Be.bin.wf(e,t+4*s,i[s])},Be.parse.fromBIV._readInts=function(e,t,i,s){for(var r=[],n=0;n<i/4;n++)16==s&&r.push(Be.bin.rsl(e,t+2*n)),32==s&&r.push(Be.bin.ril(e,t+4*n));return r},Be.parse.fromBIV._writeInts=function(e,t,i,s){for(var r=0;r<i.length;r++)16==s&&Be.bin.wsl(e,t+2*r,i[r]),32==s&&Be.bin.wil(e,t+4*r,i[r])},Be.gen={},Be.gen.Plane=function(e,t,i,s){i||(i=1),s||(s=1);for(var r={verts:[],inds:[],uvt:[]},n=e+1,A=t+1,o=0;o<A;o++)for(var a=0;a<n;a++){var l=a*(2/e)-1,c=o*(2/t)-1;r.verts.push(l,c,0),r.uvt.push(i*a/e,s*o/t),o<t&&a<e&&r.inds.push(o*n+a,o*n+a+1,(o+1)*n+a,o*n+a+1,(o+1)*n+a,(o+1)*n+a+1)}return r},Be.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},Be.gen.Sphere=function(e,t){for(var i={verts:[],inds:[],uvt:[]},s=e+1,r=t+1,n=0;n<r;n++)for(var A=0;A<s;A++){var o=-Math.PI/2+n*Math.PI/t,a=2*A*Math.PI/e,l=Math.cos(o)*Math.cos(a),c=Math.sin(o),h=Math.cos(o)*Math.sin(a);i.verts.push(l,c,h),i.uvt.push(A/e,n/t),n<t&&A<e&&i.inds.push(s*n+A,s*n+A+1,s*(n+1)+A,s*n+A+1,s*(n+1)+A,s*(n+1)+A+1)}return i},Be.mat={},Be.mat.scale=function(e,t,i){return[e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1]},Be.mat.translate=function(e,t,i){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1]},Be.mat.rotateDeg=function(e,t,i){var s=Math.PI/180;return Be.mat.rotate(e*s,t*s,i*s)},Be.mat.rotate=function(e,t,i){var s=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],r=e,n=t,A=i,o=Math.cos(r),a=Math.cos(n),l=Math.cos(A),c=Math.sin(r),h=Math.sin(n),u=Math.sin(A);return s[0]=a*l,s[1]=-a*u,s[2]=h,s[4]=o*u+c*h*l,s[5]=o*l-c*h*u,s[6]=-c*a,s[8]=c*u-o*h*l,s[9]=c*l+o*h*u,s[10]=o*a,s},Be.edit={},Be.edit.interpolate=function(e,t,i,s){for(var r=0;r<e.length;r++)i[r]=e[r]+s*(t[r]-e[r])},Be.edit.transform=function(e,t){for(var i=0;i<e.length;i+=3){var s=e[i],r=e[i+1],n=e[i+2];e[i+0]=t[0]*s+t[4]*r+t[8]*n+t[12],e[i+1]=t[1]*s+t[5]*r+t[9]*n+t[13],e[i+2]=t[2]*s+t[6]*r+t[10]*n+t[14]}},Be.edit.unwrap=function(e,t,i){for(var s=new Array(Math.floor(e.length/3)*i),r=0;r<e.length;r++)for(var n=0;n<i;n++)s[r*i+n]=t[e[r]*i+n];return s},Be.edit.remap=function(e,t,i,s){for(var r=new Array(i.length),n=0;n<e.length;n++)for(var A=0;A<s;A++)r[t[n]*s+A]=i[e[n]*s+A];return r},Be.utils={},Be.utils.getAABB=function(e){var t,i,s,r,n,A;r=n=A=-(t=i=s=999999999);for(var o=0;o<e.length;o+=3){var a=e[o+0],l=e[o+1],c=e[o+2];a<t&&(t=a),a>r&&(r=a),l<i&&(i=l),l>n&&(n=l),c<s&&(s=c),l>A&&(A=c)}return{min:{x:t,y:i,z:s},max:{x:r,y:n,z:A}}};const De={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function ke(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],n=e.size||1,A=[],o=[],a=e.text;w.isNumeric(a)&&(a=""+a);for(var l,c,h,u,d,f,p,g,m,_=(a||"").split("\n"),b=0,y=0,v=.04,B=0;B<_.length;B++){l=0,h=(c=_[B]).length;for(var C=0;C<h;C++)if(u=De[c.charAt(C)]){d=1,f=-1,p=-1,g=u.points.length;for(var M=0;M<g;M++)-1!==(m=u.points[M])[0]||-1!==m[1]?(A.push(l+m[0]*n*v+i),A.push(y+m[1]*n*v+s),A.push(0+r),-1===f?f=b:(-1===p||(f=p),p=b),b++,d?d=!1:(o.push(f),o.push(p))):d=1;l+=u.width*v*n}y-=35*v*n}return w.apply(e,{primitive:"lines",positions:A,indices:o})}function Qe(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e<t-1;e++)i.push(e),i.push(e+1);return w.apply(e,{primitive:"lines",positions:e.points,indices:i})}function Re(e={}){let t=e.curve.getPoints(e.divisions).map((e=>[...e])).flat();return Qe({id:e.id,points:t})}function Oe(e={}){if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";let t=[],i=[],s=e.startPoint[0],r=e.startPoint[1],n=e.startPoint[2],A=e.endPoint[0],o=e.endPoint[1],a=e.endPoint[2],l=Math.sqrt((A-s)**2+(o-r)**2+(a-n)**2),c=[(A-s)/l,(o-r)/l,(a-n)/l];if(e.pattern){let h=e.pattern.length,u=!1,d=0,f=0,p=0,g=[s,r,n],m=e.pattern[f];for(i.push(g[0],g[1],g[2]);m<=l-d;){let s=[c[0]*m,c[1]*m,c[2]*m],r=[g[0]+s[0],g[1]+s[1],g[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(p),t.push(p+1)),u=!u,p+=1,g=r,f+=1,f>=h&&(f=0),d+=m,m=e.pattern[f]}e.extendToEnd&&(i.push(A,o,a),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,n,A,o,a);return w.apply(e,{primitive:"lines",positions:i,indices:t})}const Ve=d.vec4(4),Le=d.vec4(),He=d.vec4(),Ne=d.vec3([1,0,0]),Ge=d.vec3([0,1,0]),je=d.vec3([0,0,1]),We=d.vec3(3),ze=d.vec3(3),Xe=d.identityMat4();class Ke extends D{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=d.vec3(),this._quaternion=d.identityQuaternion(),this._rotation=d.vec3(),this._position=d.vec3(),this._offset=d.vec3(),this._localMatrix=d.identityMat4(),this._worldMatrix=d.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let i=0,s=e.length;i<s;i++)this.addChild(e[i],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=d.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,i=this._children.length;t<i;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,i=this._children.length;e<i;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,i=this._children.length;t<i;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)d.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,i=e._children.length;t<i;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=d.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;d.collapseAABB3(this._aabb);for(let t=0,i=this._children.length;t<i;t++)e=this._children[t],e.collidable&&d.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(w.isNumeric(e)||w.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+w.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,i=this._children.length;t<i;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,i=this._children.length;t<i;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(w.isNumeric(e)||w.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+w.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=d.identityMat4()),this._localMatrix.set(e||Xe),d.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=d.identityMat4()),d.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return Ve[0]=e[0],Ve[1]=e[1],Ve[2]=e[2],Ve[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Ve,Le),d.mulQuaternions(this.quaternion,Le,He),this.quaternion=He,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ve[0]=e[0],Ve[1]=e[1],Ve[2]=e[2],Ve[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Ve,Le),d.mulQuaternions(Le,this.quaternion,Le),this}rotateX(e){return this.rotate(Ne,e)}rotateY(e){return this.rotate(Ge,e)}rotateZ(e){return this.rotate(je,e)}translate(e,t){return d.vec3ApplyQuaternion(this.quaternion,e,We),d.mulVec3Scalar(We,t,ze),d.addVec3(this.position,ze,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ne,e)}translateY(e){return this.translate(Ge,e)}translateZ(e){return this.translate(je,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice(0);let t;for(let i=0,s=e.length;i<s;i++)t=e[i],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}const Ze=d.vec3(),Je=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,n){return n=n||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(s,t,i),d.setMat4Translation(s,i,n),n.slice()}}();function Ye(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,n=Float32Array.from([e[1]])[0],A=e[1]-n,o=Float32Array.from([e[2]])[0],a=e[2]-o;t[0]=s,t[1]=n,t[2]=o,i[0]=r,i[1]=A,i[2]=a}function $e(e,t,i,s=1e3){const r=d.getPositionsCenter(e,Ze),n=Math.round(r[0]/s)*s,A=Math.round(r[1]/s)*s,o=Math.round(r[2]/s)*s;i[0]=n,i[1]=A,i[2]=o;const a=0!==i[0]||0!==i[1]||0!==i[2];if(a)for(let i=0,s=e.length;i<s;i+=3)t[i+0]=e[i+0]-n,t[i+1]=e[i+1]-A,t[i+2]=e[i+2]-o;return a}const qe=1e3,et=1001,tt=1002,it=1003,st=1004,rt=1004,nt=1005,At=1005,ot=1006,at=1007,lt=1007,ct=1008,ht=1008,ut=1009,dt=1010,ft=1011,pt=1012,gt=1013,mt=1014,_t=1015,bt=1016,yt=1017,wt=1018,vt=1020,Bt=1021,Ct=1022,Mt=1023,Et=1024,Ft=1025,Ut=1026,xt=1027,It=1028,Tt=1029,Pt=1030,St=1031,Dt=1033,kt=33776,Qt=33777,Rt=33778,Ot=33779,Vt=35840,Lt=35841,Ht=35842,Nt=35843,Gt=36196,jt=37492,Wt=37496,zt=37808,Xt=37809,Kt=37810,Zt=37811,Jt=37812,Yt=37813,$t=37814,qt=37815,ei=37816,ti=37817,ii=37818,si=37819,ri=37820,ni=37821,Ai=36492,oi=3e3,ai=3001,li=1e4,ci=10001,hi=10002,ui=10003,di=new e({}),fi=d.vec3(),pi=d.vec4(),gi={3001:"sRGBToLinear"},mi=function(){const e=[],t=[],i=[],s=[],r=[],n=[],A=[],o=(t,i)=>{let s=!1;return e.push((e=>s&&i(t,e))),{toString:()=>(s=!0,t)}},a={createAttribute:function(t,i){let s=!1;e.push((e=>s&&e.push(`in ${t} ${i};`)));const A={toString:()=>(s=!0,i)};return r.push((e=>{const t=s&&e(i);return t&&n.push(t.attributeHash),A.setInputValue=t,null})),A},createFragmentDefinition:(e,t)=>{let i=!1;return s.push((s=>i&&t(e,s))),{toString:()=>(i=!0,e)}},createOutput:(e,t,s)=>{let r=!1;return i.push((i=>r&&i.push(`layout(location = ${s||0}) out ${e} ${t};`))),{toString:()=>(r=!0,t)}},createUniform:(t,s,r)=>{let n=!1;const o=e=>n&&e.push(`uniform ${t} ${s};`);e.push(o),i.push(o);const a={toString:()=>(n=!0,s)};return A.push((e=>{const t=n&&e(s);return r?t&&(e=>r(t,e)):(a.setInputValue=t,null)})),a},createUniformArray:(t,s,r)=>{let n=!1;const o=e=>n&&e.push(`uniform ${t} ${s}[${r}];`);e.push(o),i.push(o);const a={toString:()=>(n=!0,s)};return A.push((e=>(a.setInputValue=n&&e(s),null))),a},createUniformBlock:(t,s,r)=>{let n=!1;const o=Object.keys(s),a=e=>{n&&(e.push(`uniform ${t} {`),o.forEach((t=>e.push(` ${s[t]} ${t};`))),e.push("};"))};e.push(a),i.push(a);const l={};return o.forEach((e=>l[e]={toString:()=>(n=!0,e)})),A.push((e=>{const i=n&&e(t);return r?i&&(e=>r(i,e)):(l.setInputValue=i,null)})),l},createVarying:(s,r,n,A)=>{let o=!1;const a=A?A+" ":"";return e.push((e=>o&&e.push(`${a}out ${s} ${r};`))),t.push((e=>o&&e.push(`${r} = ${n()};`))),i.push((e=>o&&e.push(`${a}in ${s} ${r};`))),{toString:()=>(o=!0,r)}},createVertexDefinition:o,commonLibrary:{octDecode:o("octDecode",((e,t)=>{t.push(`vec3 ${e}(vec2 oct) {`),t.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),t.push(" if (v.z < 0.0) {"),t.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),t.push(" }"),t.push(" return normalize(v);"),t.push("}")}))}};return{programVariables:a,buildProgram:(o,l,c)=>{const h=c.getLogDepth,u=c.clipPos,f=c.usePickClipPos&&function(){const e=a.createUniform("vec2","pickClipPos"),t=a.createUniform("vec2","pickClipPosInv");return{setClipPosInputValue:i=>{e.setInputValue(i.pickClipPos),t.setInputValue(i.pickClipPosInv)},transformedClipPos:()=>`vec4((${u}.xy / ${u}.w - ${e}) * ${t} * ${u}.w, ${u}.zw)`}}(),p=f?f.transformedClipPos():u,g=[],m=a.createVarying("float","isPerspective",(()=>`(${c.projMatrix}[2][3] == -1.0) ? 1.0 : 0.0`)),_=a.createUniform("float","logDepthBufFC",((e,t)=>e(2/(Math.log(t.view.far+1)/Math.LN2)))),b=a.createVarying("float","vFragDepth",(()=>"1.0 + clipPos.w"));h?g.push(`gl_FragDepth = ${c.testPerspectiveForGl_FragDepth?`${m} == 0.0 ? gl_FragCoord.z : `:""}log2(${h(b)}) * ${_} * 0.5;`):c.cleanerEdges&&g.push("gl_FragDepth = gl_FragCoord.z + length(vec2(dFdx(gl_FragCoord.z), dFdy(gl_FragCoord.z)));");const y=a.createFragmentDefinition("linearToGamma",((e,t)=>{t.push(`vec4 ${e}(in vec4 value, in float gammaFactor) {`),t.push(" return vec4(pow(value.xyz, vec3(1.0 / gammaFactor)), value.w);"),t.push("}")})),w=c.sectionPlanesState,v=w&&function(){const e=function(e){const t=[];for(let i=0;i<e;++i)t.push(i);return t}(w.getNumAllocatedSectionPlanes()).map((e=>{const t=(t,i,s)=>a.createUniform(t,`sectionPlane${i}${e}`,((t,i)=>{const r=w.sectionPlanes,n=r.length,A=(i.mesh.layerIndex||0)*n,o=e<n&&i.mesh.renderFlags.sectionPlanesActivePerLayer[A+e];return s(t,o,r[e],i.mesh.origin)}));return{act:t("bool","Active",((e,t)=>e(t?1:0))),dir:t("vec3","Dir",((e,t,i)=>t&&e(i.dir))),pos:t("vec3","Pos",((e,t,i,s)=>t&&e(s?d.mulVec3Scalar(d.normalizeVec3(i.dir,fi),-(d.dotVec3(i.dir,s)+i.dist),fi):i.pos)))}}));return e.length>0&&(t=>e.map((e=>`(${e.act} ? clamp(dot(-${e.dir}, ${t} - ${e.pos}), 0.0, 1000.0) : 0.0)`)).join(" + "))}(),B=c.crossSections,C=v?function(){const e=a.createUniform("vec4","sliceColor",(e=>e(B.sliceColor))),t=i=>(t.needed=!0,`(sliced ? ${e} : ${i})`);return t}():e=>e,M=c.getGammaFactor,E=a.createUniform("float","gammaFactor",(e=>e(M())));c.appendFragmentOutputs(g,M&&(e=>`${y}(${e}, ${E})`),"gl_FragCoord",C);const F=function(){const e=[],t=a.createUniform("float","sliceThickness",(e=>e(B.sliceThickness)));if(v){C.needed&&e.push(" bool sliced = false;"),e.push(` if (${c.clippableTest()}) {`);const i=a.createVarying("highp vec3","vHighpWorldPosition",(()=>`${c.worldPositionAttribute}.xyz`));if(e.push(` float dist = ${v(i)};`),c.clippingCaps){const t=a.createVarying("float","vClipPositionW",(()=>"gl_Position.w"));e.push(` if (dist > (0.002 * ${t})) { discard; }`),e.push(" if (dist > 0.0) { "),e.push(` ${c.clippingCaps} = vec4(1.0, 0.0, 0.0, 1.0);`),h&&e.push(` gl_FragDepth = log2(${h(b)}) * ${_} * 0.5;`),e.push(" return;"),e.push(" }")}else e.push(` if (dist > ${C.needed?t:"0.0"}) { discard; }`);C.needed&&e.push(" sliced = dist > 0.0;"),e.push(" }")}return e}(),U=function(){const e=[];return s.forEach((t=>t(e))),e}(),x=[...function(){const e=[];return i.forEach((t=>t(e))),e}(),...U,"void main(void) {",...c.discardPoints?[" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"," if (dot(cxy, cxy) > 1.0) { discard; }"]:[],...F,...g,"}"],I=[`gl_Position = ${p};`,...c.getPointSize?[`gl_PointSize = ${c.getPointSize()};`]:[],...function(){const e=[];return t.forEach((t=>t(e))),e}()],T=c.getVertexData?c.getVertexData():[],P=[...function(){const t=[];return e.forEach((e=>e(t))),t}(),"void main(void) {",...T,...I,"}"],S=e=>["#version 300 es","// "+l+" "+e+" shader","#ifdef GL_FRAGMENT_PRECISION_HIGH","precision highp float;","precision highp int;","precision highp usampler2D;","precision highp isampler2D;","precision highp sampler2D;","#else","precision mediump float;","precision mediump int;","precision mediump usampler2D;","precision mediump isampler2D;","precision mediump sampler2D;","#endif"],D=S("vertex").concat(P),k=S("fragment").concat(["vec4 sRGBToLinear(in vec4 value) {"," return vec4(mix(pow(value.rgb * 0.9478672986 + 0.0521327014, vec3(2.4)), value.rgb * 0.0773993808, vec3(lessThanEqual(value.rgb, vec3(0.04045)))), value.w);","}"]).concat(x),Q=(e,t)=>{const i=t.join("\n"),s=o.createShader(e);return o.shaderSource(s,i),o.compileShader(s),o.getShaderParameter(s,o.COMPILE_STATUS)?[s]:[null,["Failed to compile",o.getShaderInfoLog(s),i.split("\n").map(((e,t)=>t+1+": "+e+"\n")).join("")]]},[R,O]=Q(o.VERTEX_SHADER,D),[V,L]=Q(o.FRAGMENT_SHADER,k),H=e=>(console.error(e.join("\n")),[null,e]);if(O)return H(["Vertex shader error"].concat(O));if(L)return H(["Fragment shader error"].concat(L));{const e=o.createProgram();if(e){if(o.attachShader(e,R),o.attachShader(e,V),o.linkProgram(e),o.getProgramParameter(e,o.LINK_STATUS)){const t=yi(o,e);r.forEach((e=>e(t)));const i=A.map((e=>e(t))).filter((e=>e)),s=di.addItem({});return[{id:s,bind:()=>o.useProgram(e),inputSetters:{attributesHash:n.sort().join(", "),setUniforms:(e,t)=>{f&&f.setClipPosInputValue(e),i.forEach((e=>e(t)))}},destroy:()=>{di.removeItem(s),o.deleteProgram(e),o.deleteShader(R),o.deleteShader(V)}}]}return H(["",o.getProgramInfoLog(this.program),"","Vertex shader:","",...D,"","Fragment shader:","",...k])}return H(["Failed to allocate program"])}}}},_i=function(e,t){const i=e.createUniform("vec4","lightAmbient",(e=>e(t.getAmbientColorAndIntensity()))),s=t.lights,r=s.map(((t,i)=>{const r={color:e.createUniform("vec4",`lightColor${i}`,(e=>{const t=s[i];pi[0]=t.color[0],pi[1]=t.color[1],pi[2]=t.color[2],pi[3]=t.intensity,e(pi)})),position:e.createUniform("vec3",`lightPos${i}`,(e=>e(s[i].pos))),direction:e.createUniform("vec3",`lightDir${i}`,(e=>e(s[i].dir))),shadowProjMatrix:e.createUniform("mat4",`shadowProjMatrix${i}`,(e=>e(s[i].getShadowViewMatrix()))),shadowViewMatrix:e.createUniform("mat4",`shadowViewMatrix${i}`,(e=>e(s[i].getShadowViewMatrix()))),shadowMap:e.createUniform("sampler2D",`shadowMap${i}`,(e=>e(s[i].getShadowRenderBuf().colorTextures[0])))},n=e=>({glslLight:{isWorldSpace:"world"===t.space,getColor:()=>`${r.color}.rgb * ${r.color}.a`,getDirection:(t,i)=>`normalize(${e(t,i)})`,shadowParameters:t.castsShadow&&{getShadowProjMatrix:()=>r.shadowProjMatrix,getShadowViewMatrix:()=>r.shadowViewMatrix,getShadowMap:()=>r.shadowMap}},setupLightsInputs:()=>{const e=Object.values(r).map((e=>e.setupLightsInputs())).filter((e=>e));return()=>e.forEach((e=>e()))}});return"dir"===t.type?"view"===t.space?n(((e,t)=>`-${r.direction}`)):n(((e,t)=>`-(${e} * vec4(${r.direction}, 0.0)).xyz`)):"point"===t.type?"view"===t.space?n(((e,t)=>`${r.position} - ${t}`)):n(((e,t)=>`(${e} * vec4(${r.position}, 1.0)).xyz - ${t}`)):null})).filter((e=>e)),n=(t,i)=>{const s=()=>{const e=i();return e.length>0&&e[0]},r=s();return r&&bi(e,"samplerCube",t,r.encoding,(e=>{const t=s();t&&e(t.texture)}))},A=n("light",(()=>t.lightMaps)),o=n("reflection",(()=>t.reflectionMaps));return{getHash:()=>t.getHash(),getAmbientColor:()=>`${i}.rgb * ${i}.a`,directionalLights:r.map((e=>e.glslLight)),getIrradiance:A&&(e=>`${A(e)}.rgb`),getReflection:o&&((e,t)=>`${o(e,t)}.rgb`)}},bi=(e,t,i,s,r)=>{const n=e.createUniform(t,i+"Map",r);return(e,t)=>{const i=t?`texture(${n}, ${e}, ${t})`:`texture(${n}, ${e})`;return 3e3!==s?`${gi[s]}(${i})`:i}},yi=function(e,t){const i={},s=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<s;++r){const n=e.getActiveAttrib(t,r),A=e.getAttribLocation(t,n.name);i[n.name]=function(t){t.bindAtLocation(A),e.enableVertexAttribArray(A);const i=t.attributeDivisor;i&&e.vertexAttribDivisor(A,i)},i[n.name].attributeHash=`${A.toString().padStart(1+Math.floor(Math.log10(s)),"0")}:${n.name}`}const r=e.getProgramParameter(t,e.ACTIVE_UNIFORM_BLOCKS);for(let s=0;s<r;++s){const r=e.getActiveUniformBlockName(t,s),n=e.getUniformBlockIndex(t,r),A=s;e.uniformBlockBinding(t,n,A);const o=e.createBuffer();i[r]=function(t){e.bindBuffer(e.UNIFORM_BUFFER,o),e.bufferData(e.UNIFORM_BUFFER,t,e.DYNAMIC_DRAW),e.bindBufferBase(e.UNIFORM_BUFFER,A,o)}}const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);let A=0;for(let s=0;s<n;++s){const r=e.getActiveUniform(t,s);let n=r.name;n.endsWith("[0]")&&(n=n.substr(0,n.length-3)),"\0"===n[n.length-1]&&(n=n.substr(0,n.length-1));const o=e.getUniformLocation(t,n);if(function(){for(let t in e)if(r.type===e[t])return t}(),r.type===e.SAMPLER_2D||r.type===e.SAMPLER_CUBE||r.type===e.SAMPLER_2D_SHADOW||e instanceof window.WebGL2RenderingContext&&(r.type===e.UNSIGNED_INT_SAMPLER_2D||r.type===e.INT_SAMPLER_2D)){const t=A++;i[n]=function(i){const s=i.bind(t);return s&&e.uniform1i(o,t),s}}else i[n]=function(){if(1===r.size)switch(r.type){case e.BOOL:case e.INT:return t=>e.uniform1i(o,t);case e.FLOAT:return t=>e.uniform1f(o,t);case e.FLOAT_VEC2:return t=>e.uniform2fv(o,t);case e.FLOAT_VEC3:return t=>e.uniform3fv(o,t);case e.FLOAT_VEC4:return t=>e.uniform4fv(o,t);case e.FLOAT_MAT3:return t=>e.uniformMatrix3fv(o,!1,t);case e.FLOAT_MAT4:return t=>e.uniformMatrix4fv(o,!1,t)}else if(r.size>1)switch(r.type){case e.FLOAT:return t=>e.uniform1fv(o,t);case e.FLOAT_VEC2:return t=>e.uniform2fv(o,t);case e.FLOAT_VEC3:return t=>e.uniform3fv(o,t);case e.FLOAT_VEC4:return t=>e.uniform4fv(o,t)}throw`Unhandled uniform ${n}`}()}return function(e){const t=i[e];if(!t)throw`Missing input "${e}"`;return t}},wi=d.vec4(),vi=d.vec4();class Bi{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const Ci=d.OBB3(),Mi=d.vec4(),Ei=d.vec4(),Fi=d.vec4(),Ui=d.vec3([1,0,0]),xi=d.vec3([0,1,0]),Ii=d.vec3([0,0,1]),Ti=d.vec3(3),Pi=d.vec3(3),Si=d.identityMat4(),Di=new e({}),ki={};class Qi extends D{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new Bi,this._state=new oe({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickOcclusionHash:"",offset:d.vec3(),origin:null,originHash:null,isUI:t.isUI});const i=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,s=this,r=e=>{let t=null;const i=()=>{if(!t){const i=mi(),r=i.programVariables.createAttribute,n=s._geometry._state,A={position:r("vec3","position"),color:n.colorsBuf&&r("vec4","color"),pickColor:r("vec4","pickColor"),uv:n.uvBuf&&r("vec2","uv"),normal:(n.autoVertexNormals||n.normalsBuf)&&["triangles","triangle-strip","triangle-fan"].includes(n.primitiveName)&&r("vec3","normal")},o=function(e){const t={toString:()=>(t.needed=!0,e)};return t},a=A.normal&&o("worldNormal"),l=a&&o("viewNormal"),c=A.uv&&o("decodedUv"),h=e(i.programVariables,{attributes:{position:{world:"worldPosition",view:"viewPosition"},color:A.color,pickColor:A.pickColor,uv:c,normal:A.normal&&{world:a,view:l}},viewMatrix:"viewMatrix2"}),u=[h.programName,s.scene.canvas.canvas.id,s.scene._sectionPlanesState.getHash(),s._geometry._state.hash].concat(h.getHash()).join(";");if(!(u in ki)){const e=Oi(s,A,{decodedUv:c,worldNormal:a,viewNormal:l},h,i);if(e.errors)return void console.log(e.errors.join("\n"));const t=Di.addItem({});ki[u]={drawMesh:e.drawMesh,id:t,useCount:0,delete:()=>{Di.removeItem(t),e.destroy(),delete ki[u],m.memory.programs--}},m.memory.programs++}t=ki[u],t.useCount++}};return{get:i,getId:()=>t.id,put:()=>{t&&(0==--t.useCount&&t.delete(),t=null)},drawMesh:(e,s,r)=>{i(),t&&t.drawMesh(e,s,r)}}},n=s.scene,A=e=>(t,i)=>function(e,t,i,s,r){const n=r&&_i(t,s._lightsState),A=t.createUniform("vec3","uColor",((e,t)=>e(r?t.material.fillColor:t.material.edgeColor))),o=t.createUniform("float","uAlpha",((e,t)=>e(r?t.material.fillAlpha:t.material.edgeAlpha))),a=t.createVarying("vec4","vColor",(()=>{const e=i.attributes,t=r&&[n.getAmbientColor()].concat(e.normal?n.directionalLights.map((t=>`(max(dot(${e.normal.view}, ${t.getDirection(i.viewMatrix,e.position.view)}), 0.0) * ${t.getColor()})`)):[]);return`vec4(${A}${t?` * (${t.join(" + ")})`:""}, ${o})`})),l=t.createOutput("vec4","outColor");return{getHash:()=>[e,s.gammaOutput?"go":"",n&&n.getHash()],programName:r?"EmphasisFill":"EmphasisEdges",dontSetFrontFace:!0,discardPoints:r,drawEdges:!r,appendFragmentOutputs:(e,t)=>e.push(`${l} = ${t?t(a):a};`)}}(s._state.hash,t,i,n,e);this._renderers={_drawRenderer:r(((e,t)=>"LambertMaterial"===i.type?function(e,t,i,s,r){const n=_i(t,r._lightsState),A=t.createUniform("vec4","colorize",((e,t)=>e(t.meshColorize))),o=t.createUniform("float","materialAlpha",((e,t)=>e(t.material.alpha))),a=t.createUniform("vec3","materialColor",((e,t)=>e(t.material.color))),l=t.createUniform("vec3","materialEmissive",((e,t)=>e(t.material.emissive))),c=t.createVarying("vec4","vColor",(()=>{const e=i.attributes,t=[n.getAmbientColor()].concat(e.normal?n.directionalLights.map((t=>`(max(dot(${e.normal.view}, ${t.getDirection(i.viewMatrix,e.position.view)}), 0.0) * ${t.getColor()})`)):[]);return`${A} * vec4((${t.join(" + ")}) * ${a} + ${l}, ${o});`})),h=t.createOutput("vec4","outColor");return{getHash:()=>[e,r.gammaOutput?"go":"",n.getHash(),s._state.hash],programName:"Lambert",canActAsBackground:!0,discardPoints:!0,setupPointSize:!0,setsLineWidth:!0,appendFragmentOutputs:(e,t)=>e.push(`${h} = ${t?t(c):c};`)}}(s._state.drawHash,e,t,i,n):function(e,t,i,s,r){const n=s._state,A="PhongMaterial"===n.type,o="MetallicMaterial"===n.type,a="SpecularMaterial"===n.type,l=i.attributes,c=_i(t,r._lightsState),h=t.createUniform("vec4","colorize",((e,t)=>e(t.meshColorize))),u=t.createFragmentDefinition("fresnel",((e,t)=>{t.push(`float ${e}(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {`),t.push(" float fr = abs(dot(eyeDir, normal));"),t.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),t.push(" return pow(finalFr, power);"),t.push("}")})),d=(e,i,r)=>{const n=(i,s,n)=>t.createUniform(i,e+"Fresnel"+s,((e,t)=>e(n(r(t.material))))),A=n("float","EdgeBias",(e=>e.edgeBias)),o=n("float","CenterBias",(e=>e.centerBias)),a=n("float","Power",(e=>e.power)),l=n("vec3","EdgeColor",(e=>e.edgeColor)),c=n("vec3","CenterColor",(e=>e.centerColor));return r(s)&&((e,t)=>`mix(${l+i}, ${c+i}, ${u}(${e}, ${t}, ${A}, ${o}, ${a}))`)},f=d("diffuse","",(e=>e._diffuseFresnel)),p=d("specular","",(e=>e._specularFresnel)),g=d("emissive","",(e=>e._emissiveFresnel)),m=d("alpha",".r",(e=>e._alphaFresnel)),_=(e,i)=>{const r=l.uv&&i(s),n=r&&bi(t,"sampler2D",e,r.encoding,((e,t)=>e(i(t.material)._state.texture)));return n&&function(){const s=r._state.matrix&&t.createUniform("mat4",e+"MapMatrix",((e,t)=>e(i(t.material)._state.matrix))),A=s?e=>`(${s} * ${e}).st`:e=>`${e}.st`,o=(e,t)=>n(A(e));return o.getTexCoordExpression=A,o}()},b=_("ambient",(e=>e._ambientMap)),y=_("baseColor",(e=>e._baseColorMap)),w=_("diffuse",(e=>e._diffuseMap)),v=_("emissive",(e=>e._emissiveMap)),B=_("occlusion",(e=>e._occlusionMap)),C=_("alpha",(e=>e._alphaMap)),M=_("metallic",(e=>e._metallicMap)),E=_("roughness",(e=>e._roughnessMap)),F=_("metallicRoughness",(e=>e._metallicRoughnessMap)),U=_("specular",(e=>e._specularMap)),x=_("glossiness",(e=>e._glossinessMap)),I=_("specularGlossiness",(e=>e._specularGlossinessMap)),T=_("normal",(e=>e._normalMap)),P=(e,i,r)=>{const n=r(s);return("float"===i?null!=n:n)&&t.createUniform(i,e,((e,t)=>e(r(t.material))))},S=P("materialAmbient","vec3",(e=>e.ambient)),D=P("materialDiffuse","vec3",(e=>e.diffuse)),k=P("materialBaseColor","vec3",(e=>e.baseColor)),Q=P("materialEmissive","vec3",(e=>e.emissive)),R=P("materialSpecular","vec3",(e=>e.specular)),O=P("materialGlossiness","float",(e=>e.glossiness)),V=P("materialMetallic","float",(e=>e.metallic)),L=P("materialRoughness","float",(e=>e.roughness)),H=P("materialShininess","float",(e=>e.shininess)),N=P("materialSpecularF0","float",(e=>e.specularF0)),G=P("materialAlphaModeCutoff","vec4",(e=>{const t=e.alpha;return null!=t?(wi[0]=t,wi[1]=1===e.alphaMode?1:0,wi[2]=e.alphaCutoff,wi):null})),j=t.createVarying("vec3","vViewPosition",(()=>`${l.position.view}.xyz`)),W=t.createVarying("vec4","texturePos",(()=>`vec4(${l.uv}, 1.0, 1.0)`)),z=l.color&&t.createVarying("vec4","vColor",(()=>l.color)),X=t.createVarying("vec3","vViewNormal",(()=>l.normal.view)),K=c.directionalLights.map(((e,s)=>({vViewLightReverseDir:t.createVarying("vec3",`vViewLightReverseDir${s}`,(()=>e.getDirection(i.viewMatrix,null))),vShadowPosFromLight:t.createVarying("vec3",`vShadowPosFromLight${s}`,(()=>`(mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0) * ${e.shadowParameters.getShadowProjMatrix()} * (${e.shadowParameters.getShadowViewMatrix()} * ${l.position.world})).xyz`))}))),Z=t.createVarying("vec3","vWorldNormal",(()=>l.normal.world)),J=t.createOutput("vec4","outColor"),Y=t.createFragmentDefinition("saturate",((e,t)=>t.push(`float ${e}(const in float a) { return clamp(a, 0.0, 1.0); }`))),$=t.createFragmentDefinition("BRDF_Specular_GGX",((e,t)=>{t.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),t.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),t.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),t.push("}"),t.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),t.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),t.push(" return 1.0 / ( gl * gv );"),t.push("}"),t.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),t.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),t.push(" return 0.5 / max( gv + gl, 1e-6 );"),t.push("}"),t.push("float D_GGX(const in float alpha, const in float dotNH) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),t.push(" return 0.31830988618 * a2 / ( denom * denom);"),t.push("}"),t.push(`vec3 ${e}(const in vec3 incidentLightDirection, const in vec3 viewNormal, const in vec3 viewEyeDir, const in vec3 specularColor, const in float roughness) {`),t.push(" float alpha = ( roughness * roughness );"),t.push(" vec3 halfDir = normalize( incidentLightDirection + viewEyeDir );"),t.push(` float dotNL = ${Y}( dot( viewNormal, incidentLightDirection ) );`),t.push(` float dotNV = ${Y}( dot( viewNormal, viewEyeDir ) );`),t.push(` float dotNH = ${Y}( dot( viewNormal, halfDir ) );`),t.push(` float dotLH = ${Y}( dot( incidentLightDirection, halfDir ) );`),t.push(" vec3 F = F_Schlick( specularColor, dotLH );"),t.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),t.push(" float D = D_GGX( alpha, dotNH );"),t.push(" return F * (G * D);"),t.push("}")})),q=t.createFragmentDefinition("BRDF_Specular_GGX_Environment",((e,t)=>{t.push(`vec3 ${e}(const in vec3 viewNormal, const in vec3 viewEyeDir, const in vec3 specularColor, const in float roughness) {`),t.push(` float dotNV = ${Y}(dot(viewNormal, viewEyeDir));`),t.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),t.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),t.push(" vec4 r = roughness * c0 + c1;"),t.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),t.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),t.push(" return specularColor * AB.x + AB.y;"),t.push("}")})),ee=t.createFragmentDefinition("perturbNormal2Arb",((e,t)=>{t.push(`vec3 ${e}( vec3 eye_pos, vec3 surf_norm, vec2 uv, vec4 texel ) {`),t.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),t.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),t.push(" vec2 st0 = dFdx( uv.st );"),t.push(" vec2 st1 = dFdy( uv.st );"),t.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),t.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),t.push(" vec3 N = normalize( surf_norm );"),t.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),t.push(" mat3 tsn = mat3( S, T, N );"),t.push(" return normalize( tsn * mapN );"),t.push("}")}));return{getHash:()=>[e,r.gammaOutput?"go":"",c.getHash(),s._state.hash],programName:"Draw",canActAsBackground:!0,discardPoints:!0,setupPointSize:!0,setsLineWidth:!0,appendFragmentOutputs:(e,t,s)=>{const r=l.normal&&(c.directionalLights.length>0||c.getIrradiance||c.getReflection);if(e.push(`vec3 diffuseColor = ${r&&(A||a)&&D||o&&k||"vec3(1.0)"};`),e.push(`vec4 alphaModeCutoff = ${(A||o||a)&&G||"vec4(1.0, 0.0, 0.0, 0.0)"};`),e.push("float alpha = alphaModeCutoff[0];"),(A||o||a)&&C&&e.push(`alpha *= ${C(W)}.r;`),z&&(e.push(`diffuseColor *= ${z}.rgb;`),e.push(`alpha *= ${z}.a;`)),o&&y&&(e.push("vec4 baseColorTexel = "+y(W)+";"),e.push("diffuseColor *= baseColorTexel.rgb;"),e.push("alpha *= baseColorTexel.a;")),(A||a)&&w&&(e.push("vec4 diffuseTexel = "+w(W)+";"),e.push("diffuseColor *= diffuseTexel.rgb;"),e.push("alpha *= diffuseTexel.a;")),e.push(`vec3 emissiveColor = ${(A||o||a)&&Q||"vec3(0.0)"};`),(A||o||a)&&v&&e.push(`emissiveColor = ${v(W)}.rgb;`),r){e.push(`vec3 specular = ${(A||a)&&R||"vec3(1.0)"};`),e.push(`float glossiness = ${a&&O||"1.0"};`),e.push(`float metallic = ${o&&V||"1.0"};`),e.push(`float roughness = ${(o||a)&&L||"1.0"};`),e.push(`float shininess = ${A&&H||"1.0"};`),e.push(`float specularF0 = ${o&&N||"1.0"};`),e.push(`float occlusion = ${(A||o||a)&&B?`${B(W)}.r`:"1.0"};`),o&&M&&e.push(`metallic *= ${M(W)}.r;`),o&&E&&e.push(`roughness *= ${E(W)}.r;`),o&&F&&(e.push("vec4 metalRoughTexel = "+F(W)+";"),e.push("metallic *= metalRoughTexel.b;"),e.push("roughness *= metalRoughTexel.g;")),(A||a)&&U&&e.push(`specular *= ${U(W)}.rgb;`),a&&x&&e.push(`glossiness *= ${x(W)}.r;`),a&&I&&(e.push("vec4 specGlossTexel = "+I(W)+";"),e.push("specular *= specGlossTexel.rgb;"),e.push("glossiness *= specGlossTexel.a;"));const t=`normalize(${X})`,s=(A||o||a)&&T?`${ee}(${j}, ${t}, ${T.getTexCoordExpression(W)}, ${T(W)})`:t;if(e.push(`vec3 viewNormal = ${s};`),e.push(`vec3 viewEyeDir = normalize(-${j});`),f&&e.push(`diffuseColor *= ${f("viewEyeDir","viewNormal")};`),p&&e.push(`specular *= ${p("viewEyeDir","viewNormal")};`),g&&e.push(`emissiveColor *= ${g("viewEyeDir","viewNormal")};`),m&&e.push(`alpha *= ${m("viewEyeDir","viewNormal")};`),e.push("if (alphaModeCutoff[1] == 1.0 && alpha < alphaModeCutoff[2]) {"),e.push(" discard;"),e.push("}"),e.push("vec3 material_diffuseColor;"),A&&(e.push("material_diffuseColor = diffuseColor;"),e.push("roughness = 0.0;")),a&&(e.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),e.push("material_diffuseColor = diffuseColor * oneMinusSpecularStrength;"),e.push("roughness = clamp(1.0 - glossiness, 0.04, 1.0);")),o&&(e.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),e.push("material_diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),e.push("roughness = clamp(roughness, 0.04, 1.0);"),e.push("specular = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),A||o||a){if(e.push("const float PI = 3.14159265359;"),e.push("vec3 reflDiff = vec3(0.0);"),e.push("vec3 reflSpec = vec3(0.0);"),c.getIrradiance&&e.push(`reflDiff += ${c.getIrradiance(`normalize(${Z})`)};`),c.getReflection){const t="reflect(-viewEyeDir, viewNormal)",s=A?`0.2 * PI * ${c.getReflection(t)}`:function(){const e=`${q}(viewNormal, viewEyeDir, specular, roughness)`,s=`normalize((vec4(${t}, 0.0) * ${i.viewMatrix}).xyz)`;return`${e} * ${c.getReflection(s,"clamp(4.0 - 0.39624 - 0.25 * log2(pow(2.0 / pow(roughness + 0.0001, 2.0) - 2.0, 2.0) + 1.0), 0.0, 4.0)")}`}();e.push(`reflSpec += ${s};`)}c.directionalLights.some((e=>e.shadowParameters))&&(e.push("const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),e.push("const float texelSize = 1.0 / 1024.0;"),e.push("float shadow;"),e.push("float fragmentDepth;")),c.directionalLights.forEach(((t,i)=>{if(t.shadowParameters){const s="0.007";e.push(`fragmentDepth = ${K[i].vShadowPosFromLight}.z - ${s};`),e.push("shadow = 0.0;"),e.push("for (int x = -3; x <= 3; x++) {"),e.push(" for (int y = -3; y <= 3; y++) {"),e.push(` float texelDepth = dot(texture(${t.getShadowMap()}, ${K[i].vShadowPosFromLight}.xy + vec2(x, y) * texelSize), bitShift);`),e.push(" if (fragmentDepth < texelDepth) {"),e.push(" shadow += 1.0;"),e.push(" }"),e.push(" }"),e.push("}"),e.push("shadow /= 9.0;")}e.push(`vec3 lightColor${i} = ${t.getColor()}${t.shadowParameters?" * shadow":""};`),e.push(`vec3 lightDirection${i} = ${t.isWorldSpace?K[i].vViewLightReverseDir:t.getDirection(null,j)};`);const s=`${Y}(dot(viewNormal, lightDirection${i}))`;e.push(`vec3 irradiance${i} = ${s} * lightColor${i};`),e.push(`reflDiff += irradiance${i};`);const r=A?`lightColor${i} * specular * pow(max(dot(reflect(-lightDirection${i}, -viewNormal), viewEyeDir), 0.0), shininess)`:`irradiance${i} * PI * ${$}(lightDirection${i}, viewNormal, viewEyeDir, specular, roughness)`;e.push(`reflSpec += ${r};`)}))}const r=A&&`${c.getAmbientColor()} * diffuseColor`;e.push("vec3 outgoingLight = emissiveColor + occlusion * (reflDiff * material_diffuseColor + reflSpec)"+(r?" + "+r:"")+";")}else e.push(`vec3 ambientColor = ${A&&S||"vec3(1.0)"};`),A&&b&&e.push(`ambientColor *= ${b(W)}.rgb;`),e.push(`ambientColor *= ${c.getAmbientColor()};`),e.push("vec3 outgoingLight = emissiveColor + ambientColor;");e.push(`vec4 fragColor = ${h} * vec4(outgoingLight, alpha);`),e.push(`${J} = ${t?t("fragColor"):"fragColor"};`)}}}(s._state.drawHash,e,t,i,n))),_shadowRenderer:r((e=>function(e,t){const i=t.createFragmentDefinition("encodeFloat",((e,t)=>{t.push(`vec4 ${e}( const in float depth ) {`),t.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),t.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),t.push(" vec4 comp = fract(depth * bitShift);"),t.push(" comp -= comp.xxyz * bitMask;"),t.push(" return comp;"),t.push("}")})),s=t.createOutput("vec4","outColor");return{getHash:()=>[e],programName:"Shadow",setsLineWidth:!0,useShadowView:!0,dontBillboardAnything:!0,dontGetLogDepth:!0,appendFragmentOutputs:(e,t,r)=>e.push(`${s} = ${i}(${r}.z);`)}}(s._state.hash,e))),_emphasisEdgesRenderer:r(A(!1)),_emphasisFillRenderer:r(A(!0)),_pickMeshRenderer:r((e=>function(e,t){const i=t.createUniform("vec4","pickColor",((e,t)=>{var i=t.meshPickID;vi[0]=255&i,vi[1]=i>>8&255,vi[2]=i>>16&255,vi[3]=i>>24&255,d.mulVec4Scalar(vi,1/255,vi),e(vi)})),s=t.createOutput("vec4","outColor");return{getHash:()=>[e],programName:"PickMesh",isPick:!0,dontBillboardAnything:!0,appendFragmentOutputs:e=>e.push(`${s} = ${i};`)}}(s._state.hash,e))),_pickTriangleRenderer:r(((e,t)=>function(e,t,i){const s=t.createVarying("vec4","vColor",(()=>i.attributes.pickColor)),r=t.createOutput("vec4","outColor");return{getHash:()=>[e],programName:"PickTriangle",isPick:!0,trianglePick:!0,dontBillboardAnything:!0,appendFragmentOutputs:e=>e.push(`${r} = ${s};`)}}(s._state.hash,e,t))),_occlusionRenderer:r((e=>function(e,t){const i=t.createOutput("vec4","outColor");return{getHash:()=>[e],programName:"Occlusion",skipIfTransparent:!0,appendFragmentOutputs:e=>e.push(`${i} = vec4(0.0, 0.0, 1.0, 1.0);`)}}(s._state.pickOcclusionHash,e)))},this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=i,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=d.vec3(),this._quaternion=d.identityQuaternion(),this._rotation=d.vec3(),this._position=d.vec3(),this._worldMatrix=d.identityMat4(),this._worldNormalMatrix=d.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const o=t.origin||t.rtcCenter;if(o&&(this._state.origin=d.vec3(o),this._state.originHash=o.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=d.identityMat4()),d.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=d.identityMat4()),this.__localMatrix.set(e||Si),d.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get isUI(){return this._state.isUI}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=d.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this.scene,t=this._state,i=[e.canvas.canvas.id,e._sectionPlanesState.getHash()];t.stationary&&i.push("/s"),"none"===t.billboard?i.push("/n"):"spherical"===t.billboard?i.push("/s"):"cylindrical"===t.billboard&&i.push("/c"),i.push(";");const s=i.concat([e.gammaOutput?"go":"",e._lightsState.getHash(),t.receivesShadow?"/rs":""]).join("");this._state.drawHash!==s&&(this._state.drawHash=s,this._renderers._drawRenderer.put(),this._renderers._shadowRenderer.put(),this._renderers._emphasisFillRenderer.put(),this._renderers._emphasisEdgesRenderer.put(),this._renderers._drawRenderer.get(),this._renderers._emphasisFillRenderer.get(),this._renderers._emphasisEdgesRenderer.get());const r=i.join("");this._state.pickOcclusionHash!==r&&(this._state.pickOcclusionHash=r,this._renderers._pickMeshRenderer.put(),this._renderers._pickTriangleRenderer.put(),this._renderers._pickMeshRenderer.get(),this._state.occluder&&(this._renderers._occlusionRenderer.put(),this._renderers._occlusionRenderer.get()))}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)d.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=d.mat4()),d.transposeMat4(this._worldMatrix,this._worldNormalMatrix),d.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=d.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_buildAABB(e,t){d.transformOBB3(e,this._geometry.obb,Ci),d.OBB3ToAABB3(Ci,t);const i=this._state.offset;if(t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[0],t[4]+=i[1],t[5]+=i[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return Mi[0]=e[0],Mi[1]=e[1],Mi[2]=e[2],Mi[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Mi,Ei),d.mulQuaternions(this.quaternion,Ei,Fi),this.quaternion=Fi,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Mi[0]=e[0],Mi[1]=e[1],Mi[2]=e[2],Mi[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Mi,Ei),d.mulQuaternions(Ei,this.quaternion,Ei),this}rotateX(e){return this.rotate(Ui,e)}rotateY(e){return this.rotate(xi,e)}rotateZ(e){return this.rotate(Ii,e)}translate(e,t){return d.vec3ApplyQuaternion(this.quaternion,e,Ti),d.mulVec3Scalar(Ti,t,Pi),d.addVec3(this.position,Pi,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ui,e)}translateY(e){return this.translate(xi,e)}translateZ(e){return this.translate(Ii,e)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._renderers._drawRenderer.getId()-t._renderers._drawRenderer.getId()||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i],s=this.renderFlags;if(t.active)if(this._state.origin){const e=d.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const r=0===e;s.sectionPlanesActivePerLayer[i]=r}else s.sectionPlanesActivePerLayer[i]=!0;else s.sectionPlanesActivePerLayer[i]=!1}}return!0}drawColorOpaque(e){this._renderers._drawRenderer.drawMesh(e,this,this._material)}drawColorTransparent(e){this._renderers._drawRenderer.drawMesh(e,this,this._material)}drawSilhouetteXRayed(e){this._renderers._emphasisFillRenderer.drawMesh(e,this,this._xrayMaterial)}drawSilhouetteHighlighted(e){this._renderers._emphasisFillRenderer.drawMesh(e,this,this._highlightMaterial)}drawSilhouetteSelected(e){this._renderers._emphasisFillRenderer.drawMesh(e,this,this._selectedMaterial)}drawEdgesColorOpaque(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._edgeMaterial)}drawEdgesColorTransparent(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._edgeMaterial)}drawEdgesXRayed(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._xrayMaterial)}drawEdgesHighlighted(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._highlightMaterial)}drawEdgesSelected(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._selectedMaterial)}drawOcclusion(e){this._renderers._occlusionRenderer.drawMesh(e,this,this._material)}drawShadow(e){this._renderers._shadowRenderer.drawMesh(e,this,this._material)}drawPickMesh(e){this._renderers._pickMeshRenderer.drawMesh(e,this,this._material)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){this._renderers._pickTriangleRenderer.drawMesh(e,this,this._material)}pickTriangleSurface(e,t,i,s){Ri(this,e,t,i,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),Object.values(this._renderers).forEach((e=>e.put())),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Ri=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),n=d.vec3(),A=d.vec4(),o=d.vec3(),a=d.vec3(),l=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),f=d.vec3(),p=d.vec3(),g=d.vec3(),m=d.vec4(),_=d.vec4(),b=d.vec4(),y=d.vec3(),w=d.vec3(),v=d.vec3(),B=d.vec3(),C=d.vec3(),M=d.vec3(),E=d.vec3(),F=d.vec3(),U=d.vec3(),x=d.vec3(),I=d.vec3();return function(T,P,S,D,k){var Q=k.primIndex;if(null!=Q&&Q>-1){const L=T.geometry._state,H=T.scene,N=H.camera,G=H.canvas;if("triangles"===L.primitiveName){k.primitive="triangle";const H=Q,j=L.indices,W=L.positions;let z,X,K;if(j){var R=j[H+0],O=j[H+1],V=j[H+2];n[0]=R,n[1]=O,n[2]=V,k.indices=n,z=3*R,X=3*O,K=3*V}else z=3*H,X=z+3,K=X+3;if(i[0]=W[z+0],i[1]=W[z+1],i[2]=W[z+2],s[0]=W[X+0],s[1]=W[X+1],s[2]=W[X+2],r[0]=W[K+0],r[1]=W[K+1],r[2]=W[K+2],L.compressGeometry){const e=L.positionsDecodeMatrix;e&&(ge.decompressPosition(i,e,i),ge.decompressPosition(s,e,s),ge.decompressPosition(r,e,r))}k.canvasPos?d.canvasPosToLocalRay(G.canvas,T.origin?Je(P,T.origin):P,S,D,T.worldMatrix,k.canvasPos,e,t):k.origin&&k.direction&&d.worldRayToLocalRay(T.worldMatrix,k.origin,k.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,A),k.localPos=A,k.position=A,m[0]=A[0],m[1]=A[1],m[2]=A[2],m[3]=1,d.transformVec4(T.worldMatrix,m,_),o[0]=_[0],o[1]=_[1],o[2]=_[2],k.canvasPos&&T.origin&&(o[0]+=T.origin[0],o[1]+=T.origin[1],o[2]+=T.origin[2]),k.worldPos=o,d.transformVec4(N.matrix,_,b),a[0]=b[0],a[1]=b[1],a[2]=b[2],k.viewPos=a,d.cartesianToBarycentric(A,i,s,r,l),k.bary=l;const Z=L.normals;if(Z){if(L.compressGeometry){const e=3*R,t=3*O,i=3*V;ge.decompressNormal(Z.subarray(e,e+2),c),ge.decompressNormal(Z.subarray(t,t+2),h),ge.decompressNormal(Z.subarray(i,i+2),u)}else c[0]=Z[z],c[1]=Z[z+1],c[2]=Z[z+2],h[0]=Z[X],h[1]=Z[X+1],h[2]=Z[X+2],u[0]=Z[K],u[1]=Z[K+1],u[2]=Z[K+2];const e=d.addVec3(d.addVec3(d.mulVec3Scalar(c,l[0],y),d.mulVec3Scalar(h,l[1],w),v),d.mulVec3Scalar(u,l[2],B),C);k.worldNormal=d.normalizeVec3(d.transformVec3(T.worldNormalMatrix,e,M))}const J=L.uv;if(J){if(f[0]=J[2*R],f[1]=J[2*R+1],p[0]=J[2*O],p[1]=J[2*O+1],g[0]=J[2*V],g[1]=J[2*V+1],L.compressGeometry){const e=L.uvDecodeMatrix;e&&(ge.decompressUV(f,e,f),ge.decompressUV(p,e,p),ge.decompressUV(g,e,g))}k.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(f,l[0],E),d.mulVec2Scalar(p,l[1],F),U),d.mulVec2Scalar(g,l[2],x),I)}}}}}(),Oi=(e,t,i,s,r)=>{const n=r.programVariables,A=i.decodedUv,o=i.worldNormal,a=i.viewNormal,l=e.scene,c=l.canvas.gl,h=e._state.background,u=e._geometry._state,d=u.compressGeometry,f="points"===u.primitiveName,p=n.createUniform("float","pointSize"),g=n.createUniform("mat4","modelMatrix"),m=n.createUniform("mat4","modelNormalMatrix"),_=n.createUniform("vec3","offset"),b=n.createUniform("vec3","scale"),y=n.createUniform("mat4","positionsDecodeMatrix"),w=n.createUniform("mat3","uvDecodeMatrix"),v=n.createUniform("mat4","viewMatrix"),B=n.createUniform("mat4","viewNormalMatrix"),C=n.createUniform("mat4","projMatrix"),M=e.billboard,E=!s.dontBillboardAnything&&("spherical"===M||"cylindrical"===M),F=e.stationary,U=E&&((e,t)=>[`mat4 ${e}(in mat4 matIn) {`," mat4 mat = matIn;",` mat[0].xyz = vec3(${b}[0], 0.0, 0.0);`,..."spherical"===M?[` mat[1].xyz = vec3(0.0, ${b}[1], 0.0);`]:[]," mat[2].xyz = vec3(0.0, 0.0, 1.0);"," return mat;","}"].forEach((e=>t.push(e)))),x=function(){const e=U&&n.createVertexDefinition("billboard",U);return t=>e?`${e}(${t})`:t}(),I=function(){const e=U&&n.createFragmentDefinition("billboard",U);return t=>e?`${e}(${t})`:t}(),T=[];s.dontBillboardAnything?T.push(`mat4 viewMatrix2 = ${v};`):(T.push(`mat4 viewMatrix1 = ${v};`),F?T.push("viewMatrix1[3].xyz = vec3(0.0, 0.0, 0.0);"):h&&T.push("viewMatrix1[3] = vec4(0.0, 0.0, 0.0, 1.0);"),T.push(`mat4 viewMatrix2 = ${I("viewMatrix1")};`));const P="clipPos",S=n.createUniform("bool","clippable"),[D,k]=r.buildProgram(c,s.programName,{appendFragmentOutputs:(e,t,i,r)=>{T.forEach((t=>e.push(t))),s.appendFragmentOutputs(e,t,i,r)},clippableTest:()=>S,clippingCaps:s.clippingCaps,clipPos:h?"clipPos.xyww":P,crossSections:l.crossSections,discardPoints:f&&s.discardPoints,getGammaFactor:l.gammaOutput&&(()=>l.gammaFactor),getLogDepth:!s.dontGetLogDepth&&l.logarithmicDepthBufferEnabled&&(e=>e),getPointSize:s.setupPointSize&&f&&(()=>p),getVertexData:function(){const e=a&&a.needed&&`vec3 ${a} = normalize((${x(B)} * vec4(${o}, 0.0)).xyz);`,i=[];if(i.push(`vec4 localPosition = vec4(${t.position}, 1.0);`),d&&i.push(`localPosition = ${y} * localPosition;`),i.push(`vec4 worldPosition = ${x(g)} * localPosition;`),i.push(`worldPosition.xyz = worldPosition.xyz + ${_};`),s.dontBillboardAnything?i.push(`vec4 viewPosition = ${v} * worldPosition;`):(i.push(`mat4 viewMatrix1 = ${v};`),F?i.push("viewMatrix1[3].xyz = vec3(0.0, 0.0, 0.0);"):h&&i.push("viewMatrix1[3] = vec4(0.0, 0.0, 0.0, 1.0);"),i.push(`mat4 viewMatrix2 = ${x("viewMatrix1")};`),i.push(`vec4 viewPosition = ${E?`${x(`viewMatrix1 * ${g}`)} * localPosition`:"viewMatrix2 * worldPosition"};`)),A&&A.needed&&i.push(`vec2 ${A} = ${d?`(${w} * vec3(${t.uv}, 1.0)).xy`:t.uv};`),o&&o.needed){const e=d?`${n.commonLibrary.octDecode}(${t.normal}.xy)`:t.normal;i.push(`vec3 ${o} = (${x(m)} * vec4(${e}, 0.0)).xyz;`)}return e&&i.push(e),i.push(`vec4 clipPos = ${C} * viewPosition;`),i},projMatrix:C,sectionPlanesState:l._sectionPlanesState,testPerspectiveForGl_FragDepth:!0,usePickClipPos:s.isPick,worldPositionAttribute:"worldPosition"});if(k)return{errors:k};{const e=D.inputSetters;let i=null,r=null;return{destroy:()=>D.destroy(),drawMesh:(n,A,o)=>{if(s.skipIfTransparent&&o.alpha<1)return;const a=o._state,l=A._state,u=A._geometry,d=u._state,f=n.viewParams,M=s.canActAsBackground&&h;n.lastProgramId!==D.id&&(n.lastProgramId=D.id,D.bind(),n.useProgram++,i=null,r=null,M&&c.depthFunc(c.LEQUAL)),a.id!==i&&(n.backfaces!==a.backfaces&&(a.backfaces?c.disable(c.CULL_FACE):c.enable(c.CULL_FACE),n.backfaces=a.backfaces),s.dontSetFrontFace||n.frontface===a.frontface||(c.frontFace(a.frontface?c.CCW:c.CW),n.frontface=a.frontface),s.drawEdges&&n.lineWidth!==a.edgeWidth&&(c.lineWidth(a.edgeWidth),n.lineWidth=a.edgeWidth),s.setsLineWidth&&n.lineWidth!==a.lineWidth&&(c.lineWidth(a.lineWidth),n.lineWidth=a.lineWidth),i=a.id);const E=!s.useShadowView&&A.origin;((t,i)=>{const s=(e,t)=>e.setInputValue&&e.setInputValue(t);s(p,o.pointSize),s(g,A.worldMatrix),s(m,A.worldNormalMatrix),s(_,A.offset),s(b,A.scale),s(y,d.positionsDecodeMatrix),s(w,d.uvDecodeMatrix),s(v,i),s(B,f.viewNormalMatrix),s(C,t),s(S,A.clippable),e.setUniforms(n,{material:o,meshColorize:A.colorize,meshPickID:A._state.pickID,mesh:{origin:A.origin,renderFlags:{sectionPlanesActivePerLayer:A.renderFlags.sectionPlanesActivePerLayer}},view:{far:f.far}})})(f.projMatrix,E?n.getRTCViewMatrix(l.originHash,E):f.viewMatrix);const F=e=>{const i=(e,t)=>{e&&e.setInputValue&&t&&(e.setInputValue(t),n.bindArray++)};i(t.position,(e||d).positionsBuf),i(t.color,d.colorsBuf),i(t.pickColor,e&&e.pickColorsBuf),i(t.uv,d.uvBuf),i(t.normal,d.normalsBuf)};if(s.trianglePick){const e=u._getPickTrianglePositions();d.id!==r&&(F({positionsBuf:e,pickColorsBuf:u._getPickTriangleColors()}),r=d.id),c.drawArrays(d.primitive,0,e.numItems/3)}else if(s.drawEdges){const e=d.primitive===c.TRIANGLES?u._getEdgeIndices():d.primitive===c.LINES&&d.indicesBuf;e&&(d.id!==r&&(F(),e.bind(),n.bindArray++,r=d.id),c.drawElements(c.LINES,e.numItems,e.itemType,0),n.drawElements++)}else d.id!==r&&(F(),d.indicesBuf&&(d.indicesBuf.bind(),n.bindArray++),r=d.id),d.indicesBuf?(c.drawElements(d.primitive,d.indicesBuf.numItems,d.indicesBuf.itemType,0),n.drawElements++):d.positionsBuf&&(c.drawArrays(c.TRIANGLES,0,d.positionsBuf.numItems),n.drawArrays++);M&&c.depthFunc(c.LESS)}}}};class Vi extends D{get type(){return"Material"}constructor(e,t={}){super(e,t),m.memory.materials++}destroy(){super.destroy(),m.memory.materials--}}const Li={opaque:0,mask:1,blend:2},Hi=["opaque","mask","blend"];class Ni extends Vi{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new oe({type:"PhongMaterial",ambient:d.vec3([1,1,1]),diffuse:d.vec3([1,1,1]),specular:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Li[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Hi[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}function Gi(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}function ji(e,t,i=null){let s;const r=t;if(1009===r)return e.UNSIGNED_BYTE;if(1017===r)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===r)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===r)return e.BYTE;if(1011===r)return e.SHORT;if(1012===r)return e.UNSIGNED_SHORT;if(1013===r)return e.INT;if(1014===r)return e.UNSIGNED_INT;if(1015===r)return e.FLOAT;if(1016===r)return e.HALF_FLOAT;if(1021===r)return e.ALPHA;if(1023===r)return e.RGBA;if(1024===r)return e.LUMINANCE;if(1025===r)return e.LUMINANCE_ALPHA;if(1026===r)return e.DEPTH_COMPONENT;if(1027===r)return e.DEPTH_STENCIL;if(1028===r)return e.RED;if(1022===r)return e.RGBA;if(1029===r)return e.RED_INTEGER;if(1030===r)return e.RG;if(1031===r)return e.RG_INTEGER;if(1033===r)return e.RGBA_INTEGER;if(33776===r||33777===r||33778===r||33779===r)if(3001===i){const t=Gi(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===r)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(s=Gi(e,"WEBGL_compressed_texture_s3tc"),null===s)return null;if(33776===r)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===r)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===r)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===r)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===r||35841===r||35842===r||35843===r){const t=Gi(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===r)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===r)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===r)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===r)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===r){const t=Gi(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===r||37496===r){const t=Gi(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===r)return 3001===i?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===r||37809===r||37810===r||37811===r||37812===r||37813===r||37814===r||37815===r||37816===r||37817===r||37818===r||37819===r||37820===r||37821===r){const t=Gi(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===r){const t=Gi(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===r)return 3001===i?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===r?e.UNSIGNED_INT_24_8:1e3===r?e.REPEAT:1001===r?e.CLAMP_TO_EDGE:1004===r||1005===r?e.NEAREST_MIPMAP_LINEAR:1007===r?e.LINEAR_MIPMAP_NEAREST:1008===r?e.LINEAR_MIPMAP_LINEAR:1003===r?e.NEAREST:1006===r?e.LINEAR:null}const Wi=new Uint8Array([0,0,0,1]);class zi{constructor({gl:e,target:t,format:i,type:s,wrapS:r,wrapT:n,wrapR:A,encoding:o,preloadColor:a,premultiplyAlpha:l,flipY:c}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=i||1023,this.type=s||1009,this.internalFormat=null,this.premultiplyAlpha=!!l,this.flipY=!!c,this.unpackAlignment=4,this.wrapS=r||1e3,this.wrapT=n||1e3,this.wrapR=A||1e3,this.encoding=o||3001,this.texture=e.createTexture(),a&&this.setPreloadColor(a),this.allocated=!0}setPreloadColor(e){e?(Wi[0]=Math.floor(255*e[0]),Wi[1]=Math.floor(255*e[1]),Wi[2]=Math.floor(255*e[2]),Wi[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Wi[0]=0,Wi[1]=0,Wi[2]=0,Wi[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let i=0,s=e.length;i<s;i++)t.texImage2D(e[i],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Wi)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Wi);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const i=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let s=!1;i.bindTexture(this.target,this.texture);const r=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);const n=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const A=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);const o=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const a=ji(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,a),a!==i.NEAREST_MIPMAP_NEAREST&&a!==i.LINEAR_MIPMAP_NEAREST&&a!==i.NEAREST_MIPMAP_LINEAR&&a!==i.LINEAR_MIPMAP_LINEAR||(s=!0);const l=ji(i,this.magFilter);l&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,l);const c=ji(i,this.wrapS);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,c);const h=ji(i,this.wrapT);h&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,h);const u=ji(i,this.format,this.encoding),d=ji(i,this.type),f=Xi(i,this.internalFormat,u,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(w.isArray(e)){const t=e,s=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,r=s.length;e<r;e++)i.texImage2D(s[e],0,f,u,d,t[e])}}else i.texImage2D(i.TEXTURE_2D,0,f,u,d,e);s&&i.generateMipmap(this.target),i.bindTexture(this.target,null),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,r),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n),i.pixelStorei(i.UNPACK_ALIGNMENT,A),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,o)}setCompressedData({mipmaps:e,props:t={}}){const i=this.gl,s=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),i.activeTexture(i.TEXTURE0+0),i.bindTexture(this.target,this.texture);let r=e.length>1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const n=ji(i,this.wrapS);n&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,n);const A=ji(i,this.wrapT);if(A&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,A),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ji(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Ki(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Ki(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ji(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ji(i,this.magFilter)));const o=ji(i,this.format,this.encoding),a=ji(i,this.type),l=Xi(i,this.internalFormat,o,a,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,l,e[0].width,e[0].height);for(let t=0,s=e.length;t<s;t++){const s=e[t];1023!==this.format?null!==o?i.compressedTexSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,o,s.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):i.texSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,o,a,s.data)}i.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const i=ji(t,e.minFilter);i&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,i),i!==t.NEAREST_MIPMAP_NEAREST&&i!==t.LINEAR_MIPMAP_NEAREST&&i!==t.NEAREST_MIPMAP_LINEAR&&i!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const i=ji(t,e.magFilter);i&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,i))}if(void 0!==e.wrapS){const i=ji(t,e.wrapS);i&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,i))}if(void 0!==e.wrapT){const i=ji(t,e.wrapT);i&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,i))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function Xi(e,t,i,s,r,n=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let A=i;return i===e.RED&&(s===e.FLOAT&&(A=e.R32F),s===e.HALF_FLOAT&&(A=e.R16F),s===e.UNSIGNED_BYTE&&(A=e.R8)),i===e.RG&&(s===e.FLOAT&&(A=e.RG32F),s===e.HALF_FLOAT&&(A=e.RG16F),s===e.UNSIGNED_BYTE&&(A=e.RG8)),i===e.RGBA&&(s===e.FLOAT&&(A=e.RGBA32F),s===e.HALF_FLOAT&&(A=e.RGBA16F),s===e.UNSIGNED_BYTE&&(A=3001===r&&!1===n?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(A=e.RGBA4),s===e.UNSIGNED_SHORT_5_5_5_1&&(A=e.RGB5_A1)),A!==e.R16F&&A!==e.R32F&&A!==e.RG16F&&A!==e.RG32F&&A!==e.RGBA16F&&A!==e.RGBA32F||Gi(e,"EXT_color_buffer_float"),A}function Ki(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Zi(e){if(!Ji(e.width)||!Ji(e.height)){const t=document.createElement("canvas");t.width=Yi(e.width),t.height=Yi(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Ji(e){return 0==(e&e-1)}function Yi(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class $i extends D{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new oe({texture:new zi({gl:this.scene.canvas.gl}),matrix:d.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=d.vec2([0,0]),this._scale=d.vec2([1,1]),this._rotate=d.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),m.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=d.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=d.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?d.mulMat4(t,i):i),0!==this._rotate&&(i=d.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?d.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Zi(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=Zi(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),m.memory.textures--}}const qi=d.vec3(),es=d.vec3();d.vec3();const ts=d.vec3([0,-1,0]),is=d.vec4([0,0,0,1]);class ss extends D{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new $i(this),this._plane=new Qi(this,{geometry:new be(this,Te({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Ni(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new Qi(this,{geometry:new be(this,Ie({size:1,divisions:10})),material:new Ni(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Ke(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),Ye(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];d.subVec3(t,this.position,qi);const s=-d.dotVec3(i,qi);d.normalizeVec3(i),d.mulVec3Scalar(i,s,es),d.vec3PairToQuaternion(ts,e,is),this._node.quaternion=is}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}}class rs extends Vi{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new oe({type:"LambertMaterial",ambient:d.vec3([1,1,1]),color:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const ns={opaque:0,mask:1,blend:2},As=["opaque","mask","blend"];class os extends Vi{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new oe({type:"MetallicMaterial",baseColor:d.vec4([1,1,1]),emissive:d.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=ns[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return As[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const as={opaque:0,mask:1,blend:2},ls=["opaque","mask","blend"];class cs extends Vi{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new oe({type:"SpecularMaterial",diffuse:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),specular:d.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=as[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return ls[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const hs={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class us extends Vi{get type(){return"EmphasisMaterial"}get presets(){return hs}constructor(e,t={}){super(e,t),this._state=new oe({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),e=e||"default",this._preset===e)return;const t=hs[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(hs).join(", "))}get preset(){return console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),this._preset}destroy(){super.destroy(),this._state.destroy()}}const ds={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class fs extends Vi{get type(){return"EdgeMaterial"}get presets(){return ds}constructor(e,t={}){super(e,t),this._state=new oe({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=ds[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ds).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}class ps extends D{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new oe({edgeColor:d.vec3([0,0,0]),centerColor:d.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}class gs extends D{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=d.vec3(t.pos||[0,0,0]),this._up=d.vec3(t.up||[0,1,0]),this._normal=d.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=d.vec3(),this._rtcPos=d.vec3(),this._imageSize=d.vec2(),this._texture=new $i(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Ke(this,{matrix:d.inverseMat4(d.lookAtMat4v(this._pos,d.subVec3(this._pos,this._normal,d.mat4()),this._up,d.mat4())),children:[this._bitmapMesh=new Qi(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new be(this,Te({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ni(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const ms=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let n=0;n<3;n++)if(s=t[3*e+n],r=t[3*i+n],s!==r)return r-s;return 0}let n=e.slice().sort(r),A=null;for(let e=0,t=n.length;e<t;e++)0!==e&&0===r(n[e],n[e-1])||(A=n[e]),i[n[e]]=A;for(let t=0,r=e.length;t<r;t+=3){const r=i[e[t]],n=i[e[t+1]],A=i[e[t+2]];let o=r,a=n,l=A;if(r>n&&r>A?n>A?(o=r,a=n,l=A):(o=r,a=A,l=n):n>r&&n>A?r>A?(o=n,a=r,l=A):(o=n,a=A,l=r):A>r&&A>n&&(r>n?(o=A,a=r,l=n):(o=A,a=n,l=r)),s[t+0]=[o,a],s[t+1]=[a,l],o>l){const e=l;l=o,o=e}s[t+2]=[l,o]}function o(e,t){let i,s;for(let r=0;r<2;r++)if(i=e[r],s=t[r],s!==i)return s-i;return 0}s=s.slice(0,e.length),s.sort(o);let a=0;for(let e=0;e<s.length;e++)if(0===e||0!==o(s[e],s[e-1])){if(0!==e&&2!==a)return!1;a=1}else a++;return!(s.length>0&&2!==a)},_s=d.vec3(),bs=d.vec3(),ys=d.vec3();class ws{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}setPrimitive(e){this.primitive=e}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get volume(){const e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!ms(t,e))return-1;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],n=3*t[s+1],A=3*t[s+2];_s[0]=e[r],_s[1]=e[r+1],_s[2]=e[r+2],bs[0]=e[n],bs[1]=e[n+1],bs[2]=e[n+2],ys[0]=e[A],ys[1]=e[A+1],ys[2]=e[A+2],d.cross3Vec3(_s,bs,_s),i+=d.dotVec3(_s,ys)}return i/6}}const vs=new ws,Bs=d.vec3(),Cs=d.vec3(),Ms=d.vec3(),Es=d.vec3(),Fs=d.vec3(),Us=d.vec3();class xs{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get surfaceArea(){const e=this.vertices,t=this.indices;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],n=3*t[s+1],A=3*t[s+2];Bs[0]=e[r],Bs[1]=e[r+1],Bs[2]=e[r+2],Cs[0]=e[n],Cs[1]=e[n+1],Cs[2]=e[n+2],Ms[0]=e[A],Ms[1]=e[A+1],Ms[2]=e[A+2],d.subVec3(Bs,Cs,Es),d.subVec3(Ms,Cs,Fs),i+=.5*d.lenVec3(d.cross3Vec3(Es,Fs,Us))}return i}}const Is=new xs,Ts=d.OBB3(),Ps=d.OBB3(),Ss=d.OBB3();class Ds{constructor(e,t,i,s,r,n,A=null,o=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=n,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=d.AABB3(),this._aabbWorldDirty=!1,this.layer=A,this.portionId=o,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this),this._volume=null,this._surfaceArea=null}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbChanged()}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbChanged(),this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex&&this.layer.getEachVertex(this.portionId,e)}getEachIndex(e){this.layer.getEachIndex&&this.layer.getEachIndex(this.portionId,e)}isSolid(){return this.layer.solid}get volume(){if(null!==this._volume)return this._volume;switch(this.layer.primitive){case"solid":case"surface":case"triangles":vs.reset(),vs.setPrimitive(this.layer.primitive),this.getEachVertex((e=>{vs.addVertex(e)})),this.getEachIndex((e=>{vs.addIndex(e)})),this._volume=vs.volume;break;default:this._volume=0}return this._volume}get surfaceArea(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":Is.reset(),this.getEachVertex((e=>{Is.addVertex(e)})),this.getEachIndex((e=>{Is.addIndex(e)})),this._surfaceArea=Is.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}set aabb(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);const t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}get aabb(){return this._aabbWorldDirty&&(d.AABB3ToOBB3(this._aabbLocal,Ts),this.transform?(d.transformOBB3(this.transform.worldMatrix,Ts,Ps),d.transformOBB3(this.model.worldMatrix,Ps,Ss),d.OBB3ToAABB3(Ss,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,Ts,Ps),d.OBB3ToAABB3(Ps,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const ks=1,Qs=4,Rs=8,Os=16,Vs=32,Ls=256,Hs=512,Ns=1024,Gs=2048,js=function(e,t,i,s){const r=s&&e.createUniform("vec4","edgeColor",((e,t)=>e(t.legacyFrameCtx.programColor))),n=t.attributes.color,A=!s&&e.createVarying("vec4","vColor",(()=>`vec4(${n}.rgb * 0.5, ${n}.a)`)),o=e.createOutput("vec4","outColor");return{programName:s?"Edges":"EdgesColor",getLogDepth:i&&(e=>e),renderPassFlag:2,appendFragmentOutputs:e=>e.push(`${o} = ${r||A};`)}},Ws=function(e,t){const i=e.createOutput("vec4","outColor");return{programName:"Occlusion",getLogDepth:!1,renderPassFlag:0,appendFragmentOutputs:e=>e.push(`${i} = vec4(0.0, 0.0, 1.0, 1.0);`)}},zs=function(e,t,i,s){const r=e.createUniform("vec4","silhouetteColor",((e,t)=>e(t.legacyFrameCtx.programColor))),n=e.createVarying("float","vAlpha",(()=>`${t.attributes.color}.a`)),A=e.createOutput("vec4","outColor");return{programName:"Silhouette",getLogDepth:i&&(e=>e),renderPassFlag:1,appendFragmentOutputs:(e,t,i,o)=>{e.push(`${A} = ${s?r:o(`vec4(${r}.rgb, min(${r}.a, ${n}))`)};`)}}},Xs=d.vec2(),Ks=d.vec3(),Zs=d.vec4(),Js=d.mat4(),Ys=d.vec3([0,0,0]),$s=0,qs=1,er=2,tr=3,ir=4,sr=5,rr=6,nr=7,Ar=8,or=9,ar=10,lr=11,cr=e=>[d.safeInv(e[0]),d.safeInv(e[1]),d.safeInv(e[2])],hr=(e,t,i,s,r)=>{const n=!!(e&ks),A=!!(e&Ls),o=!!(e&Hs),a=!!(e&Ns),l=!!(e&Gs),c=!!(e&Rs),h=!!(e&Qs);let u,d;u=!n||h||A||o&&!s.highlightMaterial.glowThrough||a&&!s.selectedMaterial.glowThrough?$s:t?er:qs,d=!n||h?$s:a?ir:o?tr:A?sr:$s;let f=0;f=i&&n&&!h?a?or:o?Ar:A?ar:l?t?nr:rr:$s:$s;const p=n&&!h&&c?lr:$s;r[0]=u,r[1]=d,r[2]=f,r[3]=p},ur=function(){const e={};return function(t,i,s,r,n,A,o,a){const l=[i,"points"===s||"lines"===s?s:"triangles",!!r,!!n,!!A,!!o].join(":");l in e||(e[l]={});const c=e[l],h=t.id;if(!(h in c)){const e=t.canvas.gl,l=function(r,n,A){const o=function(){const A=mi(),o=A.programVariables,l=a(o,n);return r(o,l.geometryParameters,(function(r,a){const c=t.pointsMaterial,h="points"===s&&!n,u=()=>[t._sectionPlanesState.getHash()].concat(h?[c.hash]:[]).concat(r.getHash?r.getHash():[]).join(";"),f=u(),p=()=>f===u(),g=l.geometryParameters,m=r.incrementDrawState,_=r.isShadowProgram,b=g.attributes,y=b.position.world,w="clipPos",[v,B]=A.buildProgram(e,i+" "+s+" "+r.programName,{appendFragmentOutputs:r.appendFragmentOutputs,cleanerEdges:r.cleanerEdges,clipPos:w,clippableTest:function(){const e=o.createVarying("float","vClippable",(()=>`${b.clippable} ? 1.0 : 0.0`),"flat");return()=>`${e} > 0.0`}(),clippingCaps:r.clippingCaps,crossSections:t.crossSections,discardPoints:h&&c.roundPoints,getGammaFactor:t.gammaOutput&&(()=>t.gammaFactor),getLogDepth:r.getLogDepth,getPointSize:function(){const e=[];if(h){const t=o.createUniform("float","pointSize",(e=>e(c.pointSize)));if(c.perspectivePoints){const i=o.createUniform("float","nearPlaneHeight",((e,t)=>e(t.legacyFrameCtx.nearPlaneHeight))),s=`${Math.floor(c.minPerspectivePointSize)}.0`,r=`${Math.floor(c.maxPerspectivePointSize)}.0`;e.push(`clamp((${i} * ${t}) / gl_Position.w, ${s}, ${r})`)}else e.push(t)}else n&&n.vertices&&e.push("1.0");return r.incPointSizeBy10&&"points"===s&&e.push("10.0"),e.length>0&&(()=>e.join(" + "))}(),getVertexData:()=>{const e=b.color,t=b.flags[r.renderPassFlag],i=o.createUniform("int","renderPass",((e,t)=>e(t.renderPass))),n=[`if (${_?`(${t} <= 0) || (${e}.a < 1.0)`:`${t} != ${i}`}) {`," gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"," return;","}"].concat(l.dontCullOnAlphaZero||r.dontCullOnAlphaZero?[]:[`if (${e}.a == 0.0) {`," gl_Position = vec4(0.0, 0.0, 0.0, 1.0);"," return;","}"]).concat(r.filterIntensityRange&&"points"===s&&c.filterIntensity?function(){const t=o.createUniform("vec2","intensityRange",(e=>{Xs[0]=c.minIntensity,Xs[1]=c.maxIntensity,e(Xs)}));return[`if ((${e}.a < ${t}[0]) || (${e}.a > ${t}[1])) {`," gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"," return;","}"]}():[]),A=[];l.ensureColorAndFlagAvailable&&l.ensureColorAndFlagAvailable(A),n.forEach((e=>A.push(e))),l.appendVertexData(A);const a=g.attributes.position.view;return A.push(`vec4 ${a} = ${g.viewMatrix} * ${y};`),A.push(`vec4 clipPos = ${g.projMatrix} * ${a};`),A},projMatrix:g.projMatrix,sectionPlanesState:t._sectionPlanesState,testPerspectiveForGl_FragDepth:"points"!==s&&"lines"!==s||n,usePickClipPos:a,worldPositionAttribute:y});return B?(console.error(B),{getValid:p,destroy:()=>{},drawLayer:(e,t,i)=>{}}):{getValid:p,destroy:()=>v.destroy(),drawLayer:(e,t,i)=>{e.lastProgramId!==v.id&&(e.lastProgramId=v.id,v.bind());const s=t.origin,r=t.model,A=e.viewParams,o=Ks;d.transformPoint3(r.matrix,s,o);const a=A.viewMatrix,c=A.projMatrix;e.snapPickOrigin&&(e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2]);const h={legacyFrameCtx:e,layerTextureSet:t.layerTextureSet,mesh:{layerIndex:t.layerIndex,origin:o,renderFlags:{sectionPlanesActivePerLayer:r.renderFlags.sectionPlanesActivePerLayer}},renderPass:i,view:{eye:A.eye,far:A.far,projMatrix:c,viewMatrix:d.compareVec3(o,Ys)?a:Je(a,o,Js),viewNormalMatrix:A.viewNormalMatrix}};v.inputSetters.setUniforms(e,h),t.drawCalls[n?n.vertices?"drawVertices":"drawEdges":"drawSurface"](v.inputSetters.attributesHash,l.layerTypeInputs,{projMatrix:c,viewMatrix:d.compareVec3(o,Ys)?a:Je(a,o,Js),viewNormalMatrix:A.viewNormalMatrix,eye:A.eye}),m&&e.drawElements++}}}))};let l=A&&o();return{drawLayer:(e,t,i)=>{l||(l=o()),l.drawLayer(e,t,i)},revalidate:e=>{!l||!e&&l.getValid()||(l.destroy(),l=A&&o())}}},u=(e,t)=>l(e,t,!0),f=(e,t)=>l(e,t,!1),p=(e,i,r,n)=>function(e,t,i,s,r,n){const A=e.createVarying("vec4","vColor",(()=>{const e=t.attributes,i="points"===n?`vec4(${e.color}.rgb, 1.0)`:`${e.color}`;return s?`vec4(${[s.getAmbientColor()].concat(s.directionalLights.map((i=>`max(dot(${e.normal.view}, ${i.getDirection(t.viewMatrix,e.position.view)}), 0.0) * ${i.getColor()}`))).join(" + ")}, 1) * ${i}`:i})),o=e.createOutput("vec4","outColor");return{programName:"Color",getHash:()=>[s?s.getHash():"-",r?"sao":"nosao"],cleanerEdges:!0,getLogDepth:i&&(e=>"points"!==n&&"lines"!==n?`${e} + length(vec2(dFdx(${e}), dFdy(${e})))`:e),renderPassFlag:0,appendFragmentOutputs:(e,t,i,s)=>{"points"===n||"lines"===n?e.push(`${o} = ${A};`):(e.push(`vec4 fragColor = ${s(A)};`),e.push(`${o} = ${r?`vec4(fragColor.rgb * ${r.getAmbient(i)}, fragColor.a)`:"fragColor"};`))},filterIntensityRange:!0,incrementDrawState:!0}}(e,i,t.logarithmicDepthBufferEnabled,r,n,s),g=(e,i,s)=>s(function(e,t,i){const s=e.createUniform("float","far",((e,t)=>e(t.legacyFrameCtx.viewParams.far))),r=e.createUniform("float","near",((e,t)=>e(t.legacyFrameCtx.viewParams.near))),n=e.createVarying("vec3","vViewPosition",(()=>`${t.attributes.position.view}.xyz`)),A=e.createOutput("vec4","outPackedDepth"),o=e.createFragmentDefinition("packDepth",((e,t)=>{t.push(`vec4 ${e}(const in float depth) {`),t.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),t.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),t.push(" vec4 res = fract(depth * bitShift);"),t.push(" res -= res.xxyz * bitMask;"),t.push(" return res;"),t.push("}")}));return{programName:"PickDepth",getLogDepth:i&&(e=>e),renderPassFlag:3,incPointSizeBy10:!0,appendFragmentOutputs:e=>{e.push(`float zNormalizedDepth = abs((${r} + ${n}.z) / (${s} - ${r}));`),e.push(`${A} = ${o}(zNormalizedDepth);`)}}}(e,i,t.logarithmicDepthBufferEnabled),!0),m=(e,i,s)=>s(function(e,t,i){const s=e.createVarying("vec4","vPickColor",(()=>`${t.attributes.pickColor} / 255.0`)),r=e.createOutput("vec4","outPickColor");return{programName:"PickMesh",getLogDepth:i&&(e=>e),renderPassFlag:3,incPointSizeBy10:!0,dontCullOnAlphaZero:!0,appendFragmentOutputs:e=>e.push(`${r} = ${s};`)}}(e,i,t.logarithmicDepthBufferEnabled),!0),_=(e,i,s,r)=>s(function(e,t,i,s){const r=e.createVarying("vec3","vWorldPosition",(()=>`${t.attributes.position.world}.xyz`)),n=e.createVarying("vec3","vWorldNormal",(()=>t.attributes.normal.world)),A=e.createOutput("highp ivec4","outNormal");return{programName:s?"PickNormalsFlat":"PickNormals",getLogDepth:i&&(e=>e),renderPassFlag:3,appendFragmentOutputs:e=>{const t=s?`normalize(cross(dFdx(${r}), dFdy(${r})))`:n;e.push(`${A} = ivec4(${t} * float(${d.MAX_INT}), 1.0);`)}}}(e,i,t.logarithmicDepthBufferEnabled,r),!0),b=(e,t,i,s,r)=>i(function(e,t,i,s){const r=e.createUniform("int","layerNumber",((e,t)=>e(t.legacyFrameCtx.snapPickLayerParams.length))),n=e.createUniform("vec3","coordinateScaler",((e,t)=>e(t.legacyFrameCtx.snapPickCoordinateScale))),A=e.createVarying("vec3","vWorldPosition",(()=>`${t.attributes.position.world}.xyz`)),o=e.createVarying("vec4","vPickColor",(()=>t.attributes.pickColor),"flat"),a=e.createOutput("highp ivec4","outCoords",0),l=e.createOutput("highp ivec4","outNormal",1),c=e.createOutput("lowp uvec4","outPickColor",2);return{programName:i?"SnapInit":"Snap",getLogDepth:e=>i?`${e} + length(vec2(dFdx(${e}), dFdy(${e})))`:e,renderPassFlag:3,dontCullOnAlphaZero:!i,appendFragmentOutputs:e=>{e.push(`${a} = ivec4(${A} * ${n}.xyz, ${i?"-":""}${r});`),i&&(e.push(`${l} = ${s?"ivec4(1.0)":`ivec4(normalize(cross(dFdx(${A}), dFdy(${A}))) * float(${d.MAX_INT}), 1.0)`};`),e.push(`${c} = uvec4(${o});`))}}}(e,t,s,r),!0);c[h]="points"===s?{colorRenderers:{"sao-":{vertex:f(((e,t,i)=>i(p(e,t,null,null))))}},occlusionRenderer:f(((e,i,s)=>s(Ws(e,t.logarithmicDepthBufferEnabled)))),pickDepthRenderer:f(g),pickMeshRenderer:f(m),silhouetteRenderer:f(((e,i,s)=>s(zs(e,i,t.logarithmicDepthBufferEnabled,!0)))),snapInitRenderer:f(((e,t,i)=>b(e,t,i,!0,!0))),snapVertexRenderer:f(((e,t,i)=>b(e,t,i,!1,!0)),{vertices:!0})}:"lines"===s?{colorRenderers:{"sao-":{vertex:f(((e,t,i)=>i(p(e,t,null,null))))}},silhouetteRenderer:f(((e,i,s)=>s(zs(e,i,t.logarithmicDepthBufferEnabled,!0)))),snapInitRenderer:f(((e,t,i)=>b(e,t,i,!0,!1))),snapEdgeRenderer:f(((e,t,i)=>b(e,t,i,!1,!1)),{vertices:!1}),snapVertexRenderer:f(((e,t,i)=>b(e,t,i,!1,!1)),{vertices:!0})}:{colorRenderers:function(){const e=e=>_i(e,t._lightsState),i=e=>{const t=e.createUniform("vec4","uSAOParams",((e,t)=>e(t.legacyFrameCtx.saoParams))),i=bi(e,"sampler2D","uOcclusionTexture",3e3,((e,t)=>e(t.legacyFrameCtx.occlusionTexture)));return{getAmbient:e=>{const s=`${t}.w`;return`(smoothstep(${`${t}.z`}, 1.0, dot(${i(`${e}.xy / ${t}.xy`)}, (255. / 256.) / vec4(256. * 256. * 256., 256. * 256., 256., 1.))) * ${s})`}}},s=function(s){const r=(r,n,A)=>function(e,t,i,s,r,n,A){const o=bi(e,"sampler2D","uColorMap",3001,((e,t)=>{const i=t.layerTextureSet.colorTexture;i&&e(i.texture)})),a=n&&e.createUniform("float","materialAlphaCutoff",((e,t)=>e(t.layerTextureSet.alphaCutoff))),l=t.attributes,c=e.createVarying("vec3","vViewPosition",(()=>`${l.position.view}.xyz`)),h=e.createVarying("vec2","vUV",(()=>l.uv)),u=e.createVarying("vec4","vColor",(()=>l.color)),d=e.createOutput("vec4","outColor");return{programName:"ColorTexture",getHash:()=>[s.getHash(),r?"sao":"nosao",!!A,n?"alphaCutoffYes":"alphaCutoffNo"],getLogDepth:i.logarithmicDepthBufferEnabled&&(e=>e),renderPassFlag:0,appendFragmentOutputs:(e,i,n,A)=>{e.push(`vec3 viewNormal = normalize(cross(dFdx(${c}), dFdy(${c})));`),e.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),s.directionalLights.forEach((i=>{e.push(`reflectedColor += max(dot(viewNormal, ${i.getDirection(t.viewMatrix,c)}), 0.0) * ${i.getColor()};`)})),e.push(`vec4 color = vec4(${s.getAmbientColor()} + reflectedColor, 1) * ${A(u)};`),e.push(`vec4 sampleColor = ${o(h)};`),a&&e.push(`if (sampleColor.a < ${a}) { discard; }`),e.push("vec4 colorTexel = color * sampleColor;"),e.push(`${d} = vec4(colorTexel.rgb${r?" * "+r.getAmbient(n):""}, color.a);`),i&&e.push(`${d} = ${i(d)};`)},incrementDrawState:!0}}(r,n,t,e(r),s&&i(r),A,t.gammaOutput);return{PBR:n&&f(((r,n,A)=>A(function(e,t,i,s,r){const n=(t,i,s)=>bi(e,"sampler2D",t,i?3001:3e3,((e,t)=>{const i=s(t.layerTextureSet);i&&e(i.texture)})),A=t.attributes,o=s.getIrradiance,a=n("uColorMap",!0,(e=>e.colorTexture)),l=n("uMetallicRoughMap",!1,(e=>e.metallicRoughnessTexture)),c=n("uEmissiveMap",!0,(e=>e.emissiveTexture)),h=n("uNormalMap",!1,(e=>e.normalsTexture)),u=n("uAOMap",!1,(e=>e.occlusionTexture)),d=e.createVarying("vec3","vViewPosition",(()=>`${A.position.view}.xyz`)),f=e.createVarying("vec3","vViewNormal",(()=>A.normal.view)),p=e.createVarying("vec4","vColor",(()=>A.color)),g=e.createVarying("vec2","vUV",(()=>A.uv)),m=e.createVarying("vec2","vMetallicRoughness",(()=>A.metallicRoughness)),_=e.createVarying("vec3","vWorldNormal",(()=>`${A.normal.world}.xyz`)),b=e.createOutput("vec4","outColor"),y=e.createFragmentDefinition("saturate",((e,t)=>t.push(`float ${e}(const in float a) { return clamp(a, 0.0, 1.0); }`))),w=e.createFragmentDefinition("BRDF_Specular_GGX",((e,t)=>{t.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),t.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),t.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),t.push("}"),t.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),t.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),t.push(" return 1.0 / ( gl * gv );"),t.push("}"),t.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),t.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),t.push(" return 0.5 / max( gv + gl, 1e-6 );"),t.push("}"),t.push("float D_GGX(const in float alpha, const in float dotNH) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),t.push(" return 0.31830988618 * a2 / ( denom * denom);"),t.push("}"),t.push(`vec3 ${e}(const in vec3 incidentLightDirection, const in vec3 viewNormal, const in vec3 viewEyeDir, const in vec3 specularColor, const in float roughness) {`),t.push(" float alpha = ( roughness * roughness );"),t.push(" vec3 halfDir = normalize( incidentLightDirection + viewEyeDir );"),t.push(` float dotNL = ${y}( dot( viewNormal, incidentLightDirection ) );`),t.push(` float dotNV = ${y}( dot( viewNormal, viewEyeDir ) );`),t.push(` float dotNH = ${y}( dot( viewNormal, halfDir ) );`),t.push(` float dotLH = ${y}( dot( incidentLightDirection, halfDir ) );`),t.push(" vec3 F = F_Schlick( specularColor, dotLH );"),t.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),t.push(" float D = D_GGX( alpha, dotNH );"),t.push(" return F * (G * D);"),t.push("}")})),v=e.createFragmentDefinition("BRDF_Specular_GGX_Environment",((e,t)=>{t.push(`vec3 ${e}(const in vec3 viewNormal, const in vec3 viewEyeDir, const in vec3 specularColor, const in float roughness) {`),t.push(` float dotNV = ${y}(dot(viewNormal, viewEyeDir));`),t.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),t.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),t.push(" vec4 r = roughness * c0 + c1;"),t.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),t.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),t.push(" return specularColor * AB.x + AB.y;"),t.push("}")})),B=e.createFragmentDefinition("perturbNormal2Arb",((e,t)=>{t.push(`vec3 ${e}( vec3 eye_pos, vec3 surf_norm, vec2 uv, vec4 texel ) {`),t.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),t.push(" return surf_norm;"),t.push(" }"),t.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),t.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),t.push(" vec2 st0 = dFdx( uv.st );"),t.push(" vec2 st1 = dFdy( uv.st );"),t.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),t.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),t.push(" vec3 N = normalize( surf_norm );"),t.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),t.push(" mat3 tsn = mat3( S, T, N );"),t.push(" return normalize( tsn * mapN );"),t.push("}")}));return{programName:"PBR",getHash:()=>[s.getHash(),r?"sao":"nosao",!!i.gammaOutput],getLogDepth:i.logarithmicDepthBufferEnabled&&(e=>e),renderPassFlag:0,clippingCaps:i._sectionPlanesState.clippingCaps&&b,incrementDrawState:!0,appendFragmentOutputs:(e,i,n)=>{if(e.push("const float PI = 3.14159265359;"),e.push("vec3 reflDiff = vec3(0.0);"),e.push("vec3 reflSpec = vec3(0.0);"),e.push(`vec3 rgb = ${p}.rgb;`),e.push(`float opacity = ${p}.a;`),e.push("vec3 baseColor = rgb;"),e.push("float specularF0 = 1.0;"),e.push(`float metallic = float(${m}.r) / 255.0;`),e.push(`float roughness = float(${m}.g) / 255.0;`),e.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),e.push(`vec4 colorTexel = ${a(g)};`),e.push("baseColor *= colorTexel.rgb;"),e.push(`vec3 metalRoughTexel = ${l(g)}.rgb;`),e.push("metallic *= metalRoughTexel.b;"),e.push("roughness *= metalRoughTexel.g;"),e.push("vec3 diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),e.push("float specularRoughness = clamp(roughness, 0.04, 1.0);"),e.push("vec3 specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),e.push(`vec3 viewNormal = -${B}(${d}, normalize(${f}), ${g}, ${h(g)});`),e.push(`vec3 viewEyeDir = normalize(${d});`),o&&e.push(`reflDiff += ${o(`normalize(${_})`)};`),s.getReflection){const i=`normalize((vec4(reflect(viewEyeDir, viewNormal), 0.0) * ${t.viewMatrix}).xyz)`,r="8.0",n=`0.5 * clamp(${r} - 0.79248 - 0.5 * log2(pow((2.0 / pow(specularRoughness + 0.0001, 2.0) - 2.0), 2.0) + 1.0), 0.0, ${r})`,A=s.getReflection(i,n),o=`${v}(viewNormal, viewEyeDir, specularColor, specularRoughness)`;e.push(`reflSpec += ${A} * ${o};`)}s.directionalLights.forEach(((i,s)=>{e.push(`vec3 lightDirection${s} = -${i.getDirection(t.viewMatrix,d)};`);const r=`${y}(dot(viewNormal, lightDirection${s}))`;e.push(`vec3 irradiance${s} = ${r} * ${i.getColor()};`),e.push(`reflDiff += irradiance${s};`),e.push(`reflSpec += irradiance${s} * PI * ${w}(lightDirection${s}, viewNormal, viewEyeDir, specularColor, specularRoughness);`)})),e.push(`vec3 emissiveColor = ${c(g)}.rgb;`),e.push(`float aoFactor = ${u(g)}.r;`);const A=`${s.getAmbientColor()} * baseColor * opacity * rgb`;e.push(`vec3 outgoingLight = emissiveColor + reflDiff * diffuseColor + reflSpec + ${A};`),e.push(`${b} = vec4(outgoingLight * aoFactor${r?` * ${r.getAmbient(n)}`:""}, opacity);`),i&&e.push(`${b} = ${i(b)};`)}}}(r,n,t,e(r),s&&i(r))))),texture:A&&{"alphaCutoff-":f(((e,t,i)=>i(r(e,t,!1)))),"alphaCutoff+":f(((e,t,i)=>i(r(e,t,!0))))},vertex:f(o?(t,r,n)=>n(p(t,r,e(t),s&&i(t))):(r,n,A)=>A(function(e,t,i,s,r){const n=t.attributes,A=e.createVarying("vec3","vViewPosition",(()=>`${n.position.view}.xyz`)),o=e.createVarying("vec4","vColor",(()=>n.color)),a=e.createOutput("vec4","outColor");return{programName:"FlatColor",getHash:()=>[s.getHash(),r?"sao":"nosao"],cleanerEdges:!0,getLogDepth:i&&(e=>e),renderPassFlag:0,appendFragmentOutputs:(e,i,n,l)=>{e.push(`vec3 viewNormal = normalize(cross(dFdx(${A}), dFdy(${A})));`);const c=[s.getAmbientColor()].concat(s.directionalLights.map((e=>`max(dot(viewNormal, ${e.getDirection(t.viewMatrix,A)}), 0.0) * ${e.getColor()}`)));e.push(`vec4 fragColor = vec4(${c.join(" + ")}, 1) * ${l(o)};`),e.push(`${a} = ${r?`vec4(fragColor.rgb * ${r.getAmbient(n)}, fragColor.a)`:"fragColor"};`)}}}(r,n,t.logarithmicDepthBufferEnabled,e(r),s&&i(r))))}};return{"sao-":s(!1),"sao+":r&&s(!0)}}(),depthRenderer:f(((e,i,s)=>s(function(e,t,i){const s=e.createVarying("highp vec2","vHighPrecisionZW",(()=>`${t.attributes.position.clip}.zw`)),r=e.createOutput("vec4","outColor");return{programName:"Depth",getLogDepth:i&&(e=>e),renderPassFlag:0,appendFragmentOutputs:e=>e.push(`${r} = vec4(vec3((1.0 - ${s}[0] / ${s}[1]) / 2.0), 1.0);`)}}(e,i,t.logarithmicDepthBufferEnabled)))),edgesRenderers:{uniform:f(((e,i,s)=>s(js(e,i,t.logarithmicDepthBufferEnabled,!0))),{vertices:!1}),vertex:f(((e,i,s)=>s(js(e,i,t.logarithmicDepthBufferEnabled,!1))),{vertices:!1})},occlusionRenderer:f(((e,i,s)=>s(Ws(e,t.logarithmicDepthBufferEnabled)))),pickDepthRenderer:u(g),pickMeshRenderer:u(m),pickNormalsFlatRenderer:u(((e,t,i)=>_(e,t,i,!0))),pickNormalsRenderer:u(((e,t,i)=>_(e,t,i,!1))),shadowRenderer:f(((e,i,s)=>s(function(e,t){const i=e.createOutput("vec4","outColor"),s=e.createFragmentDefinition("encodeFloat",((e,t)=>{t.push(`vec4 ${e}(const in float v) {`),t.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),t.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),t.push(" vec4 comp = fract(v * bitShift);"),t.push(" comp -= comp.xxyz * bitMask;"),t.push(" return comp;"),t.push("}")}));return{programName:"Shadow",getLogDepth:t&&(e=>e),renderPassFlag:0,isShadowProgram:!0,appendFragmentOutputs:(e,t,r)=>e.push(`${i} = ${s}(${r}.z);`)}}(e,t)))),silhouetteRenderer:u(((e,i,s)=>s(zs(e,i,t.logarithmicDepthBufferEnabled,!1)))),snapInitRenderer:u(((e,t,i)=>b(e,t,i,!0,!1))),snapEdgeRenderer:u(((e,t,i)=>b(e,t,i,!1,!1)),{vertices:!1}),snapVertexRenderer:u(((e,t,i)=>b(e,t,i,!1,!1)),{vertices:!0})};const y=e=>{!function t(i){i.revalidate?i.revalidate(e):Object.values(i).forEach((e=>e&&t(e)))}(c[h])},w=()=>y(!1);w(),t.on("compile",w),t.on("destroyed",(()=>{delete c[h]}))}return c[h]}}();class dr{constructor(e,t,i){this.model=e,this.primitive=t,this.origin=i,this._meshes=[],this._aabb=d.collapseAABB3(),this._aabbDirty=!0}finalize(){if(!this._compiledPortions){this._compiledPortions=this.compilePortions(),this.solid=this._compiledPortions.solid,this.sortId=this._compiledPortions.sortId,this.layerTextureSet=this._compiledPortions.layerTextureSet,this.drawCalls=this._compiledPortions.drawCalls,this._renderers=this._compiledPortions.renderers,this._setFlags=this._compiledPortions.setFlags,this.setColor=this._compiledPortions.setColor,this.setMatrix=this._compiledPortions.setMatrix,this.setOffset=this._compiledPortions.setOffset,this.getEachIndex=this._compiledPortions.getEachIndex,this.getEachVertex=this._compiledPortions.getEachVertex,this.readGeometryData=this._compiledPortions.readGeometryData,this.precisionRayPickSurface=this._compiledPortions.precisionRayPickSurface,this._countsByFlag={};const e=(e,t)=>{const i={count:0,fromFlags:(s,r)=>{s&e?(i.count++,this.model[t]++):r||(i.count--,this.model[t]--)}};this._countsByFlag[e]=i};e(ks,"numVisibleLayerPortions"),e(Qs,"numCulledLayerPortions"),e(Rs,"numPickableLayerPortions"),e(Os,"numClippableLayerPortions"),e(Ls,"numXRayedLayerPortions"),e(Hs,"numHighlightedLayerPortions"),e(Ns,"numSelectedLayerPortions"),this._renderers.edgesRenderers&&e(Gs,"numEdgesLayerPortions"),this._numTransparentLayerPortions=0}}aabbChanged(){this._aabbDirty=!0}__drawLayer(e,t,i,s){if(this._countsByFlag[Qs].count<this._portions.length&&this._countsByFlag[ks].count>0){const e="points"!==this.primitive&&"lines"!==this.primitive&&[qs,er,lr,tr,ir,sr];if(e&&e.includes(s)){const e=!0;if(t.backfaces!==e){const i=this.model.scene.canvas.gl;i.disable(i.CULL_FACE),t.backfaces=e}}t.textureUnit=0,i.drawLayer(t,this,s)}}__setVec4FromMaterialColorAlpha(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=t,i}__drawColor(e,t,i){if((i?this._numTransparentLayerPortions<this._portions.length:this._numTransparentLayerPortions>0)&&this._countsByFlag[Ls].count<this._portions.length){const s=i&&t.withSAO&&this._renderers.colorRenderers["sao+"]||this._renderers.colorRenderers["sao-"],r=t.pbrEnabled&&s.PBR?s.PBR:t.colorTextureEnabled&&s.texture?s.texture[this.layerTextureSet&&"number"==typeof this.layerTextureSet.alphaCutoff?"alphaCutoff+":"alphaCutoff-"]:s.vertex,n=i?qs:er;this.__drawLayer(e,t,r,n)}}drawColorOpaque(e,t){this.__drawColor(e,t,!0)}drawColorTransparent(e,t){this.__drawColor(e,t,!1)}drawDepth(e,t){const i=this._renderers.depthRenderer;i&&this._numTransparentLayerPortions<this._portions.length&&this._countsByFlag[Ls].count<this._portions.length&&this.__drawLayer(e,t,i,qs)}__drawSilhouette(e,t,i,s){t.programColor=this.__setVec4FromMaterialColorAlpha(i.fillColor,i.fillAlpha,Zs),this.__drawLayer(e,t,this._renderers.silhouetteRenderer,s)}drawSilhouetteXRayed(e,t){this._countsByFlag[Ls].count>0&&this.__drawSilhouette(e,t,this.model.scene.xrayMaterial,sr)}drawSilhouetteHighlighted(e,t){this._countsByFlag[Hs].count>0&&this.__drawSilhouette(e,t,this.model.scene.highlightMaterial,tr)}drawSilhouetteSelected(e,t){this._countsByFlag[Ns].count>0&&this.__drawSilhouette(e,t,this.model.scene.selectedMaterial,ir)}__drawVertexEdges(e,t,i){const s=this._renderers.edgesRenderers&&this._renderers.edgesRenderers.vertex;s&&this._countsByFlag[Gs].count>0&&this.__drawLayer(e,t,s,i)}drawEdgesColorOpaque(e,t){this._compiledPortions.edgesColorOpaqueAllowed()&&this.__drawVertexEdges(e,t,rr)}drawEdgesColorTransparent(e,t){this._numTransparentLayerPortions>0&&this.__drawVertexEdges(e,t,nr)}__drawUniformEdges(e,t,i,s){const r=this._renderers.edgesRenderers&&this._renderers.edgesRenderers.uniform;r&&(t.programColor=this.__setVec4FromMaterialColorAlpha(i.edgeColor,i.edgeAlpha,Zs),this.__drawLayer(e,t,r,s))}drawEdgesHighlighted(e,t){this._countsByFlag[Hs].count>0&&this.__drawUniformEdges(e,t,this.model.scene.highlightMaterial,Ar)}drawEdgesSelected(e,t){this._countsByFlag[Ns].count>0&&this.__drawUniformEdges(e,t,this.model.scene.selectedMaterial,or)}drawEdgesXRayed(e,t){this._countsByFlag[Ls].count>0&&this.__drawUniformEdges(e,t,this.model.scene.xrayMaterial,ar)}__drawPick(e,t,i){i&&this.__drawLayer(e,t,i,lr)}drawPickMesh(e,t){this.__drawPick(e,t,this._renderers.pickMeshRenderer)}drawPickDepths(e,t){this.__drawPick(e,t,this._renderers.pickDepthRenderer)}drawPickNormals(e,t){const i=this._renderers.pickNormalsFlatRenderer;this.__drawPick(e,t,i)}drawSnap(e,t,i){t.snapPickOrigin=[0,0,0],this._aabbDirty&&(d.collapseAABB3(this._aabb),this._meshes.forEach((e=>d.expandAABB3(this._aabb,e.aabb))),this._aabbDirty=!1);const s=this._aabb;t.snapPickCoordinateScale=d.mulVec3Scalar(cr([s[3]-s[0],s[4]-s[1],s[5]-s[2]]),d.MAX_INT);const r=i?this._renderers.snapInitRenderer:"edge"===t.snapMode?this._renderers.snapEdgeRenderer:this._renderers.snapVertexRenderer;this.__drawPick(e,t,r),t.snapPickLayerParams.push({origin:t.snapPickOrigin.slice(),coordinateScale:cr(t.snapPickCoordinateScale)})}drawOcclusion(e,t){const i=this._renderers.occlusionRenderer;i&&this.__drawLayer(e,t,i,qs)}drawShadow(e,t){const i=this._renderers.shadowRenderer;i&&this.__drawLayer(e,t,i,qs)}initFlags(e,t,i){Object.values(this._countsByFlag).forEach((e=>e.fromFlags(t,!0))),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);const s="points"!==this.primitive;this._setFlags(e,t,i,s),this._compiledPortions.setFlags2(e,t,s)}flushInitFlags(){this._compiledPortions.setDeferredFlags()}setVisible(e,t,i){this._countsByFlag[ks].fromFlags(t),this._setFlags(e,t,i)}setCulled(e,t,i){this._countsByFlag[Qs].fromFlags(t),this._setFlags(e,t,i)}setPickable(e,t,i){this._countsByFlag[Rs].fromFlags(t),this._setFlags(e,t,i)}setClippable(e,t){this._countsByFlag[Os].fromFlags(t),this._compiledPortions.setClippableFlags(e,t)}setCollidable(e,t){}setXRayed(e,t,i){this._countsByFlag[Ls].fromFlags(t),this._setFlags(e,t,i)}setHighlighted(e,t,i){this._countsByFlag[Hs].fromFlags(t),this._setFlags(e,t,i)}setSelected(e,t,i){this._countsByFlag[Ns].fromFlags(t),this._setFlags(e,t,i)}setEdges(e,t,i){this._countsByFlag[Gs]&&(this._countsByFlag[Gs].fromFlags(t),this._setFlags(e,t,i))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}destroy(){this._compiledPortions&&this._compiledPortions.destroy()}}let fr=65536,pr=5e6;class gr{constructor(){}set doublePrecisionEnabled(e){d.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return d.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),fr=e}get maxDataTextureHeight(){return fr}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),pr=e}get maxGeometryBatchSize(){return pr}}const mr=e=>{const t=[];for(let i=0;i<e;++i)t.push(i);return t},_r={sizeDataColorsAndFlags:0,sizeDataInstancesMatrices:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(_r,null,4));let e=0;Object.keys(_r).forEach((t=>{t.startsWith("size")&&(e+=_r[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/_r.totalPolygons).toFixed(2)}`);let t={};Object.keys(_r).forEach((i=>{i.startsWith("size")&&(t[i]=`${(_r[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};const br=new gr,yr=br.maxDataTextureHeight,wr=d.vec3(),vr=d.vec3(),Br=d.vec4();d.vec4();const Cr=new Float32Array(16),Mr=new Uint8Array(4),Er=d.identityMat4();class Fr extends dr{constructor(e,t,i){super(e,t,i),_r.numberOfLayers++,this._sortId=`TriDTX-${_r.numberOfLayers}`;const s=e.scene.canvas.gl,r=(e,t)=>{const i=[];let r=0;const A=[];let o=0;const a=[];let l=0;const c=[];let h=0;return{len:()=>o,accumulateIndices:(s,u)=>{const d=s&&s.length>0&&function(){const t=r/3;r+=s.length,i.push(s);const a=s.length/3;return i=>{const s=o;o+=3*a,n.perObjectIndexBaseOffsets.push(s/3-t);for(let e=0;e<a;e+=8)A.push(i);_r[e]+=a,_r.totalPolygons+=a}}(),f=u&&u.length>0&&function(){const e=l/2;l+=u.length,a.push(u);const i=u.length/2;return s=>{const r=h;h+=2*i,n.perObjectEdgeIndexBaseOffsets.push(r/2-e);for(let e=0;e<i;e+=8)c.push(s);_r[t]+=i,_r.totalEdges+=i}}();return _r.numberOfGeometries++,{numTriangles:s?s.length/3:0,accumulateSubPortionId:e=>{d&&d(e),f&&f(e)}}},createDrawers:(e,t)=>{const n=function(t,i){return t.length>0?e([t],t.length,1,s.UNSIGNED_SHORT,"sizeDataTexturePortionIds"):i},u=n(A,{texture:null}),d=r>0&&e(i,r,3,t,"sizeDataTextureIndices"),f=n(c),p=l>0&&e(a,l,2,t,"sizeDataTextureEdgeIndices");return{indices:function(e,t){o>0&&(e.perPrimIndices.setInputValue(d),e.perPrimIdPorIds.setInputValue(u),s.drawArrays(t,0,o))},edges:function(e,t){h>0&&(e.perPrimIndices.setInputValue(p),e.perPrimIdPorIds.setInputValue(f),s.drawArrays(t,0,h))}}}}},n=this._buffer={positionsCompressed:[],lenPositionsCompressed:0,geometry8Bits:r("totalPolygons8Bits","totalEdges8Bits"),geometry16Bits:r("totalPolygons16Bits","totalEdges16Bits"),geometry32Bits:r("totalPolygons32Bits","totalEdges32Bits"),perObjectColors:[],perObjectPickColors:[],perObjectSolid:[],perObjectPositionsDecodeMatrices:[],perObjectInstancePositioningMatrices:[],perObjectVertexBases:[],perObjectIndexBaseOffsets:[],perObjectEdgeIndexBaseOffsets:[]};this._numVertices=0,this._portions=[],this._subPortionReadableGeometries=this.model.scene.readableGeometryEnabled&&{},this._portionToSubPortionsMap=[],this._bucketGeometries={},this._primitive=t}canCreatePortion(e){const t=e.buckets.length;this._portions.length+t>65536&&_r.cannotCreatePortion.because10BitsObjectId++;let i=this._portions.length+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=this._buffer,s=Math.max(t.geometry8Bits.len(),t.geometry16Bits.len(),t.geometry32Bits.len());let r=0,n=0;e.buckets.forEach((e=>{r+=e.positionsCompressed.length/3,n+=e.indices.length/3})),(this._numVertices+r>4096*yr||s+n>4096*yr)&&_r.cannotCreatePortion.becauseTextureSize++,i&&=this._numVertices+r<=4096*yr&&s+n<=4096*yr}return i}createPortion(e,t){const i=this._buffer,s=t.buckets.map(((e,s)=>{const r=(t.geometryId??t.id)+"#"+s;if(!(r in this._bucketGeometries)){const t=(e,t,i)=>{if(e){const s=8*Math.ceil(e.length/t/8)*t,r=new Uint32Array(s);return r.set(e),_r[i]+=2*(r.length-e.length),r}return e};e.indices=t(e.indices,3,"overheadSizeAlignementIndices"),e.edgeIndices=t(e.edgeIndices,2,"overheadSizeAlignementEdgeIndices");const s=e.positionsCompressed;i.positionsCompressed.push(s);const n=s.length/3;this._numVertices+=n;const A=i.lenPositionsCompressed/3;i.lenPositionsCompressed+=s.length,this._bucketGeometries[r]={vertexBase:A,geometryData:function(){const t=e.indices,s=e.edgeIndices;return n<=256?i.geometry8Bits.accumulateIndices(t,s):n<=65536?i.geometry16Bits.accumulateIndices(t,s):i.geometry32Bits.accumulateIndices(t,s)}()}}const n=this._bucketGeometries[r];i.perObjectPositionsDecodeMatrices.push(t.positionsDecodeMatrix),i.perObjectInstancePositioningMatrices.push(t.meshMatrix||Er),i.perObjectSolid.push(!!t.solid),i.perObjectPickColors.push(t.pickColor),i.perObjectVertexBases.push(n.vertexBase);const A=t.colors,o=t.color;i.perObjectColors.push(A?[255*A[0],255*A[1],255*A[2],255]:[o[0],o[1],o[2],t.opacity]);const a=this._portions.length;return this._portions.push({}),n.geometryData.accumulateSubPortionId(a),this._subPortionReadableGeometries&&(this._subPortionReadableGeometries[a]={indices:e.indices,positionsCompressed:e.positionsCompressed,positionsDecodeMatrix:t.positionsDecodeMatrix}),_r.numberOfPortions++,a})),r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(s),this.model.numPortions++,this._meshes.push(e),r}compilePortions(){const e=this._buffer,t=this.model,i=this._portions.length,s=this.origin,r=this._portionToSubPortionsMap,n=this._primitive,A=this._sortId,o=this._subPortionReadableGeometries,a=t.scene,l=a.canvas.gl,c=Ur(l,i,32,l.UNSIGNED_BYTE,512,(t=>{const s=e=>[e>>24&255,e>>16&255,e>>8&255,255&e];for(let r=0;r<i;r++)t.set(e.perObjectColors[r],32*r+0),t.set(e.perObjectPickColors[r],32*r+4),t.set([0,0,0,0],32*r+8),t.set([0,0,0,0],32*r+12),t.set(s(e.perObjectVertexBases[r]),32*r+16),t.set(s(e.perObjectIndexBaseOffsets[r]),32*r+20),t.set(s(e.perObjectEdgeIndexBaseOffsets[r]),32*r+24),t.set([e.perObjectSolid[r]?1:0,0,0,0],32*r+28)}),"sizeDataColorsAndFlags",!0),h=c.textureData,u=function(e,t,i,s,r,n,A){return Ur(l,t,i,s,r,(t=>{for(let i=0,s=0,r=e.length;i<r;i++){const r=e[i];t.set(r,s),s+=r.length}}),n,A)},f=function(e,t,i){const s=e.length;if(0===s)throw"num "+t+" matrices===0";return u(e,s,16,l.FLOAT,512,t,i)},p=f(e.perObjectInstancePositioningMatrices,"sizeDataInstancesMatrices",!0),g=p.textureData,m=f(e.perObjectPositionsDecodeMatrices,"sizeDataPositionDecodeMatrices",!1),_=function(e,t,i,s,r){return u(e,t/i,i,s,4096,r,!1)},b=_(e.positionsCompressed,e.lenPositionsCompressed,3,l.UNSIGNED_SHORT,"sizeDataTexturePositions"),y=e.geometry8Bits.createDrawers(_,l.UNSIGNED_BYTE),w=e.geometry16Bits.createDrawers(_,l.UNSIGNED_SHORT),v=e.geometry32Bits.createDrawers(_,l.UNSIGNED_INT);this._buffer=null;let B=!1,C=!1,M=!1,E=0;const F=()=>{B=!0},U=a.on("rendering",(()=>{C&&(B=!1,C=!1,h.reloadData()),E=0})),x=(e,i)=>{const s=r[e];if(s)for(let e=0,t=s.length;e<t;e++)i(s[e]);else t.error("portion not found: "+e)},I=(e,t,i,s)=>{const r=B||s;r?C=!0:++E>=10&&F(),h.setData(i,e,t,!r)},T=(e,t,i=!1)=>{Mr.set([t&Os?255:0,0,1,2]),x(e,(e=>I(e,3,Mr,i)))};return{edgesColorOpaqueAllowed:()=>!a.logarithmicDepthBufferEnabled||(a._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),a._loggedWarning=!0),!1),sortId:A,setClippableFlags:T,setFlags:(e,t,i,s=!1)=>{hr(t,i,!0,a,Mr),x(e,(e=>I(e,2,Mr,s)))},setFlags2:T,setDeferredFlags:()=>{},setColor:(e,t)=>{Mr.set(t),x(e,(e=>I(e,0,Mr,!1)))},setMatrix:(e,t)=>{x(e,(e=>{const i=B;i?C=!0:++E>=10&&F(),Cr.set(t),g.setData(Cr,e,0,!i)}))},setOffset:(e,t)=>{},getEachIndex:(e,t)=>{o&&x(e,(e=>o[e].indices.forEach((e=>t(e)))))},getEachVertex:(e,i)=>{o&&x(e,(e=>{const r=o[e],n=r.positionsCompressed,A=r.positionsDecodeMatrix,a=Br;for(let e=0,r=n.length;e<r;e+=3)a[0]=n[e],a[1]=n[e+1],a[2]=n[e+2],a[3]=1,d.decompressPosition(a,A),d.mulMat4v4(t.worldMatrix,a,a),d.addVec3(s,a,a),i(a)}))},precisionRayPickSurface:(e,t,i,s,r)=>!1,renderers:ur(a,"dtx",n,t.saoEnabled,!1,!1,!0,((e,t)=>xr(e,!t))),drawCalls:function(){const e=function(e){const i=(e,t)=>e.setInputValue&&e.setInputValue(t);return(r,n,A)=>{i(n.worldMatrix,t.rotationMatrix),i(n.viewMatrix,A.viewMatrix),i(n.projMatrix,A.projMatrix);const o=d.transformPoint3(t.matrix,s,wr);i(n.uCameraEyeRtc,d.subVec3(A.eye,o,vr)),i(n.perObjPosDecode,m),i(n.perVertIdCoords,b),i(n.perObjColsFlags,c),i(n.perObjectMatrix,p),e(n)}},i=function(t){return e((e=>{y.edges(e,t),w.edges(e,t),v.edges(e,t)}))};return{drawVertices:i(l.POINTS),drawEdges:i(l.LINES),drawSurface:e((e=>{const t=l.TRIANGLES;y.indices(e,t),w.indices(e,t),v.indices(e,t)}))}}(),destroy:()=>{M||(a.off(U),M=!0)}}}}const Ur=function(e,t,i,s,r,n,A,o){if(i>4&&i%4>0)throw"Unhandled data size "+i;const a=Math.ceil(i/4),l=i/a,[c,h,u]=function(){switch(s){case e.UNSIGNED_BYTE:return[Uint8Array,...1===l?[e.R8UI,e.RED_INTEGER]:2===l?[e.RG8UI,e.RG_INTEGER]:3===l?[e.RGB8UI,e.RGB_INTEGER]:[e.RGBA8UI,e.RGBA_INTEGER]];case e.UNSIGNED_SHORT:return[Uint16Array,...1===l?[e.R16UI,e.RED_INTEGER]:2===l?[e.RG16UI,e.RG_INTEGER]:3===l?[e.RGB16UI,e.RGB_INTEGER]:[e.RGBA16UI,e.RGBA_INTEGER]];case e.UNSIGNED_INT:return[Uint32Array,...1===l?[e.R32UI,e.RED_INTEGER]:2===l?[e.RG32UI,e.RG_INTEGER]:3===l?[e.RGB32UI,e.RGB_INTEGER]:[e.RGBA32UI,e.RGBA_INTEGER]];case e.FLOAT:return[Float32Array,...1===l?[e.R32F,e.RED]:2===l?[e.RG32F,e.RG]:3===l?[e.RGB32F,e.RGB]:[e.RGBA32F,e.RGBA]];default:throw"Unhandled data type "+s}}(),d=r*a,f=Math.ceil(t/r);if(0===f)throw"texture height===0";const p=new c(d*f*l);_r[A]+=p.byteLength,_r.numberOfTextures++,n(p);const g=e.createTexture();return e.bindTexture(e.TEXTURE_2D,g),e.texStorage2D(e.TEXTURE_2D,1,h,d,f),e.texSubImage2D(e.TEXTURE_2D,0,0,0,d,f,u,s,p),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),{bind:t=>(e.activeTexture(e["TEXTURE"+t]),e.bindTexture(e.TEXTURE_2D,g),!0),unbind(e){},textureData:o&&{setData(t,n,A=0,o=!1){if(p.set(t,n*i+A*l),o){e.bindTexture(e.TEXTURE_2D,g);const i=n%r*a+A,o=Math.floor(n/r),c=t.length/l;e.texSubImage2D(e.TEXTURE_2D,0,i,o,c,1,u,s,t)}},reloadData(){e.bindTexture(e.TEXTURE_2D,g),e.texSubImage2D(e.TEXTURE_2D,0,0,0,d,f,u,s,p)}}}},xr=function(e,t){const i=(t,i)=>{const s=e.createUniform(t,i),r=e=>`texelFetch(${s}, ${e}, 0)`;return r.map=s,r},s=i("highp usampler2D","perPrimIndices"),r=i("mediump usampler2D","perPrimIdPorIds"),n=i("highp sampler2D","perObjPosDecode"),A=i("mediump usampler2D","perVertIdCoords"),o=i("lowp usampler2D","perObjColsFlags"),a=i("highp sampler2D","perObjectMatrix"),l=e.createUniform("mat4","worldMatrix"),c=e.createUniform("mat4","viewMatrix"),h=e.createUniform("mat4","projMatrix"),u=e.createUniform("vec3","uCameraEyeRtc"),d=function(e){const t={toString:()=>(t.needed=!0,e)};return t},f=d("colorA"),p=d("pickColor"),g=d("worldNormal"),m=d("viewNormal"),_=e=>o(`ivec2(objectIndexCoords.x*8+${e}, objectIndexCoords.y)`);return{geometryParameters:{attributes:{clippable:"(flags2.r > 0u)",color:f,flags:mr(4).map((e=>`int(flags[${e}])`)),metallicRoughness:null,normal:{view:m,world:g},pickColor:p,position:{clip:"gl_Position",view:"viewPosition",world:"worldPosition"},uv:null},projMatrix:h,viewMatrix:c},ensureColorAndFlagAvailable:e=>{e.push("int primitiveIndex = gl_VertexID / "+(t?3:2)+";"),e.push("int h_packed_object_id_index = (primitiveIndex >> 3) & 4095;"),e.push("int v_packed_object_id_index = (primitiveIndex >> 3) >> 12;"),e.push(`int objectIndex = int(${r("ivec2(h_packed_object_id_index, v_packed_object_id_index)")}.r);`),e.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),e.push(`uvec4 flags = ${_(2)};`),e.push(`uvec4 flags2 = ${_(3)};`),f.needed&&e.push(`vec4 ${f} = vec4(${_(0)}) / 255.0;`)},appendVertexData:e=>{const i=e=>a(`ivec2(objectIndexCoords.x*4+${e}, objectIndexCoords.y)`);e.push(`mat4 objectInstanceMatrix = mat4(${i(0)}, ${i(1)}, ${i(2)}, ${i(3)});`);const r=e=>n(`ivec2(objectIndexCoords.x*4+${e}, objectIndexCoords.y)`);if(e.push(`mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4(${r(0)}, ${r(1)}, ${r(2)}, ${r(3)});`),e.push(`ivec4 packedVertexBase = ivec4(${_(4)});`),e.push(`ivec4 packedIndexBaseOffset = ivec4(${_(t?5:6)});`),e.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),e.push("int h_index = (primitiveIndex - indexBaseOffset) & 4095;"),e.push("int v_index = (primitiveIndex - indexBaseOffset) >> 12;"),e.push(`ivec3 vertexIndices = ivec3(${s("ivec2(h_index, v_index)")});`),e.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),t){e.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),e.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),e.push(`uint solid = ${_(7)}.r;`);const t=e=>`vec3(${A(`ivec2(indexPositionH[${e}], indexPositionV[${e}])`)})`;e.push(`vec3 positions[] = vec3[](${t(0)}, ${t(1)}, ${t(2)});`),e.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),e.push("vec3 position = positions[gl_VertexID % 3];"),g.needed&&e.push(`vec3 worldNormal = -normalize((transpose(inverse(${l} * objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);`),m.needed&&e.push(`vec3 viewNormal = -normalize((transpose(inverse(${c} * objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);`),e.push("if (solid != 1u) {"),e.push(` if (${o=h,`(${o}[2][3] == - 1.0)`}) {`),e.push(` vec3 uCameraEyeRtcInQuantizedSpace = (inverse(${l} * objectDecodeAndInstanceMatrix) * vec4(${u}, 1)).xyz;`),e.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),e.push(" position = positions[2 - (gl_VertexID % 3)];"),g.needed&&e.push(" worldNormal = -worldNormal;"),m.needed&&e.push(" viewNormal = -viewNormal;"),e.push(" }"),e.push(" } else {"),m.needed||e.push(` vec3 viewNormal = -normalize((transpose(inverse(${c} * objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);`),e.push(" if (viewNormal.z < 0.0) {"),e.push(" position = positions[2 - (gl_VertexID % 3)];"),g.needed&&e.push(" worldNormal = -worldNormal;"),m.needed&&e.push(" viewNormal = -viewNormal;"),e.push(" }"),e.push(" }"),e.push("}")}else e.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),e.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),e.push(`vec3 position = vec3(${A("ivec2(indexPositionH, indexPositionV)")});`);var o;p.needed&&e.push(`vec4 pickColor = vec4(${_(1)});`),e.push(`vec4 worldPosition = ${l} * (objectDecodeAndInstanceMatrix * vec4(position, 1.0));`)},layerTypeInputs:{perPrimIndices:s.map,perPrimIdPorIds:r.map,perObjPosDecode:n.map,perVertIdCoords:A.map,perObjColsFlags:o.map,perObjectMatrix:a.map,worldMatrix:l,viewMatrix:c,projMatrix:h,uCameraEyeRtc:u}}},Ir=d.mat4(),Tr=d.mat4();function Pr(e,t,i){const s=e.length,r=new Uint16Array(s),n=t[0],A=t[1],o=t[2],a=t[3]-n,l=t[4]-A,c=t[5]-o,h=65525,u=h/a,f=h/l,p=h/c,g=e=>e>=0?e:0;for(let t=0;t<s;t+=3)r[t+0]=Math.floor(g(e[t+0]-n)*u),r[t+1]=Math.floor(g(e[t+1]-A)*f),r[t+2]=Math.floor(g(e[t+2]-o)*p);return d.identityMat4(Ir),d.translationMat4v(t,Ir),d.identityMat4(Tr),d.scalingMat4v([a/h,l/h,c/h],Tr),d.mulMat4(Ir,Tr,i),r}function Sr(e,t){const i=e[0],s=e[1],r=e[2],n=e[3]-i,A=e[4]-s,o=e[5]-r,a=65525;return d.identityMat4(Ir),d.translationMat4v(e,Ir),d.identityMat4(Tr),d.scalingMat4v([n/a,A/a,o/a],Tr),d.mulMat4(Ir,Tr,t),t}function Dr(e,t,i){let s=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),r=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=s,t=r;e=(1-Math.abs(r))*(s>=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function kr(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const Qr=new Float32Array(1),Rr=new Float32Array(4),Or=new Float32Array(3),Vr=d.mat4(),Lr=d.vec4([0,0,0,1]),Hr=d.vec4(),Nr=d.vec3(),Gr=d.vec3(),jr=d.vec3(),Wr=d.vec3(),zr=d.vec3(),Xr=d.vec3(),Kr=d.vec3(),Zr=new Uint8Array(4),Jr=new Float32Array(96),Yr=function(e){const t=[];for(let i=0;i<e;++i)t.push(i);return t},$r=function(e,t){e.set(t);let i=t.length;const s=e.length;for(;i<s;){const t=Math.min(i,s-i);e.set(e.subarray(0,t),i),i+=t}},qr=function(){let e=0;const t=new Map;return{acquire:()=>e++,release:()=>{e--,0===e&&t.clear()},getTypeArray:function(e,i){t.has(e)||t.set(e,{});const s=t.get(e);return i in s||(s[i]=new e(i)),s[i]}}}();class en extends dr{constructor(e,t,i,s){super(e,t,i);const r=!!s.geometry;this._maxVerts=s.maxGeometryBatchSize;const n=r?s.geometry.positionsDecodeMatrix:s.positionsDecodeMatrix;this._positionsDecodeMatrix=n&&d.mat4(n),this._cfgUvDecodeMatrix=s.uvDecodeMatrix&&d.mat3(s.uvDecodeMatrix),this._instancedGeometry=s.geometry,this._textureSet=s.textureSet,this._modelAABB=!r&&d.collapseAABB3(),this._portions=[];const A=function(){let e=0;const t=[];return{length:()=>e,append:function(i,s=1,r=1,n=0){e+=s*i.length,t.push({data:i,times:s,denormalizeScale:r,increment:n})},compileBuffer:function(e){let i=0;t.forEach((e=>{i+=e.times*e.data.length}));const s=new e(i);let r=0;return t.forEach((e=>{const t=e.data,i=e.denormalizeScale,n=e.increment,A=s.subarray(r);if(1===i&&0===n)A.set(t);else for(let e=0;e<t.length;++e)A[e]=n+t[e]*i;let o=t.length;const a=e.times*t.length;for(;o<a;){const e=Math.min(o,a-o);A.set(A.subarray(0,e),o),o+=e}r+=o})),s}}};this._buffer={colors:A(),metallicRoughness:A(),pickColors:A(),...r?{modelMatrixCol:[A(),A(),A()],modelNormalMatrixCol:[A(),A(),A()]}:{positions:A(),indices:A(),uv:A(),normals:A(),edgeIndices:A()}}}canCreatePortion(e,t){return this._instancedGeometry||this._buffer.positions.length()+e<=3*this._maxVerts&&this._buffer.indices.length()+t<=3*this._maxVerts}createPortion(e,t){const i=this._buffer,s=this._instancedGeometry,r=this.model,n=this._portions.length,A=this.primitive,o=!!this._positionsDecodeMatrix,a=r.scene,l=t.meshMatrix,c=(s,o,l,c,h)=>{const u=this._portions.length>0&&this._portions[this._portions.length-1],f={indicesBaseIndex:u?u.indicesBaseIndex+u.numIndices:0,numIndices:l?l.length:0,portionBase:s,portionSize:o,retainedGeometry:a.readableGeometryEnabled&&"points"!==A&&"lines"!==A&&{indices:l,quantizedPositions:c,offset:a.entityOffsetsEnabled&&d.vec3(),matrix:h&&h.slice(),inverseMatrix:null,normalMatrix:null}};return"points"!==A&&"lines"!==A&&i.metallicRoughness.append([t.metallic??0,t.roughness??255],o),"lines"!==A&&i.pickColors.append(t.pickColor.slice(0,4),o),this._portions.push(f),r.numPortions++,this._meshes.push(e),n};if(s){if(i.modelMatrixCol.forEach(((e,t)=>e.append([l[t+0],l[t+4],l[t+8],l[t+12]]))),"points"!==A){const e=t.color;i.colors.append([e[0],e[1],e[2],t.opacity??255])}if("points"!==A&&"lines"!==A&&s.normals){const e=d.inverseMat4(d.transposeMat4(l,d.mat4()));i.modelNormalMatrixCol.forEach(((t,i)=>t.append([e[i+0],e[i+4],e[i+8],e[i+12]])))}return c(n,1,s.indices,s.positionsCompressed,l)}{const e=i.positions.length()/3,s=o?t.positionsCompressed:t.positions;if(!s)throw(o?"positionsCompressed":"positions")+" expected";i.positions.append(s);const r=s.length/3,n=t.indices;n&&i.indices.append(n,1,1,e);const a=t.normalsCompressed,h=t.normals;if(a&&a.length>0)i.normals.append(a);else if(h&&h.length>0){const e=Vr;l?(d.transposeMat4(l,e),d.inverseMat4(e,e)):d.identityMat4(e);const t=[];!function(e,t,i,s,r){function n(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let A,o,a,l,c,h,u=new Float32Array([0,0,0,0]),f=new Float32Array([0,0,0,0]);for(h=0;h<i;h+=3)u[0]=t[h],u[1]=t[h+1],u[2]=t[h+2],d.transformVec3(e,u,f),d.normalizeVec3(f,f),a=A=Dr(f,"floor","floor"),o=kr(A),l=c=n(f,o),A=Dr(f,"ceil","floor"),o=kr(A),l=n(f,o),l>c&&(a=A,c=l),A=Dr(f,"floor","ceil"),o=kr(A),l=n(f,o),l>c&&(a=A,c=l),A=Dr(f,"ceil","ceil"),o=kr(A),l=n(f,o),l>c&&(a=A,c=l),s[r+h+0]=a[0],s[r+h+1]=a[1],s[r+h+2]=0}(e,h,h.length,t,0),i.normals.append(t)}const u=t.colors,f=t.colorsCompressed,p=t.color;if(u)if("points"===A)i.colors.append(u,1,255);else{const e=[];for(let t=0,i=u.length;t<i;t+=3)e.push(255*u[t]),e.push(255*u[t+1]),e.push(255*u[t+2]),e.push(255);i.colors.append(e)}else if(f)if("points"===A)i.colors.append(f);else{const e=[];for(let t=0,i=f.length;t<i;t+=3)e.push(f[t]),e.push(f[t+1]),e.push(f[t+2]),e.push(255);i.colors.append(e)}else p&&i.colors.append([p[0],p[1],p[2],"points"===A?1:t.opacity],r);const g=e=>e&&e.length>0&&e,m=g(t.uv)||g(t.uvCompressed);m&&i.uv.append(m);const _=t.edgeIndices;return _&&i.edgeIndices.append(_,1,1,e),d.expandAABB3(this._modelAABB,t.aabb),c(e,r,n)}}compilePortions(){const e=this._buffer,t=this._instancedGeometry,i=this.model,s=this._modelAABB,r=this.origin,n=this._portions,A=this.primitive,o=this._textureSet;let a=this._positionsDecodeMatrix;const l=this._cfgUvDecodeMatrix,c=i.scene,h=c.canvas.gl,u=!!t,f=[],p=(e,t,i,s)=>{if(t.length>0){const r=t.constructor,[n,A]={[Uint8Array]:[1,h.UNSIGNED_BYTE],[Int8Array]:[1,h.BYTE],[Uint16Array]:[2,h.UNSIGNED_SHORT],[Int16Array]:[2,h.SHORT],[Uint32Array]:[4,h.UNSIGNED_INT],[Int32Array]:[4,h.INT],[Float32Array]:[4,h.FLOAT]}[r],o=h.createBuffer();f.push((()=>h.deleteBuffer(o)));const a=()=>h.bindBuffer(e,o),l=t=>{a(),h.bufferData(e,t,s)};l(t);const c=t.BYTES_PER_ELEMENT,u=t.length/i;return{bindBuffer:a,getData:(t=0,s=u-t)=>{a();const A=new r(s*i);return h.getBufferSubData(e,t*n*i,A,0,s*i),A},numItems:u,setData:l,setSubData:(t,i)=>{a(),h.bufferSubData(e,i*c,t)},type:A}}return null},g=(e,t,i,s=!1,r=!1)=>{const n=p(h.ARRAY_BUFFER,e,t,i);return n&&{getData:n.getData,numItems:n.numItems,setData:n.setData,setSubData:n.setSubData,attributeDivisor:s&&1,bindAtLocation:e=>{n.bindBuffer(),h.vertexAttribPointer(e,t,n.type,!!r,0,0)}}},m=e=>{const t=p(h.ELEMENT_ARRAY_BUFFER,e,1,h.STATIC_DRAW);return t&&{getData:t.getData,bindIndicesBuffer:t.bindBuffer,indicesCount:e.length,indicesType:t.type}},_=n.reduce(((e,t)=>e+t.portionSize),0),b=g(new Float32Array(_),1,h.DYNAMIC_DRAW,u),y=(e,t)=>g(e,4,t,u&&"points"!==A,!0),w=u&&t.colorsCompressed?y(new Uint8Array(t.colorsCompressed),h.STATIC_DRAW):y(e.colors.compileBuffer(Uint8Array),h.DYNAMIC_DRAW),v=c.entityOffsetsEnabled&&g(new Float32Array(3*_),3,h.DYNAMIC_DRAW,u),B=g(e.metallicRoughness.compileBuffer(Uint8Array),2,h.STATIC_DRAW,u),C=g(e.pickColors.compileBuffer(Uint8Array),4,h.STATIC_DRAW,u),M=m(u?new Uint32Array(t.edgeIndices):e.edgeIndices.compileBuffer(Uint32Array)),E=u?"points"!==A&&t.indices&&new Uint32Array(t.indices):e.indices.compileBuffer(Uint32Array),F=E&&m(E),U=u?t.positionsCompressed:a?e.positions.compileBuffer(Uint16Array):Pr(e.positions.compileBuffer(Float64Array),s,a=d.mat4()),x=U&&g(U,3,h.STATIC_DRAW);u||n.forEach((e=>{if(e.retainedGeometry){const t=3*e.portionBase;e.retainedGeometry.quantizedPositions=U.subarray(t,t+3*e.portionSize)}}));const I=u&&e.modelMatrixCol.map((e=>g(e.compileBuffer(Float32Array),4,h.STATIC_DRAW,!0))),T=!u&&e.normals.compileBuffer(Int8Array),P=T&&g(T,3,h.STATIC_DRAW,!1,!0),S=I&&P&&e.modelNormalMatrixCol.map((e=>g(e.compileBuffer(Float32Array),4,h.STATIC_DRAW,!0))),D=u?"points"!==A&&"lines"!==A&&t.uvCompressed&&{buf:g(t.uvCompressed,2,h.STATIC_DRAW),mat:t.uvDecodeMatrix}:function(){const t=e.uv.compileBuffer(Float32Array);if(0===t.length)return null;if(l)return{buf:g(t,2,h.STATIC_DRAW),mat:l};{const e=ge.getUVBounds(t),i=ge.compressUVs(t,e.min,e.max);return{buf:g(i.quantized,2,h.STATIC_DRAW),mat:d.mat3(i.decodeMatrix)}}}();this._buffer=null,qr.acquire(),f.push((()=>qr.release()));let k=null;const Q=(e,i,s,r=!1)=>{hr(i,s,"points"!==A&&"lines"!==A,c,Zr);const o=i&Os?1:0;let a=0;a|=Zr[0],a|=Zr[1]<<4,a|=Zr[2]<<8,a|=Zr[3]<<12,a|=o<<16,Qr[0]=a;const l=n[e],h=l.portionBase,u=l.portionSize;if(r&&!t)k||(k=new Float32Array(_)),$r(k.subarray(h,h+u),Qr);else if(b){const e=qr.getTypeArray(Float32Array,u);$r(e,Qr),b.setSubData(e,h)}},R="solid"===A;return{edgesColorOpaqueAllowed:()=>!0,solid:R,sortId:("points"===A?"Points":"lines"===A?"Lines":"Triangles")+(u?"Instancing":"Batching")+"Layer"+("points"!==A&&"lines"!==A?(R?"-solid":"-surface")+"-autoNormals"+(u?"":(o&&o.colorTexture?"-colorTexture":"")+(o&&o.metallicRoughnessTexture?"-metallicRoughnessTexture":"")):""),setClippableFlags:Q,setFlags:Q,setFlags2:(e,t,i)=>{},setDeferredFlags:()=>{k&&(b.setData(k),k=null)},setColor:(e,t)=>{if(w){const i=n[e],s=qr.getTypeArray(Uint8Array,4*i.portionSize);$r(s,t.slice(0,4)),w.setSubData(s,4*i.portionBase)}},setMatrix:(e,t)=>{I&&I.forEach(((i,s)=>{Rr[0]=t[s+0],Rr[1]=t[s+4],Rr[2]=t[s+8],Rr[3]=t[s+12],i.setSubData(Rr,4*e)}))},setOffset:(e,t)=>{if(c.entityOffsetsEnabled){const i=n[e];if(v){Or.set(t);const e=qr.getTypeArray(Float32Array,3*i.portionSize);$r(e,Or),v.setSubData(e,3*i.portionBase)}i.retainedGeometry&&i.retainedGeometry.offset.set(t)}else i.error("Entity#offset not enabled for this Viewer")},getEachIndex:(e,t)=>{const i=n[e].retainedGeometry;i&&i.indices.forEach((e=>t(e)))},getEachVertex:(e,t)=>{const s=n[e].retainedGeometry;if(s){const e=Hr;r?e.set(r,0):e[0]=e[1]=e[2]=0,e[3]=1;const n=i.matrix;d.mulMat4v4(n,e,e);const A=s.quantizedPositions,o=Lr;for(let i=0,r=A.length;i<r;i+=3)o[0]=A[i],o[1]=A[i+1],o[2]=A[i+2],d.decompressPosition(o,a),s.matrix&&d.transformPoint3(s.matrix,o,o),o[3]=1,d.mulMat4v4(n,o,o),d.addVec3(e,o,o),t(o)}},readGeometryData:"points"!==A&&"lines"!==A&&(e=>{const t=!u&&n[e],s=t?F.getData(t.indicesBaseIndex,t.numIndices).map((e=>e-t.portionBase)):F.getData(),A=i.matrix,o=d.vec4();o.set(r,0),o[3]=1,d.mulMat4v4(A,o,o);const l=I&&d.mat4();if(l){const t=I[0].getData(e,1),i=I[1].getData(e,1),s=I[2].getData(e,1);l.set([t[0],i[0],s[0],0,t[1],i[1],s[1],0,t[2],i[2],s[2],0,t[3],i[3],s[3],1])}const c=d.mat4();d.mulMat4(A,l?d.mulMat4(l,a,c):a,c),c[12]+=o[0],c[13]+=o[1],c[14]+=o[2];const h=t?x.getData(t.portionBase,t.portionSize):x.getData();return{indices:s,positions:d.transformPositions3(c,h,new Float64Array(h.length))}}),precisionRayPickSurface:(e,t,s,A,o)=>{const l=n[e].retainedGeometry;if(l){l.matrix&&!l.inverseMatrix&&(l.inverseMatrix=d.inverseMat4(l.matrix,d.mat4())),o&&l.inverseMatrix&&!l.normalMatrix&&(l.normalMatrix=d.transposeMat4(l.inverseMatrix,d.mat4()));const e=l.quantizedPositions,n=l.indices,c=l.offset,h=Nr,u=Gr;h.set(r?d.subVec3(t,r,jr):t),u.set(s),c&&d.subVec3(h,c),d.transformRay(i.worldNormalMatrix,h,u,h,u),l.inverseMatrix&&d.transformRay(l.inverseMatrix,h,u,h,u);const f=Wr,p=zr,g=Xr;let m=!1,_=0;const b=Kr;for(let s=0,y=n.length;s<y;s+=3){const y=3*n[s],w=3*n[s+1],v=3*n[s+2];if(f[0]=e[y],f[1]=e[y+1],f[2]=e[y+2],p[0]=e[w],p[1]=e[w+1],p[2]=e[w+2],g[0]=e[v],g[1]=e[v+1],g[2]=e[v+2],d.decompressPosition(f,a),d.decompressPosition(p,a),d.decompressPosition(g,a),d.rayTriangleIntersect(h,u,f,p,g,b)){l.matrix&&d.transformPoint3(l.matrix,b,b),d.transformPoint3(i.worldMatrix,b,b),c&&d.addVec3(b,c),r&&d.addVec3(b,r);const e=Math.abs(d.lenVec3(d.subVec3(b,t,[])));(!m||e>_)&&(_=e,A.set(b),o&&d.triangleNormal(f,p,g,o),m=!0)}}return m&&o&&(l.normalMatrix&&d.transformVec3(l.normalMatrix,o,o),d.transformVec3(i.worldNormalMatrix,o,o),d.normalizeVec3(o)),m}return!1},layerTextureSet:o,renderers:ur(c,u?"instancing":"batching",A,i.saoEnabled,i.pbrEnabled&&D&&o&&o.colorTexture&&P&&B&&o.metallicRoughnessTexture,i.colorTextureEnabled&&D&&o&&o.colorTexture,!!P,(e=>sn(e,u&&{hasModelNormalMat:!!S},c.entityOffsetsEnabled))),drawCalls:function(){const e={},t=t=>(s,r,o)=>{let l=0;Jr.set(i.rotationMatrix,0),Jr.set(o.viewMatrix,l+=16),Jr.set(o.projMatrix,l+=16),Jr.set(a,l+=16),r.needNormal()&&(Jr.set(i.worldNormalMatrix,l+=16),Jr.set(o.viewNormalMatrix,l+=16)),r.matrices.setInputValue(Jr),r.uvDecodeMatrix.setInputValue&&r.uvDecodeMatrix.setInputValue(D.mat),s in e||(e[s]=[null,null,null]);const c=e[s],d=t?t.vertices?0:1:2;if(!c[d]){const e=h.createVertexArray();h.bindVertexArray(e);const i=(e,t)=>{e&&e.setInputValue&&t&&e.setInputValue(t)},s=r.attributes;i(s.position,x),i(s.normal,P),i(s.color,w),i(s.pickColor,C),i(s.uV,D&&D.buf),i(s.metallicRoughness,B),i(s.flags,b),i(s.offset,v),s.modelMatrixCol&&s.modelMatrixCol.forEach(((e,t)=>i(e,I[t]))),s.modelNormalMatrixCol&&s.modelNormalMatrixCol.forEach(((e,t)=>i(e,S[t])));const o=function(){const e=()=>{u?h.drawArraysInstanced(h.POINTS,0,x.numItems,n.length):h.drawArrays(h.POINTS,0,x.numItems)},i=(e,t)=>{t.bindIndicesBuffer();const i=t.indicesCount,s=t.indicesType;return()=>{u?h.drawElementsInstanced(e,i,s,0,n.length):h.drawElements(e,i,s,0)}};return"points"===A?e:"lines"===A?t&&t.vertices?e:i(h.LINES,F):t&&t.vertices?e:t&&M?i(h.LINES,M):i(h.TRIANGLES,F)}();h.bindVertexArray(null),f.push((()=>h.deleteVertexArray(e))),c[d]=()=>{h.bindVertexArray(e),o(),h.bindVertexArray(null)}}c[d]()};return{drawVertices:t({vertices:!0}),drawEdges:t({}),drawSurface:t(null)}}(),destroy:()=>{f.forEach((e=>e())),f.length=0}}}}const tn=function(e){const t={toString:()=>(t.needed=!0,e)};return t},sn=function(e,t,i){const s=e.createAttribute,r={position:s("vec3","positionA"),normal:s("vec3","normalA"),color:s("vec4","colorA"),pickColor:s("vec4","pickColor"),uV:s("vec2","uvApremul"),metallicRoughness:s("vec2","metallicRoughness"),flags:s("float","flagsA"),offset:i&&s("vec3","offset"),modelMatrixCol:t&&Yr(3).map((e=>s("vec4","modelMatrixCol"+e))),modelNormalMatrixCol:t&&t.hasModelNormalMat&&Yr(3).map((e=>s("vec4","modelNormalMatrixCol"+e)))},n=tn("aUv"),A=tn("viewNormal"),o=tn("worldNormal"),a=e.createUniform("mat3","uvDecodeMatrix"),l=()=>A.needed||o.needed,c=e.createUniformBlock("Matrices",{worldMatrix:"mat4",viewMatrix:"mat4",projMatrix:"mat4",positionsDecodeMatrix:"mat4",worldNormalMatrix:"mat4",viewNormalMatrix:"mat4"});return{dontCullOnAlphaZero:!0,geometryParameters:{attributes:{clippable:`((int(${r.flags}) >> 16 & 0xF) == 1)`,color:r.color,flags:Yr(4).map((e=>({toString:()=>`(int(${r.flags}) >> ${4*e} & 0xF)`}))),metallicRoughness:r.metallicRoughness,normal:{view:A,world:o},pickColor:r.pickColor,position:{clip:"gl_Position",view:"viewPosition",world:"worldPosition"},uv:n},projMatrix:c.projMatrix,viewMatrix:c.viewMatrix},appendVertexData:t=>{n.needed&&t.push(`vec2 ${n} = (${a} * vec3(${r.uV}, 1.0)).xy;`);const i=r.modelMatrixCol&&`mat4(${r.modelMatrixCol[0]}, ${r.modelMatrixCol[1]}, ${r.modelMatrixCol[2]}, vec4(0.0,0.0,0.0,1.0))`;if(t.push(`vec4 worldPosition = ${c.worldMatrix} * (${c.positionsDecodeMatrix} * vec4(${r.position}, 1.0)${i?" * "+i:""});`),r.offset&&t.push(`worldPosition.xyz = worldPosition.xyz + ${r.offset};`),l()){const i=r.modelNormalMatrixCol&&`* mat4(${r.modelNormalMatrixCol[0]}, ${r.modelNormalMatrixCol[1]}, ${r.modelNormalMatrixCol[2]}, vec4(0.0,0.0,0.0,1.0))`;t.push(`vec4 modelNormal = vec4(${e.commonLibrary.octDecode}(${r.normal}.xy), 0.0)${i||""};`),t.push(`vec3 ${o} = (${c.worldNormalMatrix} * modelNormal).xyz;`),A.needed&&t.push(`vec3 ${A} = normalize((${c.viewNormalMatrix} * vec4(${o}, 0.0)).xyz);`)}},layerTypeInputs:{attributes:r,matrices:c,uvDecodeMatrix:a,needNormal:l}}};class rn{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.alphaCutoff=e.alphaCutoff,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class nn{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const An={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class on{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t<i;t+=2){const i=this.handlers[t],s=this.handlers[t+1];if(i.global&&(i.lastIndex=0),i.test(e))return s}return null}}const an=new on;class ln{constructor(e){this.manager=void 0!==e?e:an,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const i=this;return new Promise((function(s,r){i.load(e,s,t,r)}))}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}const cn={};class hn extends ln{constructor(e){super(e)}load(e,t,i,s){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=An.get(e);if(void 0!==r)return this.manager.itemStart(e),I.scheduleTask((()=>{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==cn[e])return void cn[e].push({onLoad:t,onProgress:i,onError:s});cn[e]=[],cn[e].push({onLoad:t,onProgress:i,onError:s});const n=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),A=this.mimeType,o=this.responseType;fetch(n).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=cn[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),n=r?parseInt(r):0,A=0!==n;let o=0;const a=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{o+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:A,loaded:o,total:n});for(let e=0,t=i.length;e<t;e++){const t=i[e];t.onProgress&&t.onProgress(s)}e.enqueue(r),t()}}))}()}});return new Response(a)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(o){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,A)));case"json":return e.json();default:if(void 0===A)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(A),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{An.add(e,t);const i=cn[e];delete cn[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onLoad&&s.onLoad(t)}})).catch((t=>{const i=cn[e];if(void 0===i)throw this.manager.itemError(e),t;delete cn[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onError&&s.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class un{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:t,msg:i,transfer:s}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(i,s)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((i=>{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<<s,this.workersResolve[s]=i,this.workers[s].postMessage(e,t)):this.queue.push({resolve:i,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let dn=0;class fn{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new un,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new hn;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new hn;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=fn.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(fn.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(fn.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(fn.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),dn>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),dn++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const n=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:n},e))).then((e=>{const i=e.data,{mipmaps:n,width:A,height:o,format:a,type:l,error:c,dfdTransferFn:h,dfdFlags:u}=i;if("error"===l)return r(c);t.setCompressedData({mipmaps:n,props:{format:a,minFilter:1===n.length?1006:1008,magFilter:1===n.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),dn--}}fn.BasisFormat={ETC1S:0,UASTC_4x4:1},fn.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},fn.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},fn.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,n=_BasisFormat;self.addEventListener("message",(function(A){const c=A.data;switch(c.type){case"init":e=c.config,h=c.transcoderBinary,t=new Promise((e=>{i={wasmBinary:h,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:A,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:f,dfdFlags:p}=function(t){const A=new i.KTX2File(new Uint8Array(t));function c(){A.close(),A.delete()}if(!A.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=A.isUASTC()?n.UASTC_4x4:n.ETC1S,u=A.getWidth(),d=A.getHeight(),f=A.getLevels(),p=A.getHasAlpha(),g=A.getDFDTransferFunc(),m=A.getDFDFlags(),{transcoderFormat:_,engineFormat:b}=function(t,i,A,c){let h,u;const d=t===n.ETC1S?o:a;for(let s=0;s<d.length;s++){const r=d[s];if(e[r.if]&&(r.basisFormat.includes(t)&&!(c&&r.transcoderFormat.length<2)&&(!r.needsPowerOfTwo||l(i)&&l(A))))return h=r.transcoderFormat[c?1:0],u=r.engineFormat[c?1:0],{transcoderFormat:h,engineFormat:u}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=r.RGBA32,u=s.RGBAFormat,{transcoderFormat:h,engineFormat:u}}(h,u,d,p);if(!u||!d||!f)throw c(),new Error("KTX2TextureTranscoder: Invalid texture");if(!A.startTranscoding())throw c(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const y=[];for(let e=0;e<f;e++){const t=A.getImageLevelInfo(e,0,0),i=t.origWidth,s=t.origHeight,r=new Uint8Array(A.getImageTranscodedSizeInBytes(e,0,0,_));if(!A.transcodeImage(r,e,0,0,_,0,-1,-1))throw c(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");y.push({data:r,width:i,height:s})}return c(),{width:u,height:d,hasAlpha:p,mipmaps:y,format:b,dfdTransferFn:g,dfdFlags:m}}(c.buffers[0]),g=[];for(let e=0;e<u.length;++e)g.push(u[e].data.buffer);self.postMessage({type:"transcode",id:c.id,width:t,height:A,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:f,dfdFlags:p},g)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:c.id,error:e.message})}}))}var h}));const A=[{if:"astcSupported",basisFormat:[n.UASTC_4x4],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[s.RGBA_ASTC_4x4_Format,s.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[s.RGBA_BPTC_Format,s.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.BC1,r.BC3],engineFormat:[s.RGB_S3TC_DXT1_Format,s.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[s.RGB_ETC2_Format,s.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.ETC1],engineFormat:[s.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[s.RGB_PVRTC_4BPPV1_Format,s.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],o=A.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),a=A.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function l(e){return e<=2||0==(e&e-1)&&0!==e}};const pn={};function gn(e){const t=e.scene.id;let i=pn[t];return i||(i=new fn({viewer:e}),pn[t]=i,e.scene.on("destroyed",(()=>{delete pn[t],i.destroy()}))),i}
|
|
7
|
+
class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s,r){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.getShown=r,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class n{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._parentNode=e.parentNode||document.body,this._offsetParent=this._parentNode instanceof ShadowRoot?this._parentNode.host:this._parentNode,this._eventSubs={},!1!==e.hideOnMouseDown&&(this._parentNode.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),this._parentNode.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this._hideOnAction=!1!==e.hideOnAction,this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}set items(e){this._clear(),this._itemsCfg=e||[],this._parseItems(e),this._createUI()}get items(){return this._itemsCfg}set enabled(e){(e=!!e)!==this._enabled&&(this._enabled=e,this._enabled||this.hide())}get enabled(){return this._enabled}set context(e){this._context=e}get context(){return this._context}show(e,t){this._context?this._enabled&&(this._shown||(this._hideAllMenus(),this._updateItemsTitles(),this._updateItemsEnabledStatus(),this._showMenu(this._rootMenu.id,e,t),this._updateSubMenuInfo(),this._shown=!0,this.fire("shown",{}))):console.error("ContextMenu cannot be shown without a context - set context first")}get shown(){return this._shown}hide(){this._enabled&&this._shown&&(this._hideAllMenus(),this._shown=!1,this.fire("hidden",{}))}destroy(){this._context=null,this._clear(),null!==this._id&&(t.removeItem(this._id),this._id=null)}_clear(){for(let e=0,t=this._menuList.length;e<t;e++){this._menuList[e].menuElement.remove()}this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={}}_parseItems(e){const t=e=>{const n=this._getNextId(),A=new i(n);for(let i=0,n=e.length;i<n;i++){const n=e[i],o=new s;A.groups.push(o);for(let e=0,i=n.length;e<i;e++){const i=n[e],s=i.items,a=s&&s.length>0,l=this._getNextId(),c=i.getTitle||(()=>i.title||""),h=i.doAction||i.callback||(()=>{}),u=i.getEnabled||(()=>!0),d=i.getShown||(()=>!0),f=new r(l,c,h,u,d);if(f.parentMenu=A,o.items.push(f),a){const e=t(s);f.subMenu=e,e.parentItem=f}this._itemList.push(f),this._itemMap[f.id]=f}}return this._menuList.push(A),this._menuMap[A.id]=A,A};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+"_"+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t<s;t++){const s=i[t].items;for(let t=0,i=s.length;t<i;t++){const i=s[t].subMenu;i&&e(i)}}};e(this._rootMenu)}_createMenuUI(e){const t=e.groups,i=[],s=document.createElement("div");if(s.classList.add("xeokit-context-menu",e.id),s.style.zIndex=3e5,s.style.position="absolute",i.push("<ul>"),t)for(let e=0,s=t.length;e<s;e++){const r=e,n=s,A=t[e].items;if(A)for(let e=0,t=A.length;e<t;e++){const s=A[e],o=s.subMenu,a=s.title||"";o?(i.push('<li id="'+s.id+'" class="xeokit-context-menu-item xeokit-context-menu-submenu">'+a+"</li>"),r===n-1||e<t-1||i.push('<li id="'+s.id+'" class="xeokit-context-menu-item-separator"></li>')):(i.push('<li id="'+s.id+'" class="xeokit-context-menu-item">'+a+"</li>"),r===n-1||e<t-1||i.push('<li id="'+s.id+'" class="xeokit-context-menu-item-separator"></li>'))}}i.push("</ul>");const r=i.join("");s.innerHTML=r,this._parentNode.appendChild(s),e.menuElement=s,s.style["border-radius"]="4px",s.style.display="none",s.style["z-index"]=3e5,s.style.background="white",s.style.border="1px solid black",s.style["box-shadow"]="0 4px 5px 0 gray",s.oncontextmenu=e=>{e.preventDefault()};const n=this;let A=null;if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e].items;if(i)for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.subMenu;t.itemElement=this._parentNode.querySelector(`#${t.id}`),t.itemElement?(t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault();const i=t.subMenu;if(!i)return void(A&&(n._hideMenu(A.id),A=null));if(A&&A.id!==i.id&&(n._hideMenu(A.id),A=null),!1===t.enabled)return;const s=t.itemElement,r=i.menuElement,o=s.getBoundingClientRect();r.getBoundingClientRect();const a=n._offsetParent.getBoundingClientRect(),l=200,c=o.right+l<a.right,h=o.left-l>a.left;if(c)n._showMenu(i.id,o.right+window.scrollX-5,o.top+window.scrollY-1);else if(h)n._showMenu(i.id,o.left-l+window.scrollX,o.top+window.scrollY-1);else{const e=o.left-a.left,t=a.right-o.right;t>e?n._showMenu(i.id,o.right-5-(l-t),o.top+window.scrollY-1):n._showMenu(i.id,o.left-e,o.top+window.scrollY-1)}A=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),n._context&&!1!==t.enabled&&(t.doAction&&t.doAction(n._context),this._hideOnAction?n.hide():(n._updateItemsTitles(),n._updateItemsEnabledStatus()))})),t.itemElement.addEventListener("mouseup",(e=>{3===e.which&&(e.preventDefault(),n._context&&!1!==t.enabled&&(t.doAction&&t.doAction(n._context),this._hideOnAction?n.hide():(n._updateItemsTitles(),n._updateItemsEnabledStatus())))})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(n._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;e<t;e++){const t=this._itemList[e],i=t.itemElement;if(!i)continue;const s=t.getShown;if(!s||!s(this._context))continue;const r=t.getTitle(this._context);t.subMenu,i.innerText=r}}_updateItemsEnabledStatus(){if(this._context)for(let e=0,t=this._itemList.length;e<t;e++){const t=this._itemList[e],i=t.itemElement;if(!i)continue;const s=t.getEnabled;if(!s)continue;const r=t.getShown;if(!r)continue;const n=r(this._context);if(t.shown=n,!n){i.style.display="none";continue}i.style.display="";const A=s(this._context);t.enabled=A,A?i.classList.remove("disabled"):i.classList.add("disabled")}}_updateSubMenuInfo(){if(!this._context)return;let e,t,i,s,r,n;this._itemList.forEach((A=>{A.subMenu&&(e=A.itemElement,t=e.getBoundingClientRect(),i=A.subMenu.menuElement,s={visibility:i.style.visibility,display:i.style.display},i.style.display="block",i.style.visibility="hidden",n=A.subMenu.menuElement.getBoundingClientRect().width,i.style.visibility=s.visibility,i.style.display=s.display,r=t.right+n>window.innerWidth,e.setAttribute("data-submenuposition",r?"left":"right"))}))}_showMenu(e,t,i){const s=this._menuMap[e];if(!s)return void console.error("Menu not found: "+e);if(s.shown)return;const r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.shown=!0)}_hideMenu(e){const t=this._menuMap[e];if(!t)return void console.error("Menu not found: "+e);if(!t.shown)return;const i=t.menuElement;i&&(this._hideMenuElement(i),t.shown=!1)}_hideAllMenus(){for(let e=0,t=this._menuList.length;e<t;e++){const t=this._menuList[e];this._hideMenu(t.id)}}_showMenuElement(e,t,i){e.style.display="block";const s=e.offsetHeight,r=e.offsetWidth,n=this._offsetParent.getBoundingClientRect(),A=this._offsetParent===window.document.body&&0===n.bottom?window.innerHeight:n.bottom+window.scrollY,o=n.right+window.scrollX;i+s>A&&(i=A-s),t+r>o&&(t=o-r),e.style.left=t-n.left-window.scrollX+"px",e.style.top=i-n.top-window.scrollY+"px"}_hideMenuElement(e){e.style.display="none"}}class A{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._lensCursorDiv=document.createElement("div"),this._lensParams={canvasSize:300,cursorBorder:2,cursorSize:10},this._lensCursorDiv.style.borderRadius="50%",this._lensCursorDiv.style.width=this._lensParams.cursorSize+"px",this._lensCursorDiv.style.height=this._lensParams.cursorSize+"px",this._lensCursorDiv.style.zIndex="100000",this._lensCursorDiv.style.position="absolute",this._lensCursorDiv.style.pointerEvents="none",this._lensContainer=document.createElement("div"),this._lensContainerId=t.containerId||"xeokit-lens",this._lensContainer.setAttribute("id",this._lensContainerId),this._lensContainer.style.border="1px solid black",this._lensContainer.style.background="white",this._lensContainer.style.borderRadius="50%",this._lensContainer.style.width=this._lensParams.canvasSize+"px",this._lensContainer.style.height=this._lensParams.canvasSize+"px",this._lensContainer.style.zIndex="15000",this._lensContainer.style.position="absolute",this._lensContainer.style.pointerEvents="none",this._lensContainer.style.visibility="hidden",this._lensCanvas=document.createElement("canvas"),this._lensCanvas.id=`${this._lensContainerId}-canvas`,this._lensCanvas.style.borderRadius="50%",this._lensCanvas.style.width=this._lensParams.canvasSize+"px",this._lensCanvas.style.height=this._lensParams.canvasSize+"px",this._lensCanvas.style.zIndex="15000",this._lensCanvas.style.pointerEvents="none",document.body.appendChild(this._lensContainer),this._lensContainer.appendChild(this._lensCanvas),this._lensContainer.appendChild(this._lensCursorDiv),this._lensCanvasContext=this._lensCanvas.getContext("2d"),this._canvasElement=this.viewer.scene.canvas.canvas,this._canvasPos=null,this._snappedCanvasPos=null,this._lensPosToggle=t.lensPosToggle||!0,this._lensPosToggleAmount=t.lensPosToggleAmount||85,this._lensPosMarginLeft=t.lensPosMarginLeft||85,this._lensPosMarginTop=t.lensPosMarginTop||25,this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,this._zoomLevel=t.zoomLevel||2,this._active=!1!==t.active,this._visible=!1,this.snapped=!1,this._onViewerRendering=this.viewer.scene.on("rendering",(()=>{this._active&&this._visible&&this.update()}))}update(){if(!this._active||!this._visible)return;if(!this._canvasPos)return;const e=this._lensContainer.getBoundingClientRect(),t=this._canvasElement.getBoundingClientRect(),i=this._canvasPos[0]<e.right&&this._canvasPos[0]>e.left&&this._canvasPos[1]<e.bottom&&this._canvasPos[1]>e.top;this._lensContainer.style.marginLeft=`${this._lensPosMarginLeft}px`,i&&(this._lensPosToggle?this._lensContainer.style.marginTop=t.bottom-t.top-this._lensCanvas.height-this._lensPosToggleAmount+"px":this._lensContainer.style.marginTop=`${this._lensPosMarginTop}px`,this._lensPosToggle=!this._lensPosToggle),this._lensCanvasContext.clearRect(0,0,this._lensCanvas.width,this._lensCanvas.height);const s=Math.max(this._lensCanvas.width,this._lensCanvas.height)/this._zoomLevel;this._lensCanvasContext.drawImage(this._canvasElement,this._canvasPos[0]-s/2,this._canvasPos[1]-s/2,s,s,0,0,this._lensCanvas.width,this._lensCanvas.height);const r=this._lensParams.canvasSize/2-this._lensParams.cursorSize/2-this._lensParams.cursorBorder,n=this._snappedCanvasPos?this._snappedCanvasPos[0]-this._canvasPos[0]:0,A=this._snappedCanvasPos?this._snappedCanvasPos[1]-this._canvasPos[1]:0;this._lensCursorDiv.style.left=`${r+n*this._zoomLevel}px`,this._lensCursorDiv.style.top=`${r+A*this._zoomLevel}px`}set zoomFactor(e){this._zoomFactor=e,this.update()}get zoomFactor(){return this._zoomFactor}set canvasPos(e){this._canvasPos=e,this.update()}get canvasPos(){return this._canvasPos}set snappedCanvasPos(e){this._snappedCanvasPos=e,this.update()}get snappedCanvasPos(){return this._snappedCanvasPos}set snapped(e){this._snapped=e;const[t,i]=e?["greenyellow","green"]:["pink","red"];this._lensCursorDiv.style.background=t,this._lensCursorDiv.style.border=this._lensParams.cursorBorder+"px solid "+i}get snapped(){return this._snapped}_updateActiveVisible(){this._lensContainer.style.visibility=this._active&&this._visible?"visible":"hidden",this.update()}set active(e){this._active=e,this._updateActiveVisible()}get active(){return this._active}set visible(e){this._visible=e,this._updateActiveVisible()}get visible(){return this._visible}destroy(){this._destroyed||(this.viewer.scene.off(this._onViewerRendering),this._lensContainer.removeChild(this._lensCanvas),document.body.removeChild(this._lensContainer),this._destroyed=!0)}}let o=!0,a=o?Float64Array:Float32Array;const l=new a(3),c=new a(16),h=new a(16),u=new a(4),d={setDoublePrecisionEnabled(e){o=e,a=o?Float64Array:Float32Array},getDoublePrecisionEnabled:()=>o,MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,MAX_INT:1e7,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,safeInv(e){const t=1/e;return isNaN(t)||!isFinite(t)?1:t},vec2:e=>new a(e||2),vec3:e=>new a(e||3),vec4:e=>new a(e||4),mat3:e=>new a(e||9),mat3ToMat4:(e,t=new a(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new a(e||16),mat4ToMat3:(e,t=new a(9))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[4],t[4]=e[5],t[5]=e[6],t[6]=e[8],t[7]=e[9],t[8]=e[10],t),doublesToFloats(e,t,i){const s=new a(2);for(let r=0,n=e.length;r<n;r++)d.splitDouble(e[r],s),t[r]=s[0],i[r]=s[1]},splitDouble(e,t){const i=a.from([e])[0],s=e-i;t[0]=i,t[1]=s},createUUID:(()=>{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],compareVec4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new a(e[0]);for(let i=1;i<e.length;i++)t[0]+=e[i][0],t[1]+=e[i][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],n=t[0],A=t[1],o=t[2];return[s*o-r*A,r*n-i*o,i*A-s*n,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],n=e[2],A=t[0],o=t[1],a=t[2];return i[0]=r*a-n*o,i[1]=n*A-s*a,i[2]=s*o-r*A,i},sqLenVec4:e=>d.dotVec4(e,e),lenVec4:e=>Math.sqrt(d.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>d.dotVec3(e,e),sqLenVec2:e=>d.dotVec2(e,e),lenVec3:e=>Math.sqrt(d.sqLenVec3(e)),distVec3:(()=>{const e=new a(3);return(t,i)=>d.lenVec3(d.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(d.sqLenVec2(e)),distVec2:(()=>{const e=new a(2);return(t,i)=>d.lenVec2(d.subVec2(t,i,e))})(),rcpVec3:(e,t)=>d.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/d.lenVec4(e);return d.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/d.lenVec3(e);return d.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/d.lenVec2(e);return d.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=d.dotVec3(e,t)/Math.sqrt(d.sqLenVec3(e)*d.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new a(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=d.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=d.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=d.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i<s;i++)t[i]=e(t[i]);return t}})(),xyzArrayToObject:e=>({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||d.vec3())[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>d.m4s(0),setMat4ToOnes:()=>d.m4s(1),diagonalMat4v:e=>new a([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>d.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>d.diagonalMat4c(e,e,e,e),identityMat4:(e=new a(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new a(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>d.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],n=e[2],A=e[3],o=e[4],a=e[5],l=e[6],c=e[7],h=e[8],u=e[9],d=e[10],f=e[11],p=e[12],g=e[13],m=e[14],_=e[15],b=t[0],y=t[1],w=t[2],v=t[3],B=t[4],C=t[5],M=t[6],E=t[7],F=t[8],U=t[9],x=t[10],I=t[11],T=t[12],P=t[13],S=t[14],D=t[15];return i[0]=b*s+y*o+w*h+v*p,i[1]=b*r+y*a+w*u+v*g,i[2]=b*n+y*l+w*d+v*m,i[3]=b*A+y*c+w*f+v*_,i[4]=B*s+C*o+M*h+E*p,i[5]=B*r+C*a+M*u+E*g,i[6]=B*n+C*l+M*d+E*m,i[7]=B*A+C*c+M*f+E*_,i[8]=F*s+U*o+x*h+I*p,i[9]=F*r+U*a+x*u+I*g,i[10]=F*n+U*l+x*d+I*m,i[11]=F*A+U*c+x*f+I*_,i[12]=T*s+P*o+S*h+D*p,i[13]=T*r+P*a+S*u+D*g,i[14]=T*n+P*l+S*d+D*m,i[15]=T*A+P*c+S*f+D*_,i},mulMat3(e,t,i){i||(i=new a(9));const s=e[0],r=e[3],n=e[6],A=e[1],o=e[4],l=e[7],c=e[2],h=e[5],u=e[8],d=t[0],f=t[3],p=t[6],g=t[1],m=t[4],_=t[7],b=t[2],y=t[5],w=t[8];return i[0]=s*d+r*g+n*b,i[3]=s*f+r*m+n*y,i[6]=s*p+r*_+n*w,i[1]=A*d+o*g+l*b,i[4]=A*f+o*m+l*y,i[7]=A*p+o*_+l*w,i[2]=c*d+h*g+u*b,i[5]=c*f+h*m+u*y,i[8]=c*p+h*_+u*w,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=d.vec4()){const s=t[0],r=t[1],n=t[2],A=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*A,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*A,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*A,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*A,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],n=e[13],A=e[12],o=e[9];if(!t||e===t){const t=e[1],a=e[2],l=e[3],c=e[6],h=e[7],u=e[11];return e[1]=i,e[2]=r,e[3]=A,e[4]=t,e[6]=o,e[7]=n,e[8]=a,e[9]=c,e[11]=s,e[12]=l,e[13]=h,e[14]=u,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=A,t[4]=e[1],t[5]=e[5],t[6]=o,t[7]=n,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],n=e[4],A=e[5],o=e[6],a=e[7],l=e[8],c=e[9],h=e[10],u=e[11],d=e[12],f=e[13],p=e[14],g=e[15];return d*c*o*r-l*f*o*r-d*A*h*r+n*f*h*r+l*A*p*r-n*c*p*r-d*c*s*a+l*f*s*a+d*i*h*a-t*f*h*a-l*i*p*a+t*c*p*a+d*A*s*u-n*f*s*u-d*i*o*u+t*f*o*u+n*i*p*u-t*A*p*u-l*A*s*g+n*c*s*g+l*i*o*g-t*c*o*g-n*i*h*g+t*A*h*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],n=e[3],A=e[4],o=e[5],a=e[6],l=e[7],c=e[8],h=e[9],u=e[10],d=e[11],f=e[12],p=e[13],g=e[14],m=e[15],_=i*o-s*A,b=i*a-r*A,y=i*l-n*A,w=s*a-r*o,v=s*l-n*o,B=r*l-n*a,C=c*p-h*f,M=c*g-u*f,E=c*m-d*f,F=h*g-u*p,U=h*m-d*p,x=u*m-d*g,I=1/(_*x-b*U+y*F+w*E-v*M+B*C);return t[0]=(o*x-a*U+l*F)*I,t[1]=(-s*x+r*U-n*F)*I,t[2]=(p*B-g*v+m*w)*I,t[3]=(-h*B+u*v-d*w)*I,t[4]=(-A*x+a*E-l*M)*I,t[5]=(i*x-r*E+n*M)*I,t[6]=(-f*B+g*y-m*b)*I,t[7]=(c*B-u*y+d*b)*I,t[8]=(A*U-o*E+l*C)*I,t[9]=(-i*U+s*E-n*C)*I,t[10]=(f*v-p*y+m*_)*I,t[11]=(-c*v+h*y-d*_)*I,t[12]=(-A*F+o*M-a*C)*I,t[13]=(i*F-s*M+r*C)*I,t[14]=(-f*w+p*b-g*_)*I,t[15]=(c*w-h*b+u*_)*I,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||d.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||d.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new a(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.translationMat4v(e,r))})(),translationMat4s:(e,t)=>d.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>d.translateMat4c(e[0],e[1],e[2],t),translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const n=s[7];s[4]+=n*e,s[5]+=n*t,s[6]+=n*i;const A=s[11];s[8]+=A*e,s[9]+=A*t,s[10]+=A*i;const o=s[15];return s[12]+=o*e,s[13]+=o*t,s[14]+=o*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=d.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),n=Math.cos(e),A=1-n,o=s[0],a=s[1],l=s[2];let c,h,u,f,p,g;return c=o*a,h=a*l,u=l*o,f=o*r,p=a*r,g=l*r,(i=i||d.mat4())[0]=A*o*o+n,i[1]=A*c+g,i[2]=A*u-p,i[3]=0,i[4]=A*c-g,i[5]=A*a*a+n,i[6]=A*h+f,i[7]=0,i[8]=A*u+p,i[9]=A*h-f,i[10]=A*l*l+n,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>d.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=d.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=d.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new a(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,d.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>d.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=d.mat4()){const s=e[0],r=e[1],n=e[2],A=e[3],o=s+s,a=r+r,l=n+n,c=s*o,h=s*a,u=s*l,f=r*a,p=r*l,g=n*l,m=A*o,_=A*a,b=A*l;return i[0]=1-(f+g),i[1]=h+b,i[2]=u-_,i[3]=0,i[4]=h-b,i[5]=1-(c+g),i[6]=p+m,i[7]=0,i[8]=u+_,i[9]=p-m,i[10]=1-(c+f),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=d.vec4()){const s=d.clamp,r=e[0],n=e[4],A=e[8],o=e[1],a=e[5],l=e[9],c=e[2],h=e[6],u=e[10];return"XYZ"===t?(i[1]=Math.asin(s(A,-1,1)),Math.abs(A)<.99999?(i[0]=Math.atan2(-l,u),i[2]=Math.atan2(-n,r)):(i[0]=Math.atan2(h,a),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(l,-1,1)),Math.abs(l)<.99999?(i[1]=Math.atan2(A,u),i[2]=Math.atan2(o,a)):(i[1]=Math.atan2(-c,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(h,-1,1)),Math.abs(h)<.99999?(i[1]=Math.atan2(-c,u),i[2]=Math.atan2(-n,a)):(i[1]=0,i[2]=Math.atan2(o,r))):"ZYX"===t?(i[1]=Math.asin(-s(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(h,u),i[2]=Math.atan2(o,r)):(i[0]=0,i[2]=Math.atan2(-n,a))):"YZX"===t?(i[2]=Math.asin(s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(-l,a),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(A,u))):"XZY"===t&&(i[2]=Math.asin(-s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(h,a),i[1]=Math.atan2(A,r)):(i[0]=Math.atan2(-l,u),i[1]=0)),i[0]*=d.RADTODEG,i[1]*=d.RADTODEG,i[2]*=d.RADTODEG,i},composeMat4:(e,t,i,s=d.mat4())=>(d.quaternionToRotationMat4(t,s),d.scaleMat4v(i,s),d.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new a(3),t=new a(16);return function(i,s,r,n){e[0]=i[0],e[1]=i[1],e[2]=i[2];let A=d.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const o=d.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const a=d.lenVec3(e);d.determinantMat4(i)<0&&(A=-A),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const l=1/A,c=1/o,h=1/a;return t[0]*=l,t[1]*=l,t[2]*=l,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=h,t[9]*=h,t[10]*=h,d.mat4ToQuaternion(t,r),n[0]=A,n[1]=o,n[2]=a,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=d.mat4());const r=e[0],n=e[1],A=e[2],o=i[0],a=i[1],l=i[2],c=t[0],h=t[1],u=t[2];if(r===c&&n===h&&A===u)return d.identityMat4();let f,p,g,m,_,b,y,w,v,B;return f=r-c,p=n-h,g=A-u,B=1/Math.sqrt(f*f+p*p+g*g),f*=B,p*=B,g*=B,m=a*g-l*p,_=l*f-o*g,b=o*p-a*f,B=Math.sqrt(m*m+_*_+b*b),B?(B=1/B,m*=B,_*=B,b*=B):(m=0,_=0,b=0),y=p*b-g*_,w=g*m-f*b,v=f*_-p*m,B=Math.sqrt(y*y+w*w+v*v),B?(B=1/B,y*=B,w*=B,v*=B):(y=0,w=0,v=0),s[0]=m,s[1]=y,s[2]=f,s[3]=0,s[4]=_,s[5]=w,s[6]=p,s[7]=0,s[8]=b,s[9]=v,s[10]=g,s[11]=0,s[12]=-(m*r+_*n+b*A),s[13]=-(y*r+w*n+v*A),s[14]=-(f*r+p*n+g*A),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,n,A,o,a)=>d.lookAtMat4v([e,t,i],[s,r,n],[A,o,a],[]),orthoMat4c(e,t,i,s,r,n,A){A||(A=d.mat4());const o=t-e,a=s-i,l=n-r;return A[0]=2/o,A[1]=0,A[2]=0,A[3]=0,A[4]=0,A[5]=2/a,A[6]=0,A[7]=0,A[8]=0,A[9]=0,A[10]=-2/l,A[11]=0,A[12]=-(e+t)/o,A[13]=-(s+i)/a,A[14]=-(n+r)/l,A[15]=1,A},frustumMat4v(e,t,i){i||(i=d.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];d.addVec4(r,s,c),d.subVec4(r,s,h);const n=2*s[2],A=h[0],o=h[1],a=h[2];return i[0]=n/A,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=n/o,i[6]=0,i[7]=0,i[8]=c[0]/A,i[9]=c[1]/o,i[10]=-c[2]/a,i[11]=-1,i[12]=0,i[13]=0,i[14]=-n*r[2]/a,i[15]=0,i},frustumMat4(e,t,i,s,r,n,A){A||(A=d.mat4());const o=t-e,a=s-i,l=n-r;return A[0]=2*r/o,A[1]=0,A[2]=0,A[3]=0,A[4]=0,A[5]=2*r/a,A[6]=0,A[7]=0,A[8]=(t+e)/o,A[9]=(s+i)/a,A[10]=-(n+r)/l,A[11]=-1,A[12]=0,A[13]=0,A[14]=-n*r*2/l,A[15]=0,A},perspectiveMat4(e,t,i,s,r){const n=[],A=[];return n[2]=i,A[2]=s,A[1]=n[2]*Math.tan(e/2),n[1]=-A[1],A[0]=A[1]*t,n[0]=-A[0],d.frustumMat4v(n,A,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=d.vec3()){const s=t[0],r=t[1],n=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*n+e[12],i[1]=e[1]*s+e[5]*r+e[9]*n+e[13],i[2]=e[2]*s+e[6]*r+e[10]*n+e[14],i},transformPoint4:(e,t,i=d.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let n,A,o,a;const l=e[0],c=e[1],h=e[2],u=e[3],d=e[4],f=e[5],p=e[6],g=e[7],m=e[8],_=e[9],b=e[10],y=e[11],w=e[12],v=e[13],B=e[14],C=e[15];let M;for(let e=0;e<r;++e)a=t[e],n=a[0],A=a[1],o=a[2],M=s[e]||(s[e]=[0,0,0]),M[0]=l*n+d*A+m*o+w,M[1]=c*n+f*A+_*o+v,M[2]=h*n+p*A+b*o+B,M[3]=u*n+g*A+y*o+C;return s.length=r,s},transformPositions3(e,t,i=t){let s;const r=t.length;let n,A,o;const a=e[0],l=e[1],c=e[2];e[3];const h=e[4],u=e[5],d=e[6];e[7];const f=e[8],p=e[9],g=e[10];e[11];const m=e[12],_=e[13],b=e[14];for(e[15],s=0;s<r;s+=3)n=t[s+0],A=t[s+1],o=t[s+2],i[s+0]=a*n+h*A+f*o+m,i[s+1]=l*n+u*A+p*o+_,i[s+2]=c*n+d*A+g*o+b;return i},transformPositions4(e,t,i=t){let s;const r=t.length;let n,A,o;const a=e[0],l=e[1],c=e[2],h=e[3],u=e[4],d=e[5],f=e[6],p=e[7],g=e[8],m=e[9],_=e[10],b=e[11],y=e[12],w=e[13],v=e[14],B=e[15];for(s=0;s<r;s+=4)n=t[s+0],A=t[s+1],o=t[s+2],i[s+0]=a*n+u*A+g*o+y,i[s+1]=l*n+d*A+m*o+w,i[s+2]=c*n+f*A+_*o+v,i[s+3]=h*n+p*A+b*o+B;return i},transformVec3(e,t,i){const s=t[0],r=t[1],n=t[2];return(i=i||this.vec3())[0]=e[0]*s+e[4]*r+e[8]*n,i[1]=e[1]*s+e[5]*r+e[9]*n,i[2]=e[2]*s+e[6]*r+e[10]*n,i},transformVec4(e,t,i){const s=t[0],r=t[1],n=t[2],A=t[3];return(i=i||d.vec4())[0]=e[0]*s+e[4]*r+e[8]*n+e[12]*A,i[1]=e[1]*s+e[5]*r+e[9]*n+e[13]*A,i[2]=e[2]*s+e[6]*r+e[10]*n+e[14]*A,i[3]=e[3]*s+e[7]*r+e[11]*n+e[15]*A,i},rotateVec2(e,t,i,s=e){const r=Math.cos(i),n=Math.sin(i),A=e[0]-t[0],o=e[1]-t[1];return s[0]=A*r-o*n+t[0],s[1]=A*n+o*r+t[1],e},rotateVec3X(e,t,i,s){const r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0],n[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),n[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Y(e,t,i,s){const r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),n[1]=r[1],n[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},rotateVec3Z(e,t,i,s){const r=[],n=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],n[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),n[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),n[2]=r[2],s[0]=n[0]+t[0],s[1]=n[1]+t[1],s[2]=n[2]+t[2],s},projectVec4(e,t){const i=1/e[3];return(t=t||d.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(()=>{const e=new a(16),t=new a(16),i=new a(16);return function(s,r,n,A){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(n,t),i),s,A)}})(),lerpVec3(e,t,i,s,r,n){const A=n||d.vec3(),o=(e-t)/(i-t);return A[0]=s[0]+o*(r[0]-s[0]),A[1]=s[1]+o*(r[1]-s[1]),A[2]=s[2]+o*(r[2]-s[2]),A},lerpMat4(e,t,i,s,r,n){const A=n||d.mat4(),o=(e-t)/(i-t);return A[0]=s[0]+o*(r[0]-s[0]),A[1]=s[1]+o*(r[1]-s[1]),A[2]=s[2]+o*(r[2]-s[2]),A[3]=s[3]+o*(r[3]-s[3]),A[4]=s[4]+o*(r[4]-s[4]),A[5]=s[5]+o*(r[5]-s[5]),A[6]=s[6]+o*(r[6]-s[6]),A[7]=s[7]+o*(r[7]-s[7]),A[8]=s[8]+o*(r[8]-s[8]),A[9]=s[9]+o*(r[9]-s[9]),A[10]=s[10]+o*(r[10]-s[10]),A[11]=s[11]+o*(r[11]-s[11]),A[12]=s[12]+o*(r[12]-s[12]),A[13]=s[13]+o*(r[13]-s[13]),A[14]=s[14]+o*(r[14]-s[14]),A[15]=s[15]+o*(r[15]-s[15]),A},flatten(e){const t=[];let i,s,r,n,A;for(i=0,s=e.length;i<s;i++)for(A=e[i],r=0,n=A.length;r<n;r++)t.push(A[r]);return t},identityQuaternion:(e=d.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=d.vec4()){const s=e[0]*d.DEGTORAD/2,r=e[1]*d.DEGTORAD/2,n=e[2]*d.DEGTORAD/2,A=Math.cos(s),o=Math.cos(r),a=Math.cos(n),l=Math.sin(s),c=Math.sin(r),h=Math.sin(n);return"XYZ"===t?(i[0]=l*o*a+A*c*h,i[1]=A*c*a-l*o*h,i[2]=A*o*h+l*c*a,i[3]=A*o*a-l*c*h):"YXZ"===t?(i[0]=l*o*a+A*c*h,i[1]=A*c*a-l*o*h,i[2]=A*o*h-l*c*a,i[3]=A*o*a+l*c*h):"ZXY"===t?(i[0]=l*o*a-A*c*h,i[1]=A*c*a+l*o*h,i[2]=A*o*h+l*c*a,i[3]=A*o*a-l*c*h):"ZYX"===t?(i[0]=l*o*a-A*c*h,i[1]=A*c*a+l*o*h,i[2]=A*o*h-l*c*a,i[3]=A*o*a+l*c*h):"YZX"===t?(i[0]=l*o*a+A*c*h,i[1]=A*c*a+l*o*h,i[2]=A*o*h-l*c*a,i[3]=A*o*a-l*c*h):"XZY"===t&&(i[0]=l*o*a-A*c*h,i[1]=A*c*a-l*o*h,i[2]=A*o*h+l*c*a,i[3]=A*o*a+l*c*h),i},mat4ToQuaternion(e,t=d.vec4()){const i=e[0],s=e[4],r=e[8],n=e[1],A=e[5],o=e[9],a=e[2],l=e[6],c=e[10];let h;const u=i+A+c;return u>0?(h=.5/Math.sqrt(u+1),t[3]=.25/h,t[0]=(l-o)*h,t[1]=(r-a)*h,t[2]=(n-s)*h):i>A&&i>c?(h=2*Math.sqrt(1+i-A-c),t[3]=(l-o)/h,t[0]=.25*h,t[1]=(s+n)/h,t[2]=(r+a)/h):A>c?(h=2*Math.sqrt(1+A-i-c),t[3]=(r-a)/h,t[0]=(s+n)/h,t[1]=.25*h,t[2]=(o+l)/h):(h=2*Math.sqrt(1+c-i-A),t[3]=(n-s)/h,t[0]=(r+a)/h,t[1]=(o+l)/h,t[2]=.25*h),t},vec3PairToQuaternion(e,t,i=d.vec4()){const s=Math.sqrt(d.dotVec3(e,e)*d.dotVec3(t,t));let r=s+d.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):d.cross3Vec3(e,t,i),i[3]=r,d.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=d.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new a(16);return(t,i,s)=>(s=s||d.vec3(),d.quaternionToRotationMat4(t,e),d.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=d.vec4()){const s=e[0],r=e[1],n=e[2],A=e[3],o=t[0],a=t[1],l=t[2],c=t[3];return i[0]=A*o+s*c+r*l-n*a,i[1]=A*a+r*c+n*o-s*l,i[2]=A*l+n*c+s*a-r*o,i[3]=A*c-s*o-r*a-n*l,i},vec3ApplyQuaternion(e,t,i=d.vec3()){const s=t[0],r=t[1],n=t[2],A=e[0],o=e[1],a=e[2],l=e[3],c=l*s+o*n-a*r,h=l*r+a*s-A*n,u=l*n+A*r-o*s,f=-A*s-o*r-a*n;return i[0]=c*l+f*-A+h*-a-u*-o,i[1]=h*l+f*-o+u*-A-c*-a,i[2]=u*l+f*-a+c*-o-h*-A,i},quaternionToMat4(e,t){t=d.identityMat4(t);const i=e[0],s=e[1],r=e[2],n=e[3],A=2*i,o=2*s,a=2*r,l=A*n,c=o*n,h=a*n,u=A*i,f=o*i,p=a*i,g=o*s,m=a*s,_=a*r;return t[0]=1-(g+_),t[1]=f+h,t[2]=p-c,t[4]=f-h,t[5]=1-(u+_),t[6]=m+l,t[8]=p+c,t[9]=m-l,t[10]=1-(u+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],n=e[3],A=i+i,o=s+s,a=r+r,l=i*A,c=i*o,h=i*a,u=s*o,d=s*a,f=r*a,p=n*A,g=n*o,m=n*a;return t[0]=1-(u+f),t[4]=c-m,t[8]=h+g,t[1]=c+m,t[5]=1-(l+f),t[9]=d-p,t[2]=h-g,t[6]=d+p,t[10]=1-(l+u),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=d.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>d.normalizeQuaternion(d.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=d.vec4()){const i=(e=d.normalizeQuaternion(e,u))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new a(e||6),AABB2:e=>new a(e||4),OBB3:e=>new a(e||32),OBB2:e=>new a(e||16),Sphere3:(e,t,i,s)=>new a([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let n,A,o;const a=e[0],l=e[1],c=e[2],h=e[3],u=e[4],d=e[5],f=e[6],p=e[7],g=e[8],m=e[9],_=e[10],b=e[11],y=e[12],w=e[13],v=e[14],B=e[15];for(s=0;s<r;s+=4)n=t[s+0],A=t[s+1],o=t[s+2],i[s+0]=a*n+u*A+g*o+y,i[s+1]=l*n+d*A+m*o+w,i[s+2]=c*n+f*A+_*o+v,i[s+3]=h*n+p*A+b*o+B;return i},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:(()=>{const e=new a(3),t=new a(3),i=new a(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],d.subVec3(t,e,i),Math.abs(d.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new a(3),t=new a(3),i=new a(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const n=d.subVec3(t,e,i),A=r[0]-s[0],o=s[3]-r[0],a=r[1]-s[1],l=s[4]-r[1],c=r[2]-s[2],h=s[5]-r[2];return n[0]+=A>o?A:o,n[1]+=a>l?a:l,n[2]+=c>h?c:h,Math.abs(d.lenVec3(n))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||d.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||d.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=d.AABB3())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MAX_DOUBLE,e[3]=d.MIN_DOUBLE,e[4]=d.MIN_DOUBLE,e[5]=d.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=d.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new a(3);return(t,i,s)=>{i=i||d.AABB3();let r,n,A,o=d.MAX_DOUBLE,a=d.MAX_DOUBLE,l=d.MAX_DOUBLE,c=d.MIN_DOUBLE,h=d.MIN_DOUBLE,u=d.MIN_DOUBLE;for(let i=0,f=t.length;i<f;i+=3)s?(e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2],d.decompressPosition(e,s,e),r=e[0],n=e[1],A=e[2]):(r=t[i+0],n=t[i+1],A=t[i+2]),r<o&&(o=r),n<a&&(a=n),A<l&&(l=A),r>c&&(c=r),n>h&&(h=n),A>u&&(u=A);return i[0]=o,i[1]=a,i[2]=l,i[3]=c,i[4]=h,i[5]=u,i}})(),OBB3ToAABB3(e,t=d.AABB3()){let i,s,r,n=d.MAX_DOUBLE,A=d.MAX_DOUBLE,o=d.MAX_DOUBLE,a=d.MIN_DOUBLE,l=d.MIN_DOUBLE,c=d.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t+=4)i=e[t+0],s=e[t+1],r=e[t+2],i<n&&(n=i),s<A&&(A=s),r<o&&(o=r),i>a&&(a=i),s>l&&(l=s),r>c&&(c=r);return t[0]=n,t[1]=A,t[2]=o,t[3]=a,t[4]=l,t[5]=c,t},points3ToAABB3(e,t=d.AABB3()){let i,s,r,n=d.MAX_DOUBLE,A=d.MAX_DOUBLE,o=d.MAX_DOUBLE,a=d.MIN_DOUBLE,l=d.MIN_DOUBLE,c=d.MIN_DOUBLE;for(let t=0,h=e.length;t<h;t++)i=e[t][0],s=e[t][1],r=e[t][2],i<n&&(n=i),s<A&&(A=s),r<o&&(o=r),i>a&&(a=i),s>l&&(l=s),r>c&&(c=r);return t[0]=n,t[1]=A,t[2]=o,t[3]=a,t[4]=l,t[5]=c,t},points3ToSphere3:(()=>{const e=new a(3);return(t,i)=>{i=i||d.vec4();let s,r=0,n=0,A=0;const o=t.length;for(s=0;s<o;s++)r+=t[s][0],n+=t[s][1],A+=t[s][2];i[0]=r/o,i[1]=n/o,i[2]=A/o;let a,l=0;for(s=0;s<o;s++)a=Math.abs(d.lenVec3(d.subVec3(t[s],i,e))),a>l&&(l=a);return i[3]=l,i}})(),positions3ToSphere3:(()=>{const e=new a(3),t=new a(3);return(i,s)=>{s=s||d.vec4();let r,n=0,A=0,o=0;const a=i.length;let l=0;for(r=0;r<a;r+=3)n+=i[r],A+=i[r+1],o+=i[r+2];const c=a/3;let h;for(s[0]=n/c,s[1]=A/c,s[2]=o/c,r=0;r<a;r+=3)e[0]=i[r],e[1]=i[r+1],e[2]=i[r+2],h=Math.abs(d.lenVec3(d.subVec3(e,s,t))),h>l&&(l=h);return s[3]=l,s}})(),OBB3ToSphere3:(()=>{const e=new a(3),t=new a(3);return(i,s)=>{s=s||d.vec4();let r,n=0,A=0,o=0;const a=i.length,l=a/4;for(r=0;r<a;r+=4)n+=i[r+0],A+=i[r+1],o+=i[r+2];s[0]=n/l,s[1]=A/l,s[2]=o/l;let c,h=0;for(r=0;r<a;r+=4)e[0]=i[r+0],e[1]=i[r+1],e[2]=i[r+2],c=Math.abs(d.lenVec3(d.subVec3(e,s,t))),c>h&&(h=c);return s[3]=h,s}})(),getSphere3Center:(e,t=d.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=d.vec3()){let i=0,s=0,r=0;for(var n=0,A=e.length;n<A;n+=3)i+=e[n+0],s+=e[n+1],r+=e[n+2];const o=e.length/3;return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},expandAABB3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e),expandAABB3Point3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e),expandAABB3Points3(e,t){for(var i,s,r,n=0,A=t.length;n<A;n+=3)i=t[n],s=t[n+1],r=t[n+2],e[0]>i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]<i&&(e[3]=i),e[4]<s&&(e[4]=s),e[5]<r&&(e[5]=r);return e},collapseAABB2:(e=d.AABB2())=>(e[0]=d.MAX_DOUBLE,e[1]=d.MAX_DOUBLE,e[2]=d.MIN_DOUBLE,e[3]=d.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2],point3AABB3AbsoluteIntersect:(e,t)=>e[0]<=t[0]&&e[3]>=t[0]&&e[1]<=t[1]&&e[4]>=t[1]&&e[2]<=t[2]&&e[5]>=t[2],planeAABB3Intersect(e,t,i){let s,r;e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]);if(s<=-t&&r<=-t)return-1;return s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=d.AABB2()){let i,s,r,n,A=d.MAX_DOUBLE,o=d.MAX_DOUBLE,a=d.MIN_DOUBLE,l=d.MIN_DOUBLE;for(let t=0,c=e.length;t<c;t+=4)i=e[t+0],s=e[t+1],r=e[t+3]||1,n=1/r,i*=n,s*=n,i<A&&(A=i),s<o&&(o=s),i>a&&(a=i),s>l&&(l=s);return t[0]=A,t[1]=o,t[2]=a,t[3]=l,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e),expandAABB2Point2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e),AABB2ToCanvas(e,t,i,s=e){const r=.5*(e[0]+1),n=.5*(e[1]+1),A=.5*(e[2]+1),o=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(o*i),s[2]=Math.floor(A*t),s[3]=i-Math.floor(n*i),s},tangentQuadraticBezier:(e,t,i,s)=>2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const n=.5*(i-e),A=.5*(s-t),o=r*r;return(2*t-2*i+n+A)*(r*o)+(-3*t+3*i-2*n-A)*o+n*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=d.vec3()){const r=t[0]-e[0],n=t[1]-e[1],A=t[2]-e[2],o=i[0]-e[0],a=i[1]-e[1],l=i[2]-e[2],c=n*l-A*a,h=A*o-r*l,u=r*a-n*o,f=Math.sqrt(c*c+h*h+u*u);return 0===f?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/f,s[1]=h/f,s[2]=u/f),s},rayTriangleIntersect:(()=>{const e=new a(3),t=new a(3),i=new a(3),s=new a(3),r=new a(3);return(n,A,o,a,l,c)=>{c=c||d.vec3();const h=d.subVec3(a,o,e),u=d.subVec3(l,o,t),f=d.cross3Vec3(A,u,i),p=d.dotVec3(h,f);if(p<1e-6)return null;const g=d.subVec3(n,o,s),m=d.dotVec3(g,f);if(m<0||m>p)return null;const _=d.cross3Vec3(g,h,r),b=d.dotVec3(A,_);if(b<0||m+b>p)return null;const y=d.dotVec3(u,_)/p;return c[0]=n[0]+y*A[0],c[1]=n[1]+y*A[1],c[2]=n[2]+y*A[2],c}})(),rayPlaneIntersect:(()=>{const e=new a(3),t=new a(3),i=new a(3),s=new a(3);return(r,n,A,o,a,l)=>{l=l||d.vec3(),n=d.normalizeVec3(n,e);const c=d.subVec3(o,A,t),h=d.subVec3(a,A,i),u=d.cross3Vec3(c,h,s);d.normalizeVec3(u,u);const f=-d.dotVec3(A,u),p=-(d.dotVec3(r,u)+f)/d.dotVec3(n,u);return l[0]=r[0]+p*n[0],l[1]=r[1]+p*n[1],l[2]=r[2]+p*n[2],l}})(),cartesianToBarycentric:(()=>{const e=new a(3),t=new a(3),i=new a(3);return(s,r,n,A,o)=>{const a=d.subVec3(A,r,e),l=d.subVec3(n,r,t),c=d.subVec3(s,r,i),h=d.dotVec3(a,a),u=d.dotVec3(a,l),f=d.dotVec3(a,c),p=d.dotVec3(l,l),g=d.dotVec3(l,c),m=h*p-u*u;if(0===m)return null;const _=1/m,b=(p*f-u*g)*_,y=(h*g-u*f)*_;return o[0]=1-b-y,o[1]=y,o[2]=b,o}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=d.vec3()){const n=e[0],A=e[1],o=e[2];return r[0]=t[0]*n+i[0]*A+s[0]*o,r[1]=t[1]*n+i[1]*A+s[1]*o,r[2]=t[2]*n+i[2]*A+s[2]*o,r},mergeVertices(e,t,i,s){const r={},n=[],A=[],o=t?[]:null,a=i?[]:null,l=[];let c,h,u,d;const f=1e4;let p,g,m=0;for(p=0,g=e.length;p<g;p+=3)c=e[p],h=e[p+1],u=e[p+2],d=`${Math.round(c*f)}_${Math.round(h*f)}_${Math.round(u*f)}`,void 0===r[d]&&(r[d]=A.length/3,A.push(c),A.push(h),A.push(u),t&&(o.push(t[p]),o.push(t[p+1]),o.push(t[p+2])),i&&(a.push(i[m]),a.push(i[m+1]))),n[p/3]=r[d],m+=2;for(p=0,g=s.length;p<g;p++)l[p]=n[s[p]];const _={positions:A,indices:l};return o&&(_.normals=o),a&&(_.uv=a),_},buildNormals:(()=>{const e=new a(3),t=new a(3),i=new a(3),s=new a(3),r=new a(3),n=new a(3);return(A,o,a)=>{let l,c;const h=new Array(A.length/3);let u,f,p,g,m,_,b;for(l=0,c=o.length;l<c;l+=3){u=o[l],f=o[l+1],p=o[l+2],e[0]=A[3*u],e[1]=A[3*u+1],e[2]=A[3*u+2],t[0]=A[3*f],t[1]=A[3*f+1],t[2]=A[3*f+2],i[0]=A[3*p],i[1]=A[3*p+1],i[2]=A[3*p+2],d.subVec3(t,e,s),d.subVec3(i,e,r);const a=d.vec3();d.normalizeVec3(d.cross3Vec3(s,r,n),a),h[u]||(h[u]=[]),h[f]||(h[f]=[]),h[p]||(h[p]=[]),h[u].push(a),h[f].push(a),h[p].push(a)}for(a=a&&a.length===A.length?a:new Float32Array(A.length),l=0,c=h.length;l<c;l++){g=h[l].length,m=0,_=0,b=0;for(let e=0;e<g;e++)m+=h[l][e][0],_+=h[l][e][1],b+=h[l][e][2];a[3*l]=m/g,a[3*l+1]=_/g,a[3*l+2]=b/g}return a}})(),buildTangents:(()=>{const e=new a(3),t=new a(3),i=new a(3),s=new a(3),r=new a(3),n=new a(3),A=new a(3);return(o,a,l)=>{const c=new Float32Array(o.length);for(let h=0;h<a.length;h+=3){let u=a[h];const f=o.subarray(3*u,3*u+3),p=l.subarray(2*u,2*u+2);u=a[h+1];const g=o.subarray(3*u,3*u+3),m=l.subarray(2*u,2*u+2);u=a[h+2];const _=o.subarray(3*u,3*u+3),b=l.subarray(2*u,2*u+2),y=d.subVec3(g,f,e),w=d.subVec3(_,f,t),v=d.subVec2(m,p,i),B=d.subVec2(b,p,s),C=1/(v[0]*B[1]-v[1]*B[0]),M=d.mulVec3Scalar(d.subVec3(d.mulVec3Scalar(y,B[1],r),d.mulVec3Scalar(w,v[1],n),A),C,n);let E;for(let e=0;e<3;e++)E=3*a[h+e],c[E]+=M[0],c[E+1]+=M[1],c[E+2]+=M[2]}return c}})(),buildPickTriangles(e,t,i){const s=t.length,r=i?new Uint16Array(9*s):new Float32Array(9*s),n=new Uint8Array(12*s);let A,o,a,l,c,h,u=0,d=0,f=0;for(let i=0;i<s;i+=3)h=u>>24&255,c=u>>16&255,l=u>>8&255,a=255&u,o=t[i],A=3*o,r[d++]=e[A],r[d++]=e[A+1],r[d++]=e[A+2],n[f++]=a,n[f++]=l,n[f++]=c,n[f++]=h,o=t[i+1],A=3*o,r[d++]=e[A],r[d++]=e[A+1],r[d++]=e[A+2],n[f++]=a,n[f++]=l,n[f++]=c,n[f++]=h,o=t[i+2],A=3*o,r[d++]=e[A],r[d++]=e[A+1],r[d++]=e[A+2],n[f++]=a,n[f++]=l,n[f++]=c,n[f++]=h,u++;return{positions:r,colors:n}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},n=[],A={};let o,a,l,c,h;const u=1e4;let f,p,g,m,_,b;for(p=0,m=e.length;p<m;p+=3){f=p/3,a=e[p],l=e[p+1],c=e[p+2],h=`${Math.round(a*u)}_${Math.round(l*u)}_${Math.round(c*u)}`,void 0===r[h]?r[h]=[f]:r[h].push(f);const i=d.normalizeVec3([t[p],t[p+1],t[p+2]]);n[f]=i,o=d.vec4([i[0],i[1],i[2],1]),A[f]=o}for(h in r)if(r.hasOwnProperty(h)){const e=r[h],t=e.length;for(p=0;p<t;p++){const i=e[p];for(o=A[i],g=0;g<t;g++){if(p===g)continue;const t=e[g];_=n[i],b=n[t];Math.abs(d.angleVec3(_,b)/d.DEGTORAD)<s&&(o[0]+=b[0],o[1]+=b[1],o[2]+=b[2],o[3]+=1)}}}for(p=0,m=t.length;p<m;p+=3)o=A[p/3],t[p+0]=o[0]/o[3],t[p+1]=o[1]/o[3],t[p+2]=o[2]/o[3]},transformRay:(()=>{const e=new a(4),t=new a(4);return(i,s,r,n,A)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],e[3]=1,d.transformVec4(i,e,t),n[0]=t[0],n[1]=t[1],n[2]=t[2],e[0]=r[0],e[1]=r[1],e[2]=r[2],d.transformVec3(i,e,t),d.normalizeVec3(t),A[0]=t[0],A[1]=t[1],A[2]=t[2]}})(),canvasPosToWorldRay:(()=>{const e=new a(16),t=new a(4),i=new a(4),s=(t,i,s,r,n)=>{n[0]=t,n[1]=i,n[2]=s,n[3]=1,d.transformVec4(e,n,n),r||d.mulVec4Scalar(n,1/n[3])};return(r,n,A,o,a,l,c)=>{const h="ortho"===o;d.mulMat4(A,n,e),d.inverseMat4(e,e);const u=2*a[0]/r.clientWidth-1,f=1-2*a[1]/r.clientHeight;s(u,f,-1,h,t),s(u,f,1,h,i),l[0]=t[0],l[1]=t[1],l[2]=t[2],d.subVec3(i,t,c),d.normalizeVec3(c)}})(),canvasPosToLocalRay:(()=>{const e=new a(3),t=new a(3);return(i,s,r,n,A,o,a,l)=>{d.canvasPosToWorldRay(i,s,r,n,o,e,t),d.worldRayToLocalRay(A,e,t,a,l)}})(),worldRayToLocalRay:(()=>{const e=new a(16),t=new a(4),i=new a(4);return(s,r,n,A,o)=>{const a=d.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(a,t,i),A[0]=i[0],A[1]=i[1],A[2]=i[2],d.transformVec3(a,n,o)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,n){const A=new a(6),o={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:A};let l,c;for(A[0]=A[1]=A[2]=Number.POSITIVE_INFINITY,A[3]=A[4]=A[5]=Number.NEGATIVE_INFINITY,l=0,c=i.length;l<c;++l){var h=3*i[l];for(let e=0;e<3;++e){const t=3*s[h+e];r[t]<A[0]&&(A[0]=r[t]),r[t]>A[3]&&(A[3]=r[t]),r[t+1]<A[1]&&(A[1]=r[t+1]),r[t+1]>A[4]&&(A[4]=r[t+1]),r[t+2]<A[2]&&(A[2]=r[t+2]),r[t+2]>A[5]&&(A[5]=r[t+2])}}if(i.length<20||n>10)return o.triangles=i,o.leaf=!0,o;e[0]=A[3]-A[0],e[1]=A[4]-A[1],e[2]=A[5]-A[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),o.splitDim=u;const d=(A[u]+A[u+3])/2,f=new Array(i.length);let p=0;const g=new Array(i.length);let m=0;for(l=0,c=i.length;l<c;++l){const e=s[h=3*i[l]],t=3*s[h+1],n=3*s[h+2];r[3*e+u]<=d||r[t+u]<=d||r[n+u]<=d?f[p++]=i[l]:g[m++]=i[l]}return f.length=p,g.length=m,o.left=t(f,s,r,n+1),o.right=t(g,s,r,n+1),o}return(e,i)=>{const s=e.length/3,r=new Array(s);for(let e=0;e<s;++e)r[e]=e;return t(r,e,i,0)}})(),decompressPosition(e,t,i){(i=i||e)[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressUV(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},octDecodeVec2(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],n=e[i+1];r=(2*r+1)/255,n=(2*n+1)/255;const A=1-Math.abs(r)-Math.abs(n);A<0&&(r=(1-Math.abs(n))*(r>=0?1:-1),n=(1-Math.abs(r))*(n>=0?1:-1));const o=Math.sqrt(r*r+n*n+A*A);t[s+0]=r/o,t[s+1]=n/o,t[s+2]=A/o,s+=3}return t}};d.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let n=0;const A=new Uint16Array(3),o=new Uint16Array(3),a=new Uint16Array(3),l=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),f=d.vec3(),p=d.vec3(),g=d.vec3();return function(m,_,b,y){!function(r,n){const A={};let o,a,l,c;const h=Math.pow(10,4);let u,d,f=0;for(u=0,d=r.length;u<d;u+=3)o=r[u],a=r[u+1],l=r[u+2],c=Math.round(o*h)+"_"+Math.round(a*h)+"_"+Math.round(l*h),void 0===A[c]&&(A[c]=f/3,e[f++]=o,e[f++]=a,e[f++]=l),t[u/3]=A[c];for(u=0,d=n.length;u<d;u++)s[u]=t[n[u]],i[s[u]]=n[u]}(m,_),function(t,i){n=0;for(let m=0,_=t;m<_;m+=3){const t=3*s[m],_=3*s[m+1],b=3*s[m+2];i?(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],o[0]=e[_],o[1]=e[_+1],o[2]=e[_+2],a[0]=e[b],a[1]=e[b+1],a[2]=e[b+2],d.decompressPosition(A,i,l),d.decompressPosition(o,i,c),d.decompressPosition(a,i,h)):(l[0]=e[t],l[1]=e[t+1],l[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],h[0]=e[b],h[1]=e[b+1],h[2]=e[b+2]),d.subVec3(h,c,u),d.subVec3(l,c,f),d.cross3Vec3(u,f,p),d.normalizeVec3(p,g);const y=r[n]||(r[n]={normal:d.vec3()});y.normal[0]=g[0],y.normal[1]=g[1],y.normal[2]=g[2],n++}}(_.length,b);const w=[],v=Math.cos(d.DEGTORAD*y),B={};let C,M,E,F,U,x,I,T,P,S,D,k=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)C=s[e+i],M=s[e+(i+1)%3],E=Math.min(C,M),F=Math.max(C,M),U=E+","+F,void 0===B[U]?B[U]={index1:E,index2:F,face1:t,face2:void 0}:B[U].face2=t}for(U in B)x=B[U],void 0!==x.face2&&(I=r[x.face1].normal,T=r[x.face2].normal,P=d.dotVec3(I,T),P>v)||(S=i[x.index1],D=i[x.index2],(!k&&S>65535||D>65535)&&(k=!0),w.push(S),w.push(D));return k?new Uint32Array(w):new Uint16Array(w)}}(),d.planeClipsPositions3=function(e,t,i,s=3){for(let r=0,n=i.length;r<n;r+=s){if(l[0]=i[r+0]-e[0],l[1]=i[r+1]-e[1],l[2]=i[r+2]-e[2],l[0]*t[0]+l[1]*t[1]+l[2]*t[2]<0)return!0}return!1};const f=new Float32Array(3);class p{constructor(e){if(!e)throw"Parameter expected: cfg";if(!e.viewer)throw"Parameter expected: cfg.viewer";this.viewer=e.viewer,this._maxTreeDepth=e.maxTreeDepth||15,this._root=null,this._needsRebuild=!0,this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{this._needsRebuild=!0})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this._needsRebuild=!0}))}get root(){return this._needsRebuild&&this._rebuild(),this._root}_rebuild(){const e=this.viewer.scene;this._root={aabb:e.getAABB()};for(let t in e.objects){const i=e.objects[t];this._insertEntity(this._root,i,1)}this._needsRebuild=!1}_insertEntity(e,t,i){const s=t.aabb;if(i>=this._maxTreeDepth)return e.entities=e.entities||[],void e.entities.push(t);if(e.left&&d.containsAABB3(e.left.aabb,s))return void this._insertEntity(e.left,t,i+1);if(e.right&&d.containsAABB3(e.right.aabb,s))return void this._insertEntity(e.right,t,i+1);const r=e.aabb;f[0]=r[3]-r[0],f[1]=r[4]-r[1],f[2]=r[5]-r[2];let n=0;if(f[1]>f[n]&&(n=1),f[2]>f[n]&&(n=2),!e.left){const A=r.slice();if(A[n+3]=(r[n]+r[n+3])/2,e.left={aabb:A},d.containsAABB3(A,s))return void this._insertEntity(e.left,t,i+1)}if(!e.right){const A=r.slice();if(A[n]=(r[n]+r[n+3])/2,e.right={aabb:A},d.containsAABB3(A,s))return void this._insertEntity(e.right,t,i+1)}e.entities=e.entities||[],e.entities.push(t)}destroy(){const e=this.viewer.scene;e.off(this._onModelLoaded),e.off(this._onModelUnloaded),this._root=null,this._needsRebuild=!0}}class g{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}}const m={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var _=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r<s;++r)t.push(r);return String.fromCharCode.apply(null,t)})).join("");function b(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return _.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}const y=function(){for(var e={},t=window.location.search.substring(1).split("&"),i=0;i<t.length;i++){var s=t[i].split("=");if(void 0===e[s[0]])e[s[0]]=decodeURIComponent(s[1]);else if("string"==typeof e[s[0]]){var r=[e[s[0]],decodeURIComponent(s[1])];e[s[0]]=r}else e[s[0]].push(decodeURIComponent(s[1]))}return e}();const w={xmlToJson:function e(t,i){if(t.nodeType===t.TEXT_NODE){var s=t.nodeValue;if(null===s.match(/^\s+$/))return s}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var r={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var n=0;n<t.attributes.length;n++){var A=t.attributes[n];r[i[A.nodeName]||A.nodeName]=A.nodeValue}for(var o=0;o<t.childNodes.length;o++){(n=e(t.childNodes[o],i))&&r.children.push(n)}return r}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return b(t[0],2)+[1,4,7,10,13].map((function(e){return b((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var i=[],s=function(e){e.type===t&&i.push(e),(e.children||[]).forEach((function(e){s(e)}))};return s(e),i},timeout:function(e){return new Promise((function(t,i){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,i){var s=new XMLHttpRequest;s.open(e.method||"GET",e.url,!0),s.onload=function(e){4===s.readyState&&(200===s.status?t(s.responseXML):i(s.statusText))},s.send(null)}))},loadJSON:function(e,t,i){var s=e=>{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const e=!!r[2];var n=r[3];n=window.decodeURIComponent(n),e&&(n=window.atob(n));try{const e=new ArrayBuffer(n.length),i=new Uint8Array(e);for(var A=0;A<n.length;A++)i[A]=n.charCodeAt(A);I.scheduleTask((()=>{t(e)}))}catch(e){I.scheduleTask((()=>{i(e)}))}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:y,isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return w.isString(e)||w.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(w.isNumeric(e)||w.isString(e)?`${e}`:e.id)===(w.isNumeric(t)||w.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return w.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return w.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,n=s.length;r<n;r++){s[r].parent=i.id,e(s[r])}i.children=[]}(e),t}},v={},B=new e,C=new g,M={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},E=[];let F,U=0,x=0;const I=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(I.scenes[e.id])return void console.error(`[ERROR] Scene ${w.inQuotes(e.id)} already exists`)}else e.id=B.addItem({});I.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;v[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},m.components.scenes++,e.once("destroyed",(()=>{B.removeItem(e.id),delete I.scenes[e.id],delete v[e.id],m.components.scenes--}))},this.clear=function(){let e;for(const t in I.scenes)I.scenes.hasOwnProperty(t)&&(e=I.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete I.scenes[e.id]))},this.scheduleTask=function(e,t=null){C.push(e),C.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;C.length>0&&(e<0||s<e);)t=C.shift(),i=C.shift(),i?t.call(i):t(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return C.length}},T=function(){let e=Date.now();if(F=e-U,U>0&&F>0){var t=1e3/F;x+=t,E.push(t),E.length>=30&&(x-=E.shift()),m.frame.fps=Math.round(x/E.length)}for(let e in I.scenes)I.scenes[e].compile();S(e),U=e};!function(e,t){let i=Date.now()+t;(function s(){const r=Date.now()-i;e(),i+=t,setTimeout(s,Math.max(0,t-r))})()}((()=>{T()}),100);const P=function(){let e=Date.now();if(F=e-U,U>0&&F>0){var t=1e3/F;x+=t,E.push(t),E.length>=30&&(x-=E.shift()),m.frame.fps=Math.round(x/E.length)}S(e),function(e){for(var t in M.time=e,I.scenes)if(I.scenes.hasOwnProperty(t)){var i=I.scenes[t];M.sceneId=t,M.startTime=i.startTime,M.deltaTime=null!=M.prevTime?M.time-M.prevTime:0,i.fire("tick",M,!0)}M.prevTime=e}(e),function(){const e=I.scenes,t=!1;let i,s,r,n,A;for(A in e)e.hasOwnProperty(A)&&(i=e[A],s=v[A],s||(s=v[A]={}),r=i.ticksPerOcclusionTest,s.ticksPerOcclusionTest!==r&&(s.ticksPerOcclusionTest=r,s.renderCountdown=r),--i.occlusionTestCountdown<=0&&(i.doOcclusionTest(),i.occlusionTestCountdown=r),n=i.ticksPerRender,s.ticksPerRender!==n&&(s.ticksPerRender=n,s.renderCountdown=n),0==--s.renderCountdown&&(i.render(t),s.renderCountdown=n))}(),void 0!==window.requestPostAnimationFrame?window.requestPostAnimationFrame(T):requestAnimationFrame(P)};function S(e){const t=I.runTasks(e+10),i=I.getNumTasks();m.frame.tasksRun=t,m.frame.tasksScheduled=i,m.frame.tasksBudget=10}P();class D{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof D))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const n=this._subIdMap.addItem();r[n]={callback:i,scope:s||this},this._subIdEvents[n]=t;const A=this._events[t];return void 0!==A&&i.call(s||this,A),n}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+w.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,n=e.type,A=e.on,o=!1!==e.recompiles;if(i&&(w.isNumeric(i)||w.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+w.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[n];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+w.inQuotes(i.id));if(n&&!i.isType(n))return void this.error("Expected a "+n+" type or subtype: "+i.type+" "+w.inQuotes(i.id))}this._attachments||(this._attachments={});const a=this._attached[t];let l,c,h;if(a){if(i&&a.id===i.id)return;const e=this._attachments[a.id];for(l=e.subs,c=0,h=l.length;c<h;c++)a.off(l[c]);delete this._attached[t],delete this._attachments[a.id];const s=e.params.onDetached;s&&(w.isFunction(s)?s(a):s.scope?s.callback.call(s.scope,a):s.callback(a)),e.managingLifecycle&&a.destroy()}if(i){const s={params:e,component:i,subs:[],managingLifecycle:false};s.subs.push(i.once("destroyed",(function(){s.params.component=null,this._attach(s.params)}),this)),o&&s.subs.push(i.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=i,this._attachments[i.id]=s;const r=e.onAttached;if(r&&(w.isFunction(r)?r(i):r.scope?r.callback.call(r.scope,i):r.callback(i)),A){let e,t,r,n;for(e in A)if(A.hasOwnProperty(e)){if(t=A[e],w.isFunction(t)?(r=t,n=null):(r=t.callback,n=t.scope),!r)continue;s.subs.push(i.on(e,r,n))}}}return o&&this.fire("dirty",this),this.fire(t,i),i}_checkComponent(e,t){if(!t.isComponent){if(!w.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}_checkComponent2(e,t){if(!t.isComponent){if(!w.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(t.scene.id===this.scene.id){for(var i=0,s=e.length;i<s;i++)if(e[i]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}_own(e){this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(()=>{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():I.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}scheduleTask(e){I.scheduleTask(e,null)}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)if(this._ownedComponents.hasOwnProperty(e)){this._ownedComponents[e].destroy(),delete this._ownedComponents[e]}}destroy(){if(this.destroyed)return;let e,t,i,s,r,n;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,n=s.length;r<n;r++)i.off(s[r]);t.managingLifecycle&&i.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(i=this._ownedComponents[e],i.destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}const k=d.vec3(),Q=d.vec3(),R=d.mat4();class O{constructor(){this.normal=d.vec3(),this.offset=0,this.testVertex=d.vec3()}set(e,t,i,s){const r=1/Math.sqrt(e*e+t*t+i*i);this.normal[0]=e*r,this.normal[1]=t*r,this.normal[2]=i*r,this.offset=s*r,this.testVertex[0]=this.normal[0]>=0?1:0,this.testVertex[1]=this.normal[1]>=0?1:0,this.testVertex[2]=this.normal[2]>=0?1:0}}class V{constructor(){this.planes=[new O,new O,new O,new O,new O,new O]}}function L(e,t,i){const s=d.mulMat4(i,t,R),r=s[0],n=s[1],A=s[2],o=s[3],a=s[4],l=s[5],c=s[6],h=s[7],u=s[8],f=s[9],p=s[10],g=s[11],m=s[12],_=s[13],b=s[14],y=s[15];e.planes[0].set(o-r,h-a,g-u,y-m),e.planes[1].set(o+r,h+a,g+u,y+m),e.planes[2].set(o-n,h-l,g-f,y-_),e.planes[3].set(o+n,h+l,g+f,y+_),e.planes[4].set(o-A,h-c,g-p,y-b),e.planes[5].set(o+A,h+c,g+p,y+b)}function H(e,t){let i=V.INSIDE;const s=k,r=Q;s[0]=t[0],s[1]=t[1],s[2]=t[2],r[0]=t[3],r[1]=t[4],r[2]=t[5];const n=[s,r];for(let t=0;t<6;++t){const s=e.planes[t];if(s.normal[0]*n[s.testVertex[0]][0]+s.normal[1]*n[s.testVertex[1]][1]+s.normal[2]*n[s.testVertex[2]][2]+s.offset<0)return V.OUTSIDE;s.normal[0]*n[1-s.testVertex[0]][0]+s.normal[1]*n[1-s.testVertex[1]][1]+s.normal[2]*n[1-s.testVertex[2]][2]+s.offset<0&&(i=V.INTERSECT)}return i}V.INSIDE=0,V.INTERSECT=1,V.OUTSIDE=2;class N extends D{constructor(e={}){if(!e.viewer)throw"[MarqueePicker] Missing config: viewer";if(!e.objectsKdTree3)throw"[MarqueePicker] Missing config: objectsKdTree3";super(e.viewer.scene,e),this.viewer=e.viewer,this._objectsKdTree3=e.objectsKdTree3,this._canvasMarqueeCorner1=d.vec2(),this._canvasMarqueeCorner2=d.vec2(),this._canvasMarquee=d.AABB2(),this._marqueeFrustum=new V,this._marqueeFrustumProjMat=d.mat4(),this._pickMode=!1,this._marqueeElement=document.createElement("div"),document.body.appendChild(this._marqueeElement),this._marqueeElement.style.position="absolute",this._marqueeElement.style["z-index"]="40000005",this._marqueeElement.style.width="8px",this._marqueeElement.style.height="8px",this._marqueeElement.style.visibility="hidden",this._marqueeElement.style.top="0px",this._marqueeElement.style.left="0px",this._marqueeElement.style["box-shadow"]="0 2px 5px 0 #182A3D;",this._marqueeElement.style.opacity=1,this._marqueeElement.style["pointer-events"]="none"}setMarqueeCorner1(e){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarqueeCorner2(e){this._canvasMarqueeCorner2.set(e),this._updateMarquee()}setMarquee(e,t){this._canvasMarqueeCorner1.set(e),this._canvasMarqueeCorner2.set(t),this._updateMarquee()}setMarqueeVisible(e){this._marqueVisible=e,this._marqueeElement.style.visibility=e?"visible":"hidden"}getMarqueeVisible(){return this._marqueVisible}setPickMode(e){if(e!==N.PICK_MODE_INSIDE&&e!==N.PICK_MODE_INTERSECTS)throw"Illegal MarqueePicker pickMode: must be MarqueePicker.PICK_MODE_INSIDE or MarqueePicker.PICK_MODE_INTERSECTS";e!==this._pickMode&&(this._marqueeElement.style["background-image"]=e===N.PICK_MODE_INSIDE?"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4'/%3e%3c/svg%3e\")":"url(\"data:image/svg+xml,%3csvg width='100%25' height='100%25' xmlns='http://www.w3.org/2000/svg'%3e%3crect width='100%25' height='100%25' fill='none' rx='6' ry='6' stroke='%23333' stroke-width='4' stroke-dasharray='6%2c 14' stroke-dashoffset='0' stroke-linecap='square'/%3e%3c/svg%3e\")",this._pickMode=e)}getPickMode(){return this._pickMode}clear(){this.fire("clear",{})}pick(){this._updateMarquee(),this._buildMarqueeFrustum();const e=[],t=(i,s=V.INTERSECT)=>{if(s===V.INTERSECT&&(s=H(this._marqueeFrustum,i.aabb)),s!==V.OUTSIDE){if(i.entities){const t=i.entities;for(let i=0,s=t.length;i<s;i++){const s=t[i];if(!s.visible)continue;const r=s.aabb;if(this._pickMode===N.PICK_MODE_INSIDE){H(this._marqueeFrustum,r)===V.INSIDE&&e.push(s.id)}else{H(this._marqueeFrustum,r)!==V.OUTSIDE&&e.push(s.id)}}}i.left&&t(i.left,s),i.right&&t(i.right,s)}};return(this._canvasMarquee[2]-this._canvasMarquee[0]>3||this._canvasMarquee[3]-this._canvasMarquee[1]>3)&&t(this._objectsKdTree3.root),this.fire("picked",e),e}_updateMarquee(){this._canvasMarquee[0]=Math.min(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[1]=Math.min(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._canvasMarquee[2]=Math.max(this._canvasMarqueeCorner1[0],this._canvasMarqueeCorner2[0]),this._canvasMarquee[3]=Math.max(this._canvasMarqueeCorner1[1],this._canvasMarqueeCorner2[1]),this._marqueeElement.style.width=this._canvasMarquee[2]-this._canvasMarquee[0]+"px",this._marqueeElement.style.height=this._canvasMarquee[3]-this._canvasMarquee[1]+"px",this._marqueeElement.style.left=`${this._canvasMarquee[0]}px`,this._marqueeElement.style.top=`${this._canvasMarquee[1]}px`}_buildMarqueeFrustum(){const e=this.viewer.scene.canvas.canvas,t=e.clientWidth,i=e.clientHeight,s=e.clientLeft,r=e.clientTop,n=2/t,A=2/i,o=e.clientHeight/e.clientWidth,a=(this._canvasMarquee[0]-s)*n-1,l=(this._canvasMarquee[2]-s)*n-1,c=-(this._canvasMarquee[3]-r)*A+1,h=-(this._canvasMarquee[1]-r)*A+1,u=this.viewer.scene.camera.frustum.near*(17*o);d.frustumMat4(a,l,c*o,h*o,u,1e4,this._marqueeFrustumProjMat),L(this._marqueeFrustum,this.viewer.scene.camera.viewMatrix,this._marqueeFrustumProjMat)}destroy(){super.destroy(),this._marqueeElement.parentElement&&(this._marqueeElement.parentElement.removeChild(this._marqueeElement),this._marqueeElement=null,this._objectsKdTree3=null)}}N.PICK_MODE_INTERSECTS=0,N.PICK_MODE_INSIDE=1;class G extends D{constructor(e){super(e.marqueePicker,e);const t=e.marqueePicker,i=t.viewer.scene.canvas.canvas;let s,r,n,A,o,a,l,c=!1,h=!1,u=!1;i.addEventListener("mousedown",(e=>{this.getActive()&&0===e.button&&(l=setTimeout((function(){const n=t.viewer.scene.input;n.keyDown[n.KEY_CTRL]||t.clear(),s=e.pageX,r=e.pageY,o=e.offsetX,t.setMarqueeCorner1([s,r]),c=!0,t.viewer.cameraControl.pointerEnabled=!1,t.setMarqueeVisible(!0),i.style.cursor="crosshair"}),400),h=!0)})),i.addEventListener("mouseup",(e=>{if(!this.getActive())return;if(!c&&!u)return;if(0!==e.button)return;clearTimeout(l),n=e.pageX,A=e.pageY;const i=Math.abs(n-s),o=Math.abs(A-r);c=!1,t.viewer.cameraControl.pointerEnabled=!0,u&&(u=!1),(i>3||o>3)&&t.pick()})),document.addEventListener("mouseup",(e=>{this.getActive()&&0===e.button&&(clearTimeout(l),c&&(t.setMarqueeVisible(!1),c=!1,h=!1,u=!0,t.viewer.cameraControl.pointerEnabled=!0))}),!0),i.addEventListener("mousemove",(e=>{this.getActive()&&0===e.button&&h&&(clearTimeout(l),c&&(n=e.pageX,A=e.pageY,a=e.offsetX,t.setMarqueeVisible(!0),t.setMarqueeCorner2([n,A]),t.setPickMode(o<a?N.PICK_MODE_INSIDE:N.PICK_MODE_INTERSECTS)))}))}setActive(e){this._active!==e&&(this._active=e,this.fire("active",this._active))}getActive(){return this._active}destroy(){}}class j{constructor(e,t={}){this.viewer=e,this.scene=this.viewer.scene,this._circleDiv=document.createElement("div"),this.viewer.scene.canvas.canvas.parentNode.insertBefore(this._circleDiv,this.viewer.scene.canvas.canvas),this._circleDiv.style.backgroundColor="transparent",this._circleDiv.style.border="2px solid green",this._circleDiv.style.borderRadius="50px",this._circleDiv.style.width="50px",this._circleDiv.style.height="50px",this._circleDiv.style.margin="-200px -200px",this._circleDiv.style.zIndex="100000",this._circleDiv.style.position="absolute",this._circleDiv.style.pointerEvents="none",this._circlePos=null,this._circleMaxRadius=200,this._circleMinRadius=2,this._active=!1!==t.active,this._visible=!1,this._running=!1,this._destroyed=!1}start(e){if(this._destroyed)return;this._circlePos=e,this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius+"px";const t=this._circleMaxRadius;let i;const s=e=>{if(!this._running)return;i||(i=e);const r=e-i,n=Math.min(r/300,1),A=t+(2-t)*n;this._circleRadius=A,this._circleDiv.style.width=`${this._circleRadius}px`,this._circleDiv.style.height=`${this._circleRadius}px`,this._circleDiv.style.marginLeft=this._circlePos[0]-this._circleRadius/2+"px",this._circleDiv.style.marginTop=this._circlePos[1]-this._circleRadius/2+"px",n<1&&requestAnimationFrame(s)};this._running=!0,requestAnimationFrame(s),this._circleDiv.style.visibility="visible"}stop(){this._destroyed||(this._running=!1,this._circleRadius=this._circleMaxRadius,this._circleDiv.style.borderRadius=`${this._circleRadius}px`,this._circleDiv.style.visibility="hidden")}set durationMs(e){this.stop(),this._durationMs=e}get durationMs(){return this._durationMs}destroy(){this._destroyed||(this.stop(),this._circleDiv.parentElement.removeChild(this._circleDiv),this._destroyed=!0)}}class W{constructor(e={}){this._eventSubIDMap=null,this._eventSubEvents=null,this._eventSubs=null,this._events=null,this._locale="en",this._messages={},this._locales=[],this._locale="en",this.messages=e.messages,this.locale=e.locale}set messages(e){this._messages=e||{},this._locales=Object.keys(this._messages),this.fire("updated",this)}loadMessages(e={}){for(let t in e)this._messages[t]=e[t];this.messages=this._messages}clearMessages(){this.messages={}}get locales(){return this._locales}set locale(e){e=e||"de",this._locale!==e&&(this._locale=e,this.fire("updated",e))}get locale(){return this._locale}translate(e,t){const i=this._messages[this._locale];if(!i)return null;const s=z(e,i);return s?t?X(s,t):s:null}translatePlurals(e,t,i){const s=this._messages[this._locale];if(!s)return null;let r=z(e,s);return r=0===(t=parseInt(""+t,10))?r.zero:t>1?r.other:r.one,r?(r=X(r,[t]),i&&(r=X(r,i)),r):null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];if(s)for(const e in s)if(s.hasOwnProperty(e)){s[e].callback(t)}}on(t,i){this._events||(this._events={}),this._eventSubIDMap||(this._eventSubIDMap=new e),this._eventSubEvents||(this._eventSubEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[t];s||(s={},this._eventSubs[t]=s);const r=this._eventSubIDMap.addItem();s[r]={callback:i},this._eventSubEvents[r]=t;const n=this._events[t];return void 0!==n&&i(n),r}off(e){if(null==e)return;if(!this._eventSubEvents)return;const t=this._eventSubEvents[e];if(t){delete this._eventSubEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._eventSubIDMap.removeItem(e)}}}function z(e,t){if(t[e])return t[e];const i=e.split(".");let s=t;for(let e=0,t=i.length;s&&e<t;e++){s=s[i[e]]}return s}function X(e,t=[]){return e.replace(/\{\{|\}\}|\{(\d+)\}/g,(function(e,i){return"{{"===e?"{":"}}"===e?"}":t[i]}))}class K extends D{constructor(e,t={}){super(e,t),this.t=t.t}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get tangent(){return this.getTangent(this._t)}get length(){var e=this._getLengths();return e[e.length-1]}getTangent(e){var t=1e-4;void 0===e&&(e=this._t);var i=e-t,s=e+t;i<0&&(i=0),s>1&&(s=1);var r=this.getPoint(i),n=this.getPoint(s),A=d.subVec3(n,r,[]);return d.normalizeVec3(A,[])}getPointAt(e){var t=this.getUToTMapping(e);return this.getPoint(t)}getPoints(e){e||(e=5);var t,i=[];for(t=0;t<=e;t++)i.push(this.getPoint(t/e));return i}_getLengths(e){if(e||(e=this.__arcLengthDivisions?this.__arcLengthDivisions:200),this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;var t,i,s=[],r=this.getPoint(0),n=0;for(s.push(0),i=1;i<=e;i++)t=this.getPoint(i/e),n+=d.lenVec3(d.subVec3(t,r,[])),s.push(n),r=t;return this.cacheArcLengths=s,s}_updateArcLengths(){this.needsUpdate=!0,this._getLengths()}getUToTMapping(e,t){var i,s=this._getLengths(),r=0,n=s.length;i=t||e*s[n-1];for(var A,o=0,a=n-1;o<=a;)if((A=s[r=Math.floor(o+(a-o)/2)]-i)<0)o=r+1;else{if(!(A>0)){a=r;break}a=r-1}if(s[r=a]===i)return r/(n-1);var l=s[r];return(r+(i-l)/(s[r+1]-l))/(n-1)}}class Z extends K{constructor(e,t={}){super(e,t),this.points=t.points,this.t=t.t}set points(e){this._points=e||[]}get points(){return this._points}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=this.points;if(!(t.length<3)){var i=(t.length-1)*e,s=Math.floor(i),r=i-s,n=t[0===s?s:s-1],A=t[s],o=t[s>t.length-2?t.length-1:s+1],a=t[s>t.length-3?t.length-1:s+2],l=d.vec3();return l[0]=d.catmullRomInterpolate(n[0],A[0],o[0],a[0],r),l[1]=d.catmullRomInterpolate(n[1],A[1],o[1],a[1],r),l[2]=d.catmullRomInterpolate(n[2],A[2],o[2],a[2],r),l}this.error("Can't sample point from SplineCurve - not enough points on curve - returning [0,0,0].")}getJSON(){return{points:points,t:this._t}}}const J=d.vec3();class Y extends D{get type(){return"CameraPath"}constructor(e,t={}){super(e,t),this._frames=[],this._eyeCurve=new Z(this),this._lookCurve=new Z(this),this._upCurve=new Z(this),t.frames&&(this.addFrames(t.frames),this.smoothFrameTimes(1))}get frames(){return this._frames}get eyeCurve(){return this._eyeCurve}get lookCurve(){return this._lookCurve}get upCurve(){return this._upCurve}saveFrame(e){const t=this.scene.camera;this.addFrame(e,t.eye,t.look,t.up)}addFrame(e,t,i,s){const r={t:e,eye:t.slice(0),look:i.slice(0),up:s.slice(0)};this._frames.push(r),this._eyeCurve.points.push(r.eye),this._lookCurve.points.push(r.look),this._upCurve.points.push(r.up)}addFrames(e){let t;for(let i=0,s=e.length;i<s;i++)t=e[i],this.addFrame(t.t||0,t.eye,t.look,t.up)}loadFrame(e){const t=this.scene.camera;e=(e/=this._frames[this._frames.length-1].t-this._frames[0].t)<0?0:e>1?1:e,t.eye=this._eyeCurve.getPoint(e,J),t.look=this._lookCurve.getPoint(e,J),t.up=this._upCurve.getPoint(e,J)}sampleFrame(e,t,i,s){e=e<0?0:e>1?1:e,this._eyeCurve.getPoint(e,t),this._lookCurve.getPoint(e,i),this._upCurve.getPoint(e,s)}smoothFrameTimes(e){if(0===this._frames.length)return;const t=d.vec3();var i=0;this._frames[0].t=0;const s=[];for(let e=1,n=this._frames.length;e<n;e++){var r=d.lenVec3(d.subVec3(this._frames[e].eye,this._frames[e-1].eye,t));s[e]=r,i+=r}for(let t=1,r=this._frames.length;t<r;t++){const r=s[t]/i*e;this._frames[t].t=this._frames[t-1].t+r}}clearFrames(){this._frames=[],this._eyeCurve.points=[],this._lookCurve.points=[],this._upCurve.points=[]}}const $=d.vec3(),q=d.vec3(),ee=d.vec3(),te=d.vec3(),ie=d.vec3();class se extends D{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=d.vec3(),this._eye1=d.vec3(),this._up1=d.vec3(),this._look2=d.vec3(),this._eye2=d.vec3(),this._up2=d.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let n,A,o,a,l;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)n=e.aabb;else if(6===e.length)n=e;else if(e.eye&&e.look||e.up)A=e.eye,o=e.look,a=e.up;else if(e.eye)A=e.eye;else if(e.look)o=e.look;else{let s=e;if((w.isNumeric(s)||w.isString(s))&&(l=s,s=this.scene.components[l],!s))return this.error("Component not found: "+w.inQuotes(l)),void(t&&(i?t.call(i):t()));r||(n=s.aabb||this.scene.aabb)}const c=e.poi;if(n){if(n[3]<n[0]||n[4]<n[1]||n[5]<n[2])return;if(n[3]===n[0]&&n[4]===n[1]&&n[5]===n[2])return;n=n.slice();const t=d.getAABB3Center(n);this._look2=c||t;const i=d.subVec3(this._eye1,this._look1,$),s=d.normalizeVec3(i),r=c?d.getAABB3DiagPoint(n,c):d.getAABB3Diag(n),A=e.fitFOV||this._fitFOV,o=Math.abs(r/Math.tan(A*d.DEGTORAD));this._orthoScale2=1.1*r,this._eye2[0]=this._look2[0]+s[0]*o,this._eye2[1]=this._look2[1]+s[1]*o,this._eye2[2]=this._look2[2]+s[2]*o,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(A||o||a)&&(this._flyingEyeLookUp=!!A&&!!o&&!!a,this._flyingEye=!!A&&!o,this._flyingLook=!!o&&!A,A&&(this._eye2[0]=A[0],this._eye2[1]=A[1],this._eye2[2]=A[2]),o&&(this._look2[0]=o[0],this._look2[1]=o[1],this._look2[2]=o[2]),a&&(this._up2[0]=a[0],this._up2[1]=a[1],this._up2[2]=a[2]));r?("ortho"===e.projection&&"ortho"!==s.projection&&(this._projection2="ortho",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.ortho.matrix.slice(),s.projection="customProjection"),"perspective"===e.projection&&"perspective"!==s.projection&&(this._projection2="perspective",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.perspective.matrix.slice(),s.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(Number.isFinite(e.duration)?1e3*e.duration:this._duration),this._flying=!0,I.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var i,s,r,n,A;if(e.aabb)i=e.aabb;else if(6===e.length)i=e;else if(e.eye||e.look||e.up)r=e.eye,n=e.look,A=e.up;else{let t=e;if((w.isNumeric(t)||w.isString(t))&&(s=t,t=this.scene.components[s],!t))return void this.error("Component not found: "+w.inQuotes(s));i=t.aabb||this.scene.aabb}const o=e.poi;if(i){if(i[3]<=i[0]||i[4]<=i[1]||i[5]<=i[2])return;var a=o?d.getAABB3DiagPoint(i,o):d.getAABB3Diag(i);let s;n=o||d.getAABB3Center(i,n),this._trail?d.subVec3(t.look,n,ie):d.subVec3(t.eye,t.look,ie),d.normalizeVec3(ie);s=(void 0!==e.fit?e.fit:this._fit)?Math.abs(a/Math.tan((e.fitFOV||this._fitFOV)*d.DEGTORAD)):d.lenVec3(d.subVec3(t.eye,t.look,$)),d.mulVec3Scalar(ie,s),t.eye=d.addVec3(n,ie,$),t.look=n,this.scene.camera.ortho.scale=1.1*a}else(r||n||A)&&(r&&(t.eye=r),n&&(t.look=n),A&&(t.up=A));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const i=this.easing?se._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(d.subVec3(s.eye,s.look,ie),s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,ee),s.look=d.subVec3(ee,ie,q)):this._flyingLook&&(s.look=d.lerpVec3(i,0,1,this._look1,this._look2,q),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,te)):this._flyingEyeLookUp&&(s.eye=d.lerpVec3(i,0,1,this._eye1,this._eye2,ee),s.look=d.lerpVec3(i,0,1,this._look1,this._look2,q),s.up=d.lerpVec3(i,0,1,this._up1,this._up2,te)),this._projection2){const t="ortho"===this._projection2?se._easeOutExpo(e,0,1,1):se._easeInCubic(e,0,1,1);s.customProjection.matrix=d.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);if(t)return s.ortho.scale=this._orthoScale2,void this.stop();I.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=Number.isFinite(e)?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}class re extends D{get type(){return"CameraPathAnimation"}constructor(e,t={}){super(e,t),this._cameraFlightAnimation=new se(this),this._t=0,this.state=re.SCRUBBING,this._playingFromT=0,this._playingToT=0,this._playingRate=t.playingRate||1,this._playingDir=1,this._lastTime=null,this.cameraPath=t.cameraPath,this._tick=this.scene.on("tick",this._updateT,this)}_updateT(){const e=this._cameraPath;if(!e)return;let t,i;const s=performance.now(),r=this._lastTime?.001*(s-this._lastTime):0;if(this._lastTime=s,0!==r)switch(this.state){case re.SCRUBBING:return;case re.PLAYING:if(this._t+=this._playingRate*r,t=this._cameraPath.frames.length,0===t||this._playingDir<0&&this._t<=0||this._playingDir>0&&this._t>=this._cameraPath.frames[t-1].t)return this.state=re.SCRUBBING,this._t=this._cameraPath.frames[t-1].t,void this.fire("stopped");e.loadFrame(this._t);break;case re.PLAYING_TO:i=this._t+this._playingRate*r*this._playingDir,(this._playingDir<0&&i<=this._playingToT||this._playingDir>0&&i>=this._playingToT)&&(i=this._playingToT,this.state=re.SCRUBBING,this.fire("stopped")),this._t=i,e.loadFrame(this._t)}}_ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}set cameraPath(e){this._cameraPath=e}get cameraPath(){return this._cameraPath}set rate(e){this._playingRate=e}get rate(){return this._playingRate}play(){this._cameraPath&&(this._lastTime=null,this.state=re.PLAYING)}playToT(e){this._cameraPath&&(this._playingFromT=this._t,this._playingToT=e,this._playingDir=this._playingToT-this._playingFromT<0?-1:1,this._lastTime=null,this.state=re.PLAYING_TO)}playToFrame(e){const t=this._cameraPath;if(!t)return;const i=t.frames[e];i?this.playToT(i.t):this.error("playToFrame - frame index out of range: "+e)}flyToFrame(e,t){const i=this._cameraPath;if(!i)return;const s=i.frames[e];s?(this.state=re.SCRUBBING,this._cameraFlightAnimation.flyTo(s,t)):this.error("flyToFrame - frame index out of range: "+e)}scrubToT(e){const t=this._cameraPath;if(!t)return;this.scene.camera&&(this._t=e,t.loadFrame(this._t),this.state=re.SCRUBBING)}scrubToFrame(e){const t=this._cameraPath;if(!t)return;if(!this.scene.camera)return;t.frames[e]?(t.loadFrame(this._t),this.state=re.SCRUBBING):this.error("playToFrame - frame index out of range: "+e)}stop(){this.state=re.SCRUBBING,this.fire("stopped")}destroy(){super.destroy(),this.scene.off(this._tick)}}re.STOPPED=0,re.SCRUBBING=1,re.PLAYING=2,re.PLAYING_TO=3;class ne extends D{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),m.memory.meshes++}destroy(){super.destroy(),m.memory.meshes--}}const Ae=new e({});class oe{constructor(e){this.id=Ae.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){Ae.removeItem(this.id)}}class ae{constructor(e,t,i,s,r,n,A,o,a){switch(this._gl=e,this.type=t,this.allocated=!1,i.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=n,this.length=0,this.dataLength=s,this.numItems=0,this.itemSize=r,this.normalized=!!A,this.stride=o||0,this.offset=a||0,this._allocate(i)}_allocate(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}bindAtLocation(e){this.bind(),this._gl.vertexAttribPointer(e,this.itemSize,this.itemType,this.normalized,0,0)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}var le=function(){const e=[],t=[],i=[],s=[],r=[];let n=0;const A=new Uint16Array(3),o=new Uint16Array(3),a=new Uint16Array(3),l=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),f=d.vec3(),p=d.vec3(),g=d.vec3();return function(m,_,b,y){!function(r,n){const A={};let o,a,l,c;const h=Math.pow(10,4);let u,d,f=0;for(u=0,d=r.length;u<d;u+=3)o=r[u],a=r[u+1],l=r[u+2],c=Math.round(o*h)+"_"+Math.round(a*h)+"_"+Math.round(l*h),void 0===A[c]&&(A[c]=f/3,e[f++]=o,e[f++]=a,e[f++]=l),t[u/3]=A[c];for(u=0,d=n.length;u<d;u++)s[u]=t[n[u]],i[s[u]]=n[u]}(m,_),function(t,i){n=0;for(let m=0,_=t;m<_;m+=3){const t=3*s[m],_=3*s[m+1],b=3*s[m+2];i?(A[0]=e[t],A[1]=e[t+1],A[2]=e[t+2],o[0]=e[_],o[1]=e[_+1],o[2]=e[_+2],a[0]=e[b],a[1]=e[b+1],a[2]=e[b+2],d.decompressPosition(A,i,l),d.decompressPosition(o,i,c),d.decompressPosition(a,i,h)):(l[0]=e[t],l[1]=e[t+1],l[2]=e[t+2],c[0]=e[_],c[1]=e[_+1],c[2]=e[_+2],h[0]=e[b],h[1]=e[b+1],h[2]=e[b+2]),d.subVec3(h,c,u),d.subVec3(l,c,f),d.cross3Vec3(u,f,p),d.normalizeVec3(p,g);const y=r[n]||(r[n]={normal:d.vec3()});y.normal[0]=g[0],y.normal[1]=g[1],y.normal[2]=g[2],n++}}(_.length,b);const w=[],v=Math.cos(d.DEGTORAD*y),B={};let C,M,E,F,U,x,I,T,P,S,D,k=!1;for(let e=0,t=_.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)C=s[e+i],M=s[e+(i+1)%3],E=Math.min(C,M),F=Math.max(C,M),U=E+","+F,void 0===B[U]?B[U]={index1:E,index2:F,face1:t,face2:void 0}:B[U].face2=t}for(U in B)x=B[U],void 0!==x.face2&&(I=r[x.face1].normal,T=r[x.face2].normal,P=d.dotVec3(I,T),P>v)||(S=i[x.index1],D=i[x.index2],(!k&&S>65535||D>65535)&&(k=!0),w.push(S),w.push(D));return k?new Uint32Array(w):new Uint16Array(w)}}();const ce=function(){const e=d.mat4(),t=d.mat4();return function(i,s){s=s||d.mat4();const r=i[0],n=i[1],A=i[2],o=i[3]-r,a=i[4]-n,l=i[5]-A,c=65535;return d.identityMat4(e),d.translationMat4v(i,e),d.identityMat4(t),d.scalingMat4v([o/c,a/c,l/c],t),d.mulMat4(e,t,s),s}}();var he=function(){const e=d.mat4(),t=d.mat4();return function(i,s,r){const n=new Uint16Array(i.length),A=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let o;for(o=0;o<i.length;o+=3)n[o+0]=Math.max(0,Math.min(65535,Math.floor((i[o+0]-s[0])*A[0]))),n[o+1]=Math.max(0,Math.min(65535,Math.floor((i[o+1]-s[1])*A[1]))),n[o+2]=Math.max(0,Math.min(65535,Math.floor((i[o+2]-s[2])*A[2])));d.identityMat4(e),d.translationMat4v(s,e),d.identityMat4(t),d.scalingMat4v([(r[0]-s[0])/65535,(r[1]-s[1])/65535,(r[2]-s[2])/65535],t);return{quantized:n,decodeMatrix:d.mulMat4(e,t,d.identityMat4())}}}();var ue=function(){const e=d.mat3(),t=d.mat3();return function(i,s,r){const n=new Uint16Array(i.length),A=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);let o;for(o=0;o<i.length;o+=2)n[o+0]=Math.max(0,Math.min(65535,Math.floor((i[o+0]-s[0])*A[0]))),n[o+1]=Math.max(0,Math.min(65535,Math.floor((i[o+1]-s[1])*A[1])));d.identityMat3(e),d.translationMat3v(s,e),d.identityMat3(t),d.scalingMat3v([(r[0]-s[0])/65535,(r[1]-s[1])/65535],t);return{quantized:n,decodeMatrix:d.mulMat3(e,t,d.identityMat3())}}}();function de(e,t,i,s){let r=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),n=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){let e=(1-Math.abs(n))*(r>=0?1:-1),t=(1-Math.abs(r))*(n>=0?1:-1);r=e,n=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*n+(n<0?-1:0))])}function fe(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function pe(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const ge={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=3)for(r=0;r<3;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},createPositionsDecodeMatrix:ce,compressPositions:he,compressPosition:function(e,t,i){const s=new Float32Array([t[3]!==t[0]?65535/(t[3]-t[0]):0,t[4]!==t[1]?65535/(t[4]-t[1]):0,t[5]!==t[2]?65535/(t[5]-t[2]):0]);i[0]=Math.max(0,Math.min(65535,Math.floor((e[0]-t[0])*s[0]))),i[1]=Math.max(0,Math.min(65535,Math.floor((e[1]-t[1])*s[1]))),i[2]=Math.max(0,Math.min(65535,Math.floor((e[2]-t[2])*s[2])))},decompressPositions:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressPosition:function(e,t,i){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i},decompressAABB:function(e,t,i=e){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){const t=new Float32Array(2),i=new Float32Array(2);let s,r;for(s=0;s<2;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=2)for(r=0;r<2;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},compressUVs:ue,decompressUVs:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let i,s,r,n,A;for(let o=0;o<e.length;o+=3)r=i=de(e,o,"floor","floor"),s=fe(i),n=A=pe(e,o,s),i=de(e,o,"ceil","floor"),s=fe(i),n=pe(e,o,s),n>A&&(r=i,A=n),i=de(e,o,"floor","ceil"),s=fe(i),n=pe(e,o,s),n>A&&(r=i,A=n),i=de(e,o,"ceil","ceil"),s=fe(i),n=pe(e,o,s),n>A&&(r=i,A=n),t[o]=r[0],t[o+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],n=e[i+1];r=(2*r+1)/255,n=(2*n+1)/255;const A=1-Math.abs(r)-Math.abs(n);A<0&&(r=(1-Math.abs(n))*(r>=0?1:-1),n=(1-Math.abs(r))*(n>=0?1:-1));const o=Math.sqrt(r*r+n*n+A*A);t[s+0]=r/o,t[s+1]=n/o,t[s+2]=A/o,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const n=Math.sqrt(i*i+s*s+r*r);return t[0]=i/n,t[1]=s/n,t[2]=r/n,t}},me=m.memory,_e=d.AABB3();class be extends ne{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new oe({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=ge.getPositionsBounds(t.positions),s=ge.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=ge.getUVBounds(t.uv),s=ge.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);if(t.normals&&(this._state.compressGeometry?i.normals=ge.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices&&(i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)),this._buildHash(),me.meshes++,i.indices&&(i.indicesBuf=new ae(s,s.ELEMENT_ARRAY_BUFFER,i.indices,i.indices.length,1,s.STATIC_DRAW),me.indices+=i.indicesBuf.numItems),i.positions&&(i.positionsBuf=new ae(s,s.ARRAY_BUFFER,i.positions,i.positions.length,3,s.STATIC_DRAW),me.positions+=i.positionsBuf.numItems),i.normals){let e=i.compressGeometry;i.normalsBuf=new ae(s,s.ARRAY_BUFFER,i.normals,i.normals.length,3,s.STATIC_DRAW,e),me.normals+=i.normalsBuf.numItems}i.colors&&(i.colorsBuf=new ae(s,s.ARRAY_BUFFER,i.colors,i.colors.length,4,s.STATIC_DRAW),me.colors+=i.colorsBuf.numItems),i.uv&&(i.uvBuf=new ae(s,s.ARRAY_BUFFER,i.uv,i.uv.length,2,s.STATIC_DRAW),me.uvs+=i.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=le(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ae(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),me.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=d.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new ae(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ae(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),me.positions+=this._pickTrianglePositionsBuf.numItems,me.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),ge.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=ge.getPositionsBounds(e),s=ge.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),ge.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),ge.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=d.AABB3()),d.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=d.OBB3()),d.positions3ToAABB3(this._state.positions,_e,this._state.positionsDecodeMatrix),d.AABB3ToOBB3(_e,this._obb),this._obbDirty=!1),this._obb}_getMetrics(){if(!("_metrics"in this))switch(this._state.primitiveName){case"solid":case"surface":case"triangles":{const e=this._state.indices,t=this._state.positions,i=(i,s)=>{const r=3*e[i];for(let e=0;e<3;++e)s[e]=t[r+e];return s},s=[d.vec3(),d.vec3(),d.vec3(),d.vec3()];let r=0;const n=d.vec3([0,0,0]);for(let t=0;t<e.length;t+=3){const e=i(t,s[0]),A=i(t+1,s[1]),o=i(t+2,s[2]);d.addVec3(e,A,s[3]),d.addVec3(o,s[3],s[3]);const a=d.lenVec3(d.cross3Vec3(d.subVec3(A,e,s[1]),d.subVec3(o,e,s[2]),s[0]))/2;r+=a,d.mulVec3Scalar(s[3],a,s[3]),d.addVec3(n,s[3],n)}this._metrics={surfaceArea:r,centroid:d.mulVec3Scalar(n,1/r/3,n)};break}default:this._metrics={surfaceArea:0}}return this._metrics}get surfaceArea(){return this._getMetrics().surfaceArea}get centroid(){return this._getMetrics().centroid}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),me.meshes--}}const ye=m.memory,we=d.AABB3();class ve extends ne{get type(){return"VBOGeometry"}get isVBOGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new oe({compressGeometry:!0,primitive:null,primitiveName:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._aabb=null,this._obb=d.OBB3();const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(t.indices){var r;if(t.positionsDecodeMatrix);else{const e=ge.getPositionsBounds(t.positions),n=ge.compressPositions(t.positions,e.min,e.max);r=n.quantized,i.positionsDecodeMatrix=n.decodeMatrix,i.positionsBuf=new ae(s,s.ARRAY_BUFFER,r,r.length,3,s.STATIC_DRAW),ye.positions+=i.positionsBuf.numItems,d.positions3ToAABB3(t.positions,this._aabb),d.positions3ToAABB3(r,we,i.positionsDecodeMatrix),d.AABB3ToOBB3(we,this._obb)}if(t.colors){const e=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors);i.colorsBuf=new ae(s,s.ARRAY_BUFFER,e,e.length,4,s.STATIC_DRAW),ye.colors+=i.colorsBuf.numItems}if(t.uv){const e=ge.getUVBounds(t.uv),r=ge.compressUVs(t.uv,e.min,e.max),n=r.quantized;i.uvDecodeMatrix=r.decodeMatrix,i.uvBuf=new ae(s,s.ARRAY_BUFFER,n,n.length,2,s.STATIC_DRAW),ye.uvs+=i.uvBuf.numItems}if(t.normals){const e=ge.compressNormals(t.normals);let r=i.compressGeometry;i.normalsBuf=new ae(s,s.ARRAY_BUFFER,e,e.length,3,s.STATIC_DRAW,r),ye.normals+=i.normalsBuf.numItems}{const e=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Uint32Array(t.indices);i.indicesBuf=new ae(s,s.ELEMENT_ARRAY_BUFFER,e,e.length,1,s.STATIC_DRAW),ye.indices+=i.indicesBuf.numItems;const n=le(r,e,i.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ae(s,s.ELEMENT_ARRAY_BUFFER,n,n.length,1,s.STATIC_DRAW),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),ye.meshes++}else this.error("Config expected: indices");else this.error("Config expected: positions")}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positionsBuf&&t.push("p"),e.colorsBuf&&t.push("c"),(e.normalsBuf||e.autoVertexNormals)&&t.push("n"),e.uvBuf&&t.push("u"),t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf}get primitive(){return this._state.primitiveName}get aabb(){return this._aabb}get obb(){return this._obb}get numTriangles(){return this._numTriangles}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),e.destroy(),ye.meshes--}}var Be={};function Ce(e,t={}){return new Promise((function(i,s){t.src||(console.error("load3DSGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,w.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("load3DSGeometry: no data loaded"),r.processes--,s());var n=Be.parse.from3DS(e).edit.objects[0].mesh,A=n.vertices,o=n.uvt,a=n.indices;r.processes--,i(w.apply(t,{primitive:"triangles",positions:A,normals:null,uv:o,indices:a}))}),(function(e){console.error("load3DSGeometry: "+e),r.processes--,s()}))}))}function Me(e,t={}){return new Promise((function(i,s){t.src||(console.error("loadOBJGeometry: Parameter expected: src"),s());var r=e.canvas.spinner;r.processes++,w.loadArraybuffer(t.src,(function(e){e.byteLength||(console.error("loadOBJGeometry: no data loaded"),r.processes--,s());for(var n=Be.parse.fromOBJ(e),A=Be.edit.unwrap(n.i_verts,n.c_verts,3),o=Be.edit.unwrap(n.i_norms,n.c_norms,3),a=Be.edit.unwrap(n.i_uvt,n.c_uvt,2),l=new Int32Array(n.i_verts.length),c=0;c<n.i_verts.length;c++)l[c]=c;r.processes--,i(w.apply(t,{primitive:"triangles",positions:A,normals:o.length>0?o:null,autoNormals:0===o.length,uv:a,indices:l}))}),(function(e){console.error("loadOBJGeometry: "+e),r.processes--,s()}))}))}function Ee(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,n=r?r[0]:0,A=r?r[1]:0,o=r?r[2]:0,a=-t+n,l=-i+A,c=-s+o,h=t+n,u=i+A,d=s+o;return w.apply(e,{positions:[h,u,d,a,u,d,a,l,d,h,l,d,h,u,d,h,l,d,h,l,c,h,u,c,h,u,d,h,u,c,a,u,c,a,u,d,a,u,d,a,u,c,a,l,c,a,l,d,a,l,c,h,l,c,h,l,d,a,l,d,h,l,c,a,l,c,a,u,c,h,u,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}function Fe(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,n=r?r[0]:0,A=r?r[1]:0,o=r?r[2]:0,a=-t+n,l=-i+A,c=-s+o,h=t+n,u=i+A,d=s+o;return w.apply(e,{primitive:"lines",positions:[a,l,c,a,l,d,a,u,c,a,u,d,h,l,c,h,l,d,h,u,c,h,u,d],indices:[0,1,1,3,3,2,2,0,4,5,5,7,7,6,6,4,0,4,1,5,2,6,3,7]})}function Ue(e={}){return Fe({id:e.id,center:[(e.aabb[0]+e.aabb[3])/2,(e.aabb[1]+e.aabb[4])/2,(e.aabb[2]+e.aabb[5])/2],xSize:Math.abs(e.aabb[3]-e.aabb[0])/2,ySize:Math.abs(e.aabb[4]-e.aabb[1])/2,zSize:Math.abs(e.aabb[5]-e.aabb[2])/2})}function xe(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let n=e.heightSegments||1;n<0&&(console.error("negative heightSegments not allowed - will invert"),n*=-1),n<1&&(n=1);const A=!!e.openEnded;let o=e.center;const a=o?o[0]:0,l=o?o[1]:0,c=o?o[2]:0,h=s/2,u=s/n,d=2*Math.PI/r,f=1/r,p=(t-i)/n,g=[],m=[],_=[],b=[];let y,v,B,C,M,E,F,U,x,I,T;const P=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=n;y++)for(M=t-y*p,E=h-y*u,v=0;v<=r;v++)B=Math.sin(v*d),C=Math.cos(v*d),m.push(M*B),m.push(P),m.push(M*C),_.push(v*f),_.push(1*y/n),g.push(M*B+a),g.push(E+l),g.push(M*C+c);for(y=0;y<n;y++)for(v=0;v<=r;v++)F=y*(r+1)+v,U=F+r,b.push(F),b.push(U),b.push(U+1),b.push(F),b.push(U+1),b.push(F+1);if(!A&&t>0){for(x=g.length/3,m.push(0),m.push(1),m.push(0),_.push(.5),_.push(.5),g.push(0+a),g.push(h+l),g.push(0+c),v=0;v<=r;v++)B=Math.sin(v*d),C=Math.cos(v*d),I=.5*Math.sin(v*d)+.5,T=.5*Math.cos(v*d)+.5,m.push(t*B),m.push(1),m.push(t*C),_.push(I),_.push(T),g.push(t*B+a),g.push(h+l),g.push(t*C+c);for(v=0;v<r;v++)o=x,F=x+1+v,b.push(F),b.push(F+1),b.push(o)}if(!A&&i>0){for(x=g.length/3,m.push(0),m.push(-1),m.push(0),_.push(.5),_.push(.5),g.push(0+a),g.push(0-h+l),g.push(0+c),v=0;v<=r;v++)B=Math.sin(v*d),C=Math.cos(v*d),I=.5*Math.sin(v*d)+.5,T=.5*Math.cos(v*d)+.5,m.push(i*B),m.push(-1),m.push(i*C),_.push(I),_.push(T),g.push(i*B+a),g.push(0-h+l),g.push(i*C+c);for(v=0;v<r;v++)o=x,F=x+1+v,b.push(o),b.push(F+1),b.push(F)}return w.apply(e,{positions:g,normals:m,uv:_,indices:b})}function Ie(e={}){let t=e.size||1;t<0&&(console.error("negative size not allowed - will invert"),t*=-1);let i=e.divisions||1;i<0&&(console.error("negative divisions not allowed - will invert"),i*=-1),i<1&&(i=1),t=t||10,i=i||10;const s=t/i,r=t/2,n=[],A=[];let o=0;for(let e=0,t=-r;e<=i;e++,t+=s)n.push(-r),n.push(0),n.push(t),n.push(r),n.push(0),n.push(t),n.push(t),n.push(0),n.push(-r),n.push(t),n.push(0),n.push(r),A.push(o++),A.push(o++),A.push(o++),A.push(o++);return w.apply(e,{primitive:"lines",positions:n,indices:A})}function Te(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.zSize||1;i<0&&(console.error("negative zSize not allowed - will invert"),i*=-1);let s=e.xSegments||1;s<0&&(console.error("negative xSegments not allowed - will invert"),s*=-1),s<1&&(s=1);let r=e.xSegments||1;r<0&&(console.error("negative zSegments not allowed - will invert"),r*=-1),r<1&&(r=1);const n=e.center,A=n?n[0]:0,o=n?n[1]:0,a=n?n[2]:0,l=t/2,c=i/2,h=Math.floor(s)||1,u=Math.floor(r)||1,d=h+1,f=u+1,p=t/h,g=i/u,m=new Float32Array(d*f*3),_=new Float32Array(d*f*3),b=new Float32Array(d*f*2);let y,v,B,C,M,E,F,U=0,x=0;for(y=0;y<f;y++){const e=y*g-c;for(v=0;v<d;v++)B=v*p-l,m[U]=B+A,m[U+1]=o,m[U+2]=-e+a,_[U+1]=1,b[x]=v/h,b[x+1]=(u-y)/u,U+=3,x+=2}U=0;const I=new(m.length/3>65535?Uint32Array:Uint16Array)(h*u*6);for(y=0;y<u;y++)for(v=0;v<h;v++)C=v+d*y,M=v+d*(y+1),E=v+1+d*(y+1),F=v+1+d*y,I[U]=F,I[U+1]=M,I[U+2]=C,I[U+3]=F,I[U+4]=E,I[U+5]=M,U+=6;return w.apply(e,{positions:m,normals:_,uv:b,indices:I})}function Pe(e={}){const t=e.lod||1,i=e.center?e.center[0]:0,s=e.center?e.center[1]:0,r=e.center?e.center[2]:0;let n=e.radius||1;n<0&&(console.error("negative radius not allowed - will invert"),n*=-1);let A=e.heightSegments||18;A<0&&(console.error("negative heightSegments not allowed - will invert"),A*=-1),A=Math.floor(t*A),A<18&&(A=18);let o=e.widthSegments||18;o<0&&(console.error("negative widthSegments not allowed - will invert"),o*=-1),o=Math.floor(t*o),o<18&&(o=18);const a=[],l=[],c=[],h=[];let u,d,f,p,g,m,_,b,y,v,B,C,M,E,F;for(u=0;u<=A;u++)for(f=u*Math.PI/A,p=Math.sin(f),g=Math.cos(f),d=0;d<=o;d++)m=2*d*Math.PI/o,_=Math.sin(m),b=Math.cos(m),y=b*p,v=g,B=_*p,C=1-d/o,M=u/A,l.push(y),l.push(v),l.push(B),c.push(C),c.push(M),a.push(i+n*y),a.push(s+n*v),a.push(r+n*B);for(u=0;u<A;u++)for(d=0;d<o;d++)E=u*(o+1)+d,F=E+o+1,h.push(E+1),h.push(F+1),h.push(F),h.push(E+1),h.push(F),h.push(E);return w.apply(e,{positions:a,normals:l,uv:c,indices:h})}function Se(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);let s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<4&&(s=4);let r=e.tubeSegments||24;r<0&&(console.error("negative tubeSegments not allowed - will invert"),r*=-1),r<4&&(r=4);let n=e.arc||2*Math.PI;n<0&&(console.warn("negative arc not allowed - will invert"),n*=-1),n>360&&(n=360);const A=e.center;let o=A?A[0]:0,a=A?A[1]:0;const l=A?A[2]:0,c=[],h=[],u=[],f=[];let p,g,m,_,b,y,v,B,C,M,E,F;for(B=0;B<=r;B++)for(v=0;v<=s;v++)p=v/s*n,g=.785398+B/r*Math.PI*2,o=t*Math.cos(p),a=t*Math.sin(p),m=(t+i*Math.cos(g))*Math.cos(p),_=(t+i*Math.cos(g))*Math.sin(p),b=i*Math.sin(g),c.push(m+o),c.push(_+a),c.push(b+l),u.push(1-v/s),u.push(B/r),y=d.normalizeVec3(d.subVec3([m,_,b],[o,a,l],[]),[]),h.push(y[0]),h.push(y[1]),h.push(y[2]);for(B=1;B<=r;B++)for(v=1;v<=s;v++)C=(s+1)*B+v-1,M=(s+1)*(B-1)+v-1,E=(s+1)*(B-1)+v,F=(s+1)*B+v,f.push(C),f.push(M),f.push(E),f.push(E),f.push(F),f.push(C);return w.apply(e,{positions:c,normals:h,uv:u,indices:f})}Be.load=function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},Be.save=function(e,t){var i="data:application/octet-stream;base64,"+btoa(Be.parse._buffToStr(e));window.location.href=i},Be.clone=function(e){return JSON.parse(JSON.stringify(e))},Be.bin={},Be.bin.f=new Float32Array(1),Be.bin.fb=new Uint8Array(Be.bin.f.buffer),Be.bin.rf=function(e,t){for(var i=Be.bin.f,s=Be.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},Be.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Be.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Be.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},Be.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},Be.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},Be.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Be.parse={},Be.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;s<t.length;s++)i=i.concat(String.fromCharCode(t[s]));return i},Be.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),i=new Uint8Array(t),s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return t},Be.parse._readLine=function(e,t){for(var i="";10!=e[t];)i+=String.fromCharCode(e[t++]);return i},Be.parse.fromJSON=function(e){return JSON.parse(Be.parse._buffToStr(e))},Be.parse.toJSON=function(e){var t=JSON.stringify(e);return Be.parse._strToBuff(t)},Be.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},i={from:0,to:0},s=0,r=new Uint8Array(e);s<r.length;){var n=Be.parse._readLine(r,s);s+=n.length+1;var A=(n=(n=n.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==A[0]&&(i.to=t.i_verts.length,null==t.groups[A[1]]&&(t.groups[A[1]]={from:t.i_verts.length,to:0}),i=t.groups[A[1]]),"v"==A[0]){var o=parseFloat(A[1]),a=parseFloat(A[2]),l=parseFloat(A[3]);t.c_verts.push(o,a,l)}if("vt"==A[0]){o=parseFloat(A[1]),a=1-parseFloat(A[2]);t.c_uvt.push(o,a)}if("vn"==A[0]){o=parseFloat(A[1]),a=parseFloat(A[2]),l=parseFloat(A[3]);t.c_norms.push(o,a,l)}if("f"==A[0]){var c=A[1].split("/"),h=A[2].split("/"),u=A[3].split("/"),d=parseInt(c[0])-1,f=parseInt(h[0])-1,p=parseInt(u[0])-1,g=parseInt(c[1])-1,m=parseInt(h[1])-1,_=parseInt(u[1])-1,b=parseInt(c[2])-1,y=parseInt(h[2])-1,w=parseInt(u[2])-1,v=t.c_verts.length/3,B=t.c_uvt.length/2,C=t.c_norms.length/3;if(d<0&&(d=v+d+1),f<0&&(f=v+f+1),p<0&&(p=v+p+1),g<0&&(g=B+g+1),m<0&&(m=B+m+1),_<0&&(_=B+_+1),b<0&&(b=C+b+1),y<0&&(y=C+y+1),w<0&&(w=C+w+1),t.i_verts.push(d,f,p),t.i_uvt.push(g,m,_),t.i_norms.push(b,y,w),5==A.length){var M=A[4].split("/"),E=parseInt(M[0])-1,F=parseInt(M[1])-1,U=parseInt(M[2])-1;E<0&&(E=v+E+1),F<0&&(F=B+F+1),U<0&&(U=C+U+1),t.i_verts.push(d,p,E),t.i_uvt.push(g,_,F),t.i_norms.push(b,w,U)}}}return i.to=t.i_verts.length,t},Be.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},i={};i.ident=Be.bin.ril(e,0),i.version=Be.bin.ril(e,4),i.skinwidth=Be.bin.ril(e,8),i.skinheight=Be.bin.ril(e,12),i.framesize=Be.bin.ril(e,16),i.num_skins=Be.bin.ril(e,20),i.num_vertices=Be.bin.ril(e,24),i.num_st=Be.bin.ril(e,28),i.num_tris=Be.bin.ril(e,32),i.num_glcmds=Be.bin.ril(e,36),i.num_frames=Be.bin.ril(e,40),i.offset_skins=Be.bin.ril(e,44),i.offset_st=Be.bin.ril(e,48),i.offset_tris=Be.bin.ril(e,52),i.offset_frames=Be.bin.ril(e,56),i.offset_glcmds=Be.bin.ril(e,60),i.offset_end=Be.bin.ril(e,64);var s=i.offset_st;t.c_uvt=[];for(var r=0;r<i.num_st;r++){var n=Be.bin.rsl(e,s)/i.skinwidth,A=Be.bin.rsl(e,s+2)/i.skinheight;t.c_uvt.push(n,A),s+=4}s=i.offset_tris;var o=[],a=[];t.i_verts=o,t.i_uvt=a;for(r=0;r<i.num_tris;r++)o.push(Be.bin.rsl(e,s),Be.bin.rsl(e,s+2),Be.bin.rsl(e,s+4)),a.push(Be.bin.rsl(e,s+6),Be.bin.rsl(e,s+8),Be.bin.rsl(e,s+10)),s+=12;s=i.offset_skins;t.skins=[];for(r=0;r<i.num_skins;r++)t.skins.push(Be.bin.rASCII0(e,s)),s+=64;s=i.offset_frames;t.frames=[];var l=Be.parse.fromMD2._normals;for(r=0;r<i.num_frames;r++){var c={},h=Be.bin.rf(e,s),u=Be.bin.rf(e,s+4),d=Be.bin.rf(e,s+8);s+=12;var f=Be.bin.rf(e,s),p=Be.bin.rf(e,s+4),g=Be.bin.rf(e,s+8);s+=12,c.name=Be.bin.rASCII0(e,s),s+=16,c.verts=[],c.norms=[];for(var m=0;m<i.num_vertices;m++)c.verts.push(e[s]*h+f,e[s+1]*u+p,e[s+2]*d+g),c.norms.push(l[3*e[s+3]],l[3*e[s+3]+1],l[3*e[s+3]+2]),s+=4;t.frames.push(c)}return t},Be.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],Be.parse.fromCollada=function(e){var t=Be.parse._buffToStr(e),i=(new DOMParser).parseFromString(t,"text/xml"),s={},r=(i=i.childNodes[0]).getElementsByTagName("asset")[0],n=i.getElementsByTagName("library_geometries")[0],A=i.getElementsByTagName("library_images")[0],o=i.getElementsByTagName("library_materials")[0],a=i.getElementsByTagName("library_effects")[0];return r&&(s.asset=Be.parse.fromCollada._asset(r)),n&&(s.geometries=Be.parse.fromCollada._libGeometries(n)),A&&(s.images=Be.parse.fromCollada._libImages(A)),o&&(s.materials=Be.parse.fromCollada._libMaterials(o)),a&&(s.effects=Be.parse.fromCollada._libEffects(a)),s},Be.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},Be.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],i=0;i<e.length;i++){var s=e[i],r=Be.parse.fromCollada._getMesh(s.getElementsByTagName("mesh")[0]);t.push(r)}return t},Be.parse.fromCollada._getMesh=function(e){for(var t={},i=e.getElementsByTagName("source"),s=t.sources={},r=0;r<i.length;r++){for(var n=i[r].getElementsByTagName("float_array")[0].textContent.split(" "),A=n.length-(""==n[n.length-1]?1:0),o=new Array(A),a=0;a<A;a++)o[a]=parseFloat(n[a]);s[i[r].getAttribute("id")]=o}t.triangles=[];var l=e.getElementsByTagName("triangles");if(null==l)return t;for(r=0;r<l.length;r++){var c={},h=l[r];c.material=h.getAttribute("material");var u=h.getElementsByTagName("input"),d=[];for(a=0;a<u.length;a++){var f=u[a];o=[];d[parseInt(f.getAttribute("offset"))]=o;var p=f.getAttribute("semantic");c["s_"+p]="VERTEX"==p?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):f.getAttribute("source").substring(1),c["i_"+p]=o,s[c["s_"+p]]}var g=h.getElementsByTagName("p")[0].textContent.split(" "),m=3*Math.floor(g.length/3);for(a=0;a<m;a++)d[a%u.length].push(parseInt(g[a]));t.triangles.push(c)}return t},Be.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("id")]=e[i].getElementsByTagName("init_from")[0].textContent;return t},Be.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("name")]=e[i].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},Be.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},i=0;i<e.length;i++){for(var s={},r=e[i].getElementsByTagName("newparam"),n=0;n<r.length;n++){var A=r[n].getElementsByTagName("surface")[0];A&&(s.surface=A.getElementsByTagName("init_from")[0].textContent)}t[e[i].getAttribute("id")]=s}return t},Be.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=Be.bin.rsl(e,0))return null;for(var i=Be.bin.ril(e,2),s=6;s<i;){var r=Be.bin.rsl(e,s),n=Be.bin.ril(e,s+2);15677==r&&(t.edit=Be.parse.from3DS._edit3ds(e,s,n)),45056==r&&(t.keyf=Be.parse.from3DS._keyf3ds(e,s,n)),s+=n}return t},Be.parse.from3DS._edit3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);16384==n&&(null==s.objects&&(s.objects=[]),s.objects.push(Be.parse.from3DS._edit_object(e,r,A))),r+=A}return s},Be.parse.from3DS._keyf3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);45058==n&&(null==s.desc&&(s.desc=[]),s.desc.push(Be.parse.from3DS._keyf_objdes(e,r,A))),r+=A}return s},Be.parse.from3DS._keyf_objdes=function(e,t,i){for(var s={},r=t+6;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);45072==n&&(s.hierarchy=Be.parse.from3DS._keyf_objhierarch(e,r,A)),45073==n&&(s.dummy_name=Be.bin.rASCII0(e,r+6)),r+=A}return s},Be.parse.from3DS._keyf_objhierarch=function(e,t,i){var s={},r=t+6;return s.name=Be.bin.rASCII0(e,r),r+=s.name.length+1,s.hierarchy=Be.bin.rsl(e,r+4),s},Be.parse.from3DS._edit_object=function(e,t,i){var s={},r=t+6;for(s.name=Be.bin.rASCII0(e,r),r+=s.name.length+1;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);16640==n&&(s.mesh=Be.parse.from3DS._obj_trimesh(e,r,A)),r+=A}return s},Be.parse.from3DS._obj_trimesh=function(e,t,i){for(var s={},r=t+6;r<t+i;){var n=Be.bin.rsl(e,r),A=Be.bin.ril(e,r+2);16656==n&&(s.vertices=Be.parse.from3DS._tri_vertexl(e,r,A)),16672==n&&(s.indices=Be.parse.from3DS._tri_facel1(e,r,A)),16704==n&&(s.uvt=Be.parse.from3DS._tri_mappingcoors(e,r,A)),16736==n&&(s.local=Be.parse.from3DS._tri_local(e,r,A)),r+=A}return s},Be.parse.from3DS._tri_vertexl=function(e,t,i){var s=[],r=t+6,n=Be.bin.rsl(e,r);r+=2;for(var A=0;A<n;A++)s.push(Be.bin.rf(e,r)),s.push(Be.bin.rf(e,r+4)),s.push(Be.bin.rf(e,r+8)),r+=12;return s},Be.parse.from3DS._tri_facel1=function(e,t,i){var s=[],r=t+6,n=Be.bin.rsl(e,r);r+=2;for(var A=0;A<n;A++)s.push(Be.bin.rsl(e,r)),s.push(Be.bin.rsl(e,r+2)),s.push(Be.bin.rsl(e,r+4)),r+=8;return s},Be.parse.from3DS._tri_mappingcoors=function(e,t,i){var s=[],r=t+6,n=Be.bin.rsl(e,r);r+=2;for(var A=0;A<n;A++)s.push(Be.bin.rf(e,r)),s.push(1-Be.bin.rf(e,r+4)),r+=8;return s},Be.parse.from3DS._tri_local=function(e,t,i){var s={},r=t+6;return s.X=[Be.bin.rf(e,r),Be.bin.rf(e,r+4),Be.bin.rf(e,r+8)],r+=12,s.Y=[Be.bin.rf(e,r),Be.bin.rf(e,r+4),Be.bin.rf(e,r+8)],r+=12,s.Z=[Be.bin.rf(e,r),Be.bin.rf(e,r+4),Be.bin.rf(e,r+8)],r+=12,s.C=[Be.bin.rf(e,r),Be.bin.rf(e,r+4),Be.bin.rf(e,r+8)],r+=12,s},Be.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},i={};return i.id=Be.bin.ril(e,0),i.verS=Be.bin.ril(e,4),i.texS=Be.bin.ril(e,8),i.indS=Be.bin.ril(e,12),i.verO=Be.bin.ril(e,16),i.verL=Be.bin.ril(e,20),i.texO=Be.bin.ril(e,24),i.texL=Be.bin.ril(e,28),i.indO=Be.bin.ril(e,32),i.indL=Be.bin.ril(e,36),0!=i.verO&&(t.vertices=Be.parse.fromBIV._readFloats(e,i.verO,i.verL)),0!=i.texO&&(t.uvt=Be.parse.fromBIV._readFloats(e,i.texO,i.texL)),0!=i.indO&&(t.indices=Be.parse.fromBIV._readInts(e,i.indO,i.indL,i.indS)),t},Be.parse.toBIV=function(e){for(var t=0,i=0;i<e.indices.length;i++)t=Math.max(t,e.indices[i]);var s=32;t<=65535&&(s=16);var r=40;e.vertices&&(r+=4*e.vertices.length),e.uvt&&(r+=4*e.uvt.length),e.indices&&(r+=e.indices.length*s/8);var n=new Uint8Array(r);Be.bin.wil(n,0,1769365870),Be.bin.wil(n,4,32),Be.bin.wil(n,8,32),Be.bin.wil(n,12,s);var A=40;return e.vertices&&(Be.bin.wil(n,16,A),Be.bin.wil(n,20,4*e.vertices.length),Be.parse.fromBIV._writeFloats(n,A,e.vertices),A+=4*e.vertices.length),e.uvt&&(Be.bin.wil(n,24,A),Be.bin.wil(n,28,4*e.uvt.length),Be.parse.fromBIV._writeFloats(n,A,e.uvt),A+=4*e.uvt.length),e.indices&&(Be.bin.wil(n,32,A),Be.bin.wil(n,36,4*e.indices.length),Be.parse.fromBIV._writeInts(n,A,e.indices,s)),n.buffer},Be.parse.fromBIV._readFloats=function(e,t,i){for(var s=[],r=0;r<i/4;r++)s.push(Be.bin.rf(e,t+4*r));return s},Be.parse.fromBIV._writeFloats=function(e,t,i){for(var s=0;s<i.length;s++)Be.bin.wf(e,t+4*s,i[s])},Be.parse.fromBIV._readInts=function(e,t,i,s){for(var r=[],n=0;n<i/4;n++)16==s&&r.push(Be.bin.rsl(e,t+2*n)),32==s&&r.push(Be.bin.ril(e,t+4*n));return r},Be.parse.fromBIV._writeInts=function(e,t,i,s){for(var r=0;r<i.length;r++)16==s&&Be.bin.wsl(e,t+2*r,i[r]),32==s&&Be.bin.wil(e,t+4*r,i[r])},Be.gen={},Be.gen.Plane=function(e,t,i,s){i||(i=1),s||(s=1);for(var r={verts:[],inds:[],uvt:[]},n=e+1,A=t+1,o=0;o<A;o++)for(var a=0;a<n;a++){var l=a*(2/e)-1,c=o*(2/t)-1;r.verts.push(l,c,0),r.uvt.push(i*a/e,s*o/t),o<t&&a<e&&r.inds.push(o*n+a,o*n+a+1,(o+1)*n+a,o*n+a+1,(o+1)*n+a,(o+1)*n+a+1)}return r},Be.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},Be.gen.Sphere=function(e,t){for(var i={verts:[],inds:[],uvt:[]},s=e+1,r=t+1,n=0;n<r;n++)for(var A=0;A<s;A++){var o=-Math.PI/2+n*Math.PI/t,a=2*A*Math.PI/e,l=Math.cos(o)*Math.cos(a),c=Math.sin(o),h=Math.cos(o)*Math.sin(a);i.verts.push(l,c,h),i.uvt.push(A/e,n/t),n<t&&A<e&&i.inds.push(s*n+A,s*n+A+1,s*(n+1)+A,s*n+A+1,s*(n+1)+A,s*(n+1)+A+1)}return i},Be.mat={},Be.mat.scale=function(e,t,i){return[e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1]},Be.mat.translate=function(e,t,i){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1]},Be.mat.rotateDeg=function(e,t,i){var s=Math.PI/180;return Be.mat.rotate(e*s,t*s,i*s)},Be.mat.rotate=function(e,t,i){var s=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],r=e,n=t,A=i,o=Math.cos(r),a=Math.cos(n),l=Math.cos(A),c=Math.sin(r),h=Math.sin(n),u=Math.sin(A);return s[0]=a*l,s[1]=-a*u,s[2]=h,s[4]=o*u+c*h*l,s[5]=o*l-c*h*u,s[6]=-c*a,s[8]=c*u-o*h*l,s[9]=c*l+o*h*u,s[10]=o*a,s},Be.edit={},Be.edit.interpolate=function(e,t,i,s){for(var r=0;r<e.length;r++)i[r]=e[r]+s*(t[r]-e[r])},Be.edit.transform=function(e,t){for(var i=0;i<e.length;i+=3){var s=e[i],r=e[i+1],n=e[i+2];e[i+0]=t[0]*s+t[4]*r+t[8]*n+t[12],e[i+1]=t[1]*s+t[5]*r+t[9]*n+t[13],e[i+2]=t[2]*s+t[6]*r+t[10]*n+t[14]}},Be.edit.unwrap=function(e,t,i){for(var s=new Array(Math.floor(e.length/3)*i),r=0;r<e.length;r++)for(var n=0;n<i;n++)s[r*i+n]=t[e[r]*i+n];return s},Be.edit.remap=function(e,t,i,s){for(var r=new Array(i.length),n=0;n<e.length;n++)for(var A=0;A<s;A++)r[t[n]*s+A]=i[e[n]*s+A];return r},Be.utils={},Be.utils.getAABB=function(e){var t,i,s,r,n,A;r=n=A=-(t=i=s=999999999);for(var o=0;o<e.length;o+=3){var a=e[o+0],l=e[o+1],c=e[o+2];a<t&&(t=a),a>r&&(r=a),l<i&&(i=l),l>n&&(n=l),c<s&&(s=c),l>A&&(A=c)}return{min:{x:t,y:i,z:s},max:{x:r,y:n,z:A}}};const De={" ":{width:16,points:[]},"!":{width:10,points:[[5,21],[5,7],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},'"':{width:16,points:[[4,21],[4,14],[-1,-1],[12,21],[12,14]]},"#":{width:21,points:[[11,25],[4,-7],[-1,-1],[17,25],[10,-7],[-1,-1],[4,12],[18,12],[-1,-1],[3,6],[17,6]]},$:{width:20,points:[[8,25],[8,-4],[-1,-1],[12,25],[12,-4],[-1,-1],[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},"%":{width:24,points:[[21,21],[3,0],[-1,-1],[8,21],[10,19],[10,17],[9,15],[7,14],[5,14],[3,16],[3,18],[4,20],[6,21],[8,21],[10,20],[13,19],[16,19],[19,20],[21,21],[-1,-1],[17,7],[15,6],[14,4],[14,2],[16,0],[18,0],[20,1],[21,3],[21,5],[19,7],[17,7]]},"&":{width:26,points:[[23,12],[23,13],[22,14],[21,14],[20,13],[19,11],[17,6],[15,3],[13,1],[11,0],[7,0],[5,1],[4,2],[3,4],[3,6],[4,8],[5,9],[12,13],[13,14],[14,16],[14,18],[13,20],[11,21],[9,20],[8,18],[8,16],[9,13],[11,10],[16,3],[18,1],[20,0],[22,0],[23,1],[23,2]]},"'":{width:10,points:[[5,19],[4,20],[5,21],[6,20],[6,18],[5,16],[4,15]]},"(":{width:14,points:[[11,25],[9,23],[7,20],[5,16],[4,11],[4,7],[5,2],[7,-2],[9,-5],[11,-7]]},")":{width:14,points:[[3,25],[5,23],[7,20],[9,16],[10,11],[10,7],[9,2],[7,-2],[5,-5],[3,-7]]},"*":{width:16,points:[[8,21],[8,9],[-1,-1],[3,18],[13,12],[-1,-1],[13,18],[3,12]]},"+":{width:26,points:[[13,18],[13,0],[-1,-1],[4,9],[22,9]]},",":{width:10,points:[[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"-":{width:26,points:[[4,9],[22,9]]},".":{width:10,points:[[5,2],[4,1],[5,0],[6,1],[5,2]]},"/":{width:22,points:[[20,25],[2,-7]]},0:{width:20,points:[[9,21],[6,20],[4,17],[3,12],[3,9],[4,4],[6,1],[9,0],[11,0],[14,1],[16,4],[17,9],[17,12],[16,17],[14,20],[11,21],[9,21]]},1:{width:20,points:[[6,17],[8,18],[11,21],[11,0]]},2:{width:20,points:[[4,16],[4,17],[5,19],[6,20],[8,21],[12,21],[14,20],[15,19],[16,17],[16,15],[15,13],[13,10],[3,0],[17,0]]},3:{width:20,points:[[5,21],[16,21],[10,13],[13,13],[15,12],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},4:{width:20,points:[[13,21],[3,7],[18,7],[-1,-1],[13,21],[13,0]]},5:{width:20,points:[[15,21],[5,21],[4,12],[5,13],[8,14],[11,14],[14,13],[16,11],[17,8],[17,6],[16,3],[14,1],[11,0],[8,0],[5,1],[4,2],[3,4]]},6:{width:20,points:[[16,18],[15,20],[12,21],[10,21],[7,20],[5,17],[4,12],[4,7],[5,3],[7,1],[10,0],[11,0],[14,1],[16,3],[17,6],[17,7],[16,10],[14,12],[11,13],[10,13],[7,12],[5,10],[4,7]]},7:{width:20,points:[[17,21],[7,0],[-1,-1],[3,21],[17,21]]},8:{width:20,points:[[8,21],[5,20],[4,18],[4,16],[5,14],[7,13],[11,12],[14,11],[16,9],[17,7],[17,4],[16,2],[15,1],[12,0],[8,0],[5,1],[4,2],[3,4],[3,7],[4,9],[6,11],[9,12],[13,13],[15,14],[16,16],[16,18],[15,20],[12,21],[8,21]]},9:{width:20,points:[[16,14],[15,11],[13,9],[10,8],[9,8],[6,9],[4,11],[3,14],[3,15],[4,18],[6,20],[9,21],[10,21],[13,20],[15,18],[16,14],[16,9],[15,4],[13,1],[10,0],[8,0],[5,1],[4,3]]},":":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[5,2],[4,1],[5,0],[6,1],[5,2]]},";":{width:10,points:[[5,14],[4,13],[5,12],[6,13],[5,14],[-1,-1],[6,1],[5,0],[4,1],[5,2],[6,1],[6,-1],[5,-3],[4,-4]]},"<":{width:24,points:[[20,18],[4,9],[20,0]]},"=":{width:26,points:[[4,12],[22,12],[-1,-1],[4,6],[22,6]]},">":{width:24,points:[[4,18],[20,9],[4,0]]},"?":{width:18,points:[[3,16],[3,17],[4,19],[5,20],[7,21],[11,21],[13,20],[14,19],[15,17],[15,15],[14,13],[13,12],[9,10],[9,7],[-1,-1],[9,2],[8,1],[9,0],[10,1],[9,2]]},"@":{width:27,points:[[18,13],[17,15],[15,16],[12,16],[10,15],[9,14],[8,11],[8,8],[9,6],[11,5],[14,5],[16,6],[17,8],[-1,-1],[12,16],[10,14],[9,11],[9,8],[10,6],[11,5],[-1,-1],[18,16],[17,8],[17,6],[19,5],[21,5],[23,7],[24,10],[24,12],[23,15],[22,17],[20,19],[18,20],[15,21],[12,21],[9,20],[7,19],[5,17],[4,15],[3,12],[3,9],[4,6],[5,4],[7,2],[9,1],[12,0],[15,0],[18,1],[20,2],[21,3],[-1,-1],[19,16],[18,8],[18,6],[19,5]]},A:{width:18,points:[[9,21],[1,0],[-1,-1],[9,21],[17,0],[-1,-1],[4,7],[14,7]]},B:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[-1,-1],[4,11],[13,11],[16,10],[17,9],[18,7],[18,4],[17,2],[16,1],[13,0],[4,0]]},C:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5]]},D:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[11,21],[14,20],[16,18],[17,16],[18,13],[18,8],[17,5],[16,3],[14,1],[11,0],[4,0]]},E:{width:19,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11],[-1,-1],[4,0],[17,0]]},F:{width:18,points:[[4,21],[4,0],[-1,-1],[4,21],[17,21],[-1,-1],[4,11],[12,11]]},G:{width:21,points:[[18,16],[17,18],[15,20],[13,21],[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[18,8],[-1,-1],[13,8],[18,8]]},H:{width:22,points:[[4,21],[4,0],[-1,-1],[18,21],[18,0],[-1,-1],[4,11],[18,11]]},I:{width:8,points:[[4,21],[4,0]]},J:{width:16,points:[[12,21],[12,5],[11,2],[10,1],[8,0],[6,0],[4,1],[3,2],[2,5],[2,7]]},K:{width:21,points:[[4,21],[4,0],[-1,-1],[18,21],[4,7],[-1,-1],[9,12],[18,0]]},L:{width:17,points:[[4,21],[4,0],[-1,-1],[4,0],[16,0]]},M:{width:24,points:[[4,21],[4,0],[-1,-1],[4,21],[12,0],[-1,-1],[20,21],[12,0],[-1,-1],[20,21],[20,0]]},N:{width:22,points:[[4,21],[4,0],[-1,-1],[4,21],[18,0],[-1,-1],[18,21],[18,0]]},O:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21]]},P:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,14],[17,12],[16,11],[13,10],[4,10]]},Q:{width:22,points:[[9,21],[7,20],[5,18],[4,16],[3,13],[3,8],[4,5],[5,3],[7,1],[9,0],[13,0],[15,1],[17,3],[18,5],[19,8],[19,13],[18,16],[17,18],[15,20],[13,21],[9,21],[-1,-1],[12,4],[18,-2]]},R:{width:21,points:[[4,21],[4,0],[-1,-1],[4,21],[13,21],[16,20],[17,19],[18,17],[18,15],[17,13],[16,12],[13,11],[4,11],[-1,-1],[11,11],[18,0]]},S:{width:20,points:[[17,18],[15,20],[12,21],[8,21],[5,20],[3,18],[3,16],[4,14],[5,13],[7,12],[13,10],[15,9],[16,8],[17,6],[17,3],[15,1],[12,0],[8,0],[5,1],[3,3]]},T:{width:16,points:[[8,21],[8,0],[-1,-1],[1,21],[15,21]]},U:{width:22,points:[[4,21],[4,6],[5,3],[7,1],[10,0],[12,0],[15,1],[17,3],[18,6],[18,21]]},V:{width:18,points:[[1,21],[9,0],[-1,-1],[17,21],[9,0]]},W:{width:24,points:[[2,21],[7,0],[-1,-1],[12,21],[7,0],[-1,-1],[12,21],[17,0],[-1,-1],[22,21],[17,0]]},X:{width:20,points:[[3,21],[17,0],[-1,-1],[17,21],[3,0]]},Y:{width:18,points:[[1,21],[9,11],[9,0],[-1,-1],[17,21],[9,11]]},Z:{width:20,points:[[17,21],[3,0],[-1,-1],[3,21],[17,21],[-1,-1],[3,0],[17,0]]},"[":{width:14,points:[[4,25],[4,-7],[-1,-1],[5,25],[5,-7],[-1,-1],[4,25],[11,25],[-1,-1],[4,-7],[11,-7]]},"\\":{width:14,points:[[0,21],[14,-3]]},"]":{width:14,points:[[9,25],[9,-7],[-1,-1],[10,25],[10,-7],[-1,-1],[3,25],[10,25],[-1,-1],[3,-7],[10,-7]]},"^":{width:16,points:[[6,15],[8,18],[10,15],[-1,-1],[3,12],[8,17],[13,12],[-1,-1],[8,17],[8,0]]},_:{width:16,points:[[0,-2],[16,-2]]},"`":{width:10,points:[[6,21],[5,20],[4,18],[4,16],[5,15],[6,16],[5,17]]},a:{width:19,points:[[15,14],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},b:{width:19,points:[[4,21],[4,0],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},c:{width:18,points:[[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},d:{width:19,points:[[15,21],[15,0],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},e:{width:18,points:[[3,8],[15,8],[15,10],[14,12],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},f:{width:12,points:[[10,21],[8,21],[6,20],[5,17],[5,0],[-1,-1],[2,14],[9,14]]},g:{width:19,points:[[15,14],[15,-2],[14,-5],[13,-6],[11,-7],[8,-7],[6,-6],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},h:{width:19,points:[[4,21],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},i:{width:8,points:[[3,21],[4,20],[5,21],[4,22],[3,21],[-1,-1],[4,14],[4,0]]},j:{width:10,points:[[5,21],[6,20],[7,21],[6,22],[5,21],[-1,-1],[6,14],[6,-3],[5,-6],[3,-7],[1,-7]]},k:{width:17,points:[[4,21],[4,0],[-1,-1],[14,14],[4,4],[-1,-1],[8,8],[15,0]]},l:{width:8,points:[[4,21],[4,0]]},m:{width:30,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0],[-1,-1],[15,10],[18,13],[20,14],[23,14],[25,13],[26,10],[26,0]]},n:{width:19,points:[[4,14],[4,0],[-1,-1],[4,10],[7,13],[9,14],[12,14],[14,13],[15,10],[15,0]]},o:{width:19,points:[[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3],[16,6],[16,8],[15,11],[13,13],[11,14],[8,14]]},p:{width:19,points:[[4,14],[4,-7],[-1,-1],[4,11],[6,13],[8,14],[11,14],[13,13],[15,11],[16,8],[16,6],[15,3],[13,1],[11,0],[8,0],[6,1],[4,3]]},q:{width:19,points:[[15,14],[15,-7],[-1,-1],[15,11],[13,13],[11,14],[8,14],[6,13],[4,11],[3,8],[3,6],[4,3],[6,1],[8,0],[11,0],[13,1],[15,3]]},r:{width:13,points:[[4,14],[4,0],[-1,-1],[4,8],[5,11],[7,13],[9,14],[12,14]]},s:{width:17,points:[[14,11],[13,13],[10,14],[7,14],[4,13],[3,11],[4,9],[6,8],[11,7],[13,6],[14,4],[14,3],[13,1],[10,0],[7,0],[4,1],[3,3]]},t:{width:12,points:[[5,21],[5,4],[6,1],[8,0],[10,0],[-1,-1],[2,14],[9,14]]},u:{width:19,points:[[4,14],[4,4],[5,1],[7,0],[10,0],[12,1],[15,4],[-1,-1],[15,14],[15,0]]},v:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0]]},w:{width:22,points:[[3,14],[7,0],[-1,-1],[11,14],[7,0],[-1,-1],[11,14],[15,0],[-1,-1],[19,14],[15,0]]},x:{width:17,points:[[3,14],[14,0],[-1,-1],[14,14],[3,0]]},y:{width:16,points:[[2,14],[8,0],[-1,-1],[14,14],[8,0],[6,-4],[4,-6],[2,-7],[1,-7]]},z:{width:17,points:[[14,14],[3,0],[-1,-1],[3,14],[14,14],[-1,-1],[3,0],[14,0]]},"{":{width:14,points:[[9,25],[7,24],[6,23],[5,21],[5,19],[6,17],[7,16],[8,14],[8,12],[6,10],[-1,-1],[7,24],[6,22],[6,20],[7,18],[8,17],[9,15],[9,13],[8,11],[4,9],[8,7],[9,5],[9,3],[8,1],[7,0],[6,-2],[6,-4],[7,-6],[-1,-1],[6,8],[8,6],[8,4],[7,2],[6,1],[5,-1],[5,-3],[6,-5],[7,-6],[9,-7]]},"|":{width:8,points:[[4,25],[4,-7]]},"}":{width:14,points:[[5,25],[7,24],[8,23],[9,21],[9,19],[8,17],[7,16],[6,14],[6,12],[8,10],[-1,-1],[7,24],[8,22],[8,20],[7,18],[6,17],[5,15],[5,13],[6,11],[10,9],[6,7],[5,5],[5,3],[6,1],[7,0],[8,-2],[8,-4],[7,-6],[-1,-1],[8,8],[6,6],[6,4],[7,2],[8,1],[9,-1],[9,-3],[8,-5],[7,-6],[5,-7]]},"~":{width:24,points:[[3,6],[3,8],[4,11],[6,12],[8,12],[10,11],[14,8],[16,7],[18,7],[20,8],[21,10],[-1,-1],[3,8],[4,10],[6,11],[8,11],[10,10],[14,7],[16,6],[18,6],[20,7],[21,10],[21,12]]}};function ke(e={}){var t=e.origin||[0,0,0],i=t[0],s=t[1],r=t[2],n=e.size||1,A=[],o=[],a=e.text;w.isNumeric(a)&&(a=""+a);for(var l,c,h,u,d,f,p,g,m,_=(a||"").split("\n"),b=0,y=0,v=.04,B=0;B<_.length;B++){l=0,h=(c=_[B]).length;for(var C=0;C<h;C++)if(u=De[c.charAt(C)]){d=1,f=-1,p=-1,g=u.points.length;for(var M=0;M<g;M++)-1!==(m=u.points[M])[0]||-1!==m[1]?(A.push(l+m[0]*n*v+i),A.push(y+m[1]*n*v+s),A.push(0+r),-1===f?f=b:(-1===p||(f=p),p=b),b++,d?d=!1:(o.push(f),o.push(p))):d=1;l+=u.width*v*n}y-=35*v*n}return w.apply(e,{primitive:"lines",positions:A,indices:o})}function Qe(e={}){if(e.points.length%3!=0)throw"Size of points array for given polyline should be divisible by 3";let t=e.points.length/3;if(t<2)throw"There should be at least 2 points to create a polyline";let i=[];for(let e=0;e<t-1;e++)i.push(e),i.push(e+1);return w.apply(e,{primitive:"lines",positions:e.points,indices:i})}function Re(e={}){let t=e.curve.getPoints(e.divisions).map((e=>[...e])).flat();return Qe({id:e.id,points:t})}function Oe(e={}){if(3!==e.startPoint.length)throw"Start point should contain 3 elements in array: x, y and z";if(3!==e.endPoint.length)throw"End point should contain 3 elements in array: x, y and z";let t=[],i=[],s=e.startPoint[0],r=e.startPoint[1],n=e.startPoint[2],A=e.endPoint[0],o=e.endPoint[1],a=e.endPoint[2],l=Math.sqrt((A-s)**2+(o-r)**2+(a-n)**2),c=[(A-s)/l,(o-r)/l,(a-n)/l];if(e.pattern){let h=e.pattern.length,u=!1,d=0,f=0,p=0,g=[s,r,n],m=e.pattern[f];for(i.push(g[0],g[1],g[2]);m<=l-d;){let s=[c[0]*m,c[1]*m,c[2]*m],r=[g[0]+s[0],g[1]+s[1],g[2]+s[2]];i.push(r[0],r[1],r[2]),u||(t.push(p),t.push(p+1)),u=!u,p+=1,g=r,f+=1,f>=h&&(f=0),d+=m,m=e.pattern[f]}e.extendToEnd&&(i.push(A,o,a),t.push(t.length-2),t.push(t.length-1))}else t.push(0),t.push(1),i.push(s,r,n,A,o,a);return w.apply(e,{primitive:"lines",positions:i,indices:t})}const Ve=d.vec4(4),Le=d.vec4(),He=d.vec4(),Ne=d.vec3([1,0,0]),Ge=d.vec3([0,1,0]),je=d.vec3([0,0,1]),We=d.vec3(3),ze=d.vec3(3),Xe=d.identityMat4();class Ke extends D{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=d.vec3(),this._quaternion=d.identityQuaternion(),this._rotation=d.vec3(),this._position=d.vec3(),this._offset=d.vec3(),this._localMatrix=d.identityMat4(),this._worldMatrix=d.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.origin=t.origin,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let i=0,s=e.length;i<s;i++)this.addChild(e[i],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set origin(e){e?(this._origin||(this._origin=d.vec3()),this._origin.set(e)):this._origin&&(this._origin=null);for(let t=0,i=this._children.length;t<i;t++)this._children[t].origin=e;this.glRedraw()}get origin(){return this._origin}set rtcCenter(e){this.origin=e}get rtcCenter(){return this.origin}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,i=this._children.length;e<i;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,i=this._children.length;t<i;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)d.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,i=e._children.length;t<i;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=d.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;d.collapseAABB3(this._aabb);for(let t=0,i=this._children.length;t<i;t++)e=this._children[t],e.collidable&&d.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(w.isNumeric(e)||w.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+w.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,i=this._children.length;t<i;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,i=this._children.length;t<i;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(w.isNumeric(e)||w.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+w.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=d.identityMat4()),this._localMatrix.set(e||Xe),d.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=d.identityMat4()),d.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return Ve[0]=e[0],Ve[1]=e[1],Ve[2]=e[2],Ve[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Ve,Le),d.mulQuaternions(this.quaternion,Le,He),this.quaternion=He,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Ve[0]=e[0],Ve[1]=e[1],Ve[2]=e[2],Ve[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Ve,Le),d.mulQuaternions(Le,this.quaternion,Le),this}rotateX(e){return this.rotate(Ne,e)}rotateY(e){return this.rotate(Ge,e)}rotateZ(e){return this.rotate(je,e)}translate(e,t){return d.vec3ApplyQuaternion(this.quaternion,e,We),d.mulVec3Scalar(We,t,ze),d.addVec3(this.position,ze,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ne,e)}translateY(e){return this.translate(Ge,e)}translateZ(e){return this.translate(je,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice(0);let t;for(let i=0,s=e.length;i<s;i++)t=e[i],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}const Ze=d.vec3(),Je=function(){const e=new Float64Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,n){return n=n||e,t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,d.transformVec4(s,t,i),d.setMat4Translation(s,i,n),n.slice()}}();function Ye(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,n=Float32Array.from([e[1]])[0],A=e[1]-n,o=Float32Array.from([e[2]])[0],a=e[2]-o;t[0]=s,t[1]=n,t[2]=o,i[0]=r,i[1]=A,i[2]=a}function $e(e,t,i,s=1e3){const r=d.getPositionsCenter(e,Ze),n=Math.round(r[0]/s)*s,A=Math.round(r[1]/s)*s,o=Math.round(r[2]/s)*s;i[0]=n,i[1]=A,i[2]=o;const a=0!==i[0]||0!==i[1]||0!==i[2];if(a)for(let i=0,s=e.length;i<s;i+=3)t[i+0]=e[i+0]-n,t[i+1]=e[i+1]-A,t[i+2]=e[i+2]-o;return a}const qe=1e3,et=1001,tt=1002,it=1003,st=1004,rt=1004,nt=1005,At=1005,ot=1006,at=1007,lt=1007,ct=1008,ht=1008,ut=1009,dt=1010,ft=1011,pt=1012,gt=1013,mt=1014,_t=1015,bt=1016,yt=1017,wt=1018,vt=1020,Bt=1021,Ct=1022,Mt=1023,Et=1024,Ft=1025,Ut=1026,xt=1027,It=1028,Tt=1029,Pt=1030,St=1031,Dt=1033,kt=33776,Qt=33777,Rt=33778,Ot=33779,Vt=35840,Lt=35841,Ht=35842,Nt=35843,Gt=36196,jt=37492,Wt=37496,zt=37808,Xt=37809,Kt=37810,Zt=37811,Jt=37812,Yt=37813,$t=37814,qt=37815,ei=37816,ti=37817,ii=37818,si=37819,ri=37820,ni=37821,Ai=36492,oi=3e3,ai=3001,li=1e4,ci=10001,hi=10002,ui=10003,di=new e({}),fi=d.vec3(),pi=d.vec4(),gi={3001:"sRGBToLinear"},mi=function(){const e=[],t=[],i=[],s=[],r=[],n=[],A=[],o=(t,i)=>{let s=!1;return e.push((e=>s&&i(t,e))),{toString:()=>(s=!0,t)}},a={createAttribute:function(t,i){let s=!1;e.push((e=>s&&e.push(`in ${t} ${i};`)));const A={toString:()=>(s=!0,i)};return r.push((e=>{const t=s&&e(i);return t&&n.push(t.attributeHash),A.setInputValue=t,null})),A},createFragmentDefinition:(e,t)=>{let i=!1;return s.push((s=>i&&t(e,s))),{toString:()=>(i=!0,e)}},createOutput:(e,t,s)=>{let r=!1;return i.push((i=>r&&i.push(`layout(location = ${s||0}) out ${e} ${t};`))),{toString:()=>(r=!0,t)}},createUniform:(t,s,r)=>{let n=!1;const o=e=>n&&e.push(`uniform ${t} ${s};`);e.push(o),i.push(o);const a={toString:()=>(n=!0,s)};return A.push((e=>{const t=n&&e(s);return r?t&&(e=>r(t,e)):(a.setInputValue=t,null)})),a},createUniformArray:(t,s,r)=>{let n=!1;const o=e=>n&&e.push(`uniform ${t} ${s}[${r}];`);e.push(o),i.push(o);const a={toString:()=>(n=!0,s)};return A.push((e=>(a.setInputValue=n&&e(s),null))),a},createUniformBlock:(t,s,r)=>{let n=!1;const o=Object.keys(s),a=e=>{n&&(e.push(`uniform ${t} {`),o.forEach((t=>e.push(` ${s[t]} ${t};`))),e.push("};"))};e.push(a),i.push(a);const l={};return o.forEach((e=>l[e]={toString:()=>(n=!0,e)})),A.push((e=>{const i=n&&e(t);return r?i&&(e=>r(i,e)):(l.setInputValue=i,null)})),l},createVarying:(s,r,n,A)=>{let o=!1;const a=A?A+" ":"";return e.push((e=>o&&e.push(`${a}out ${s} ${r};`))),t.push((e=>o&&e.push(`${r} = ${n()};`))),i.push((e=>o&&e.push(`${a}in ${s} ${r};`))),{toString:()=>(o=!0,r)}},createVertexDefinition:o,commonLibrary:{octDecode:o("octDecode",((e,t)=>{t.push(`vec3 ${e}(vec2 oct) {`),t.push(" vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),t.push(" if (v.z < 0.0) {"),t.push(" v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),t.push(" }"),t.push(" return normalize(v);"),t.push("}")}))}};return{programVariables:a,buildProgram:(o,l,c)=>{const h=c.getLogDepth,u=c.clipPos,f=c.usePickClipPos&&function(){const e=a.createUniform("vec2","pickClipPos"),t=a.createUniform("vec2","pickClipPosInv");return{setClipPosInputValue:i=>{e.setInputValue(i.pickClipPos),t.setInputValue(i.pickClipPosInv)},transformedClipPos:()=>`vec4((${u}.xy / ${u}.w - ${e}) * ${t} * ${u}.w, ${u}.zw)`}}(),p=f?f.transformedClipPos():u,g=[],m=a.createVarying("float","isPerspective",(()=>`(${c.projMatrix}[2][3] == -1.0) ? 1.0 : 0.0`)),_=a.createUniform("float","logDepthBufFC",((e,t)=>e(2/(Math.log(t.view.far+1)/Math.LN2)))),b=a.createVarying("float","vFragDepth",(()=>"1.0 + clipPos.w"));h?g.push(`gl_FragDepth = ${c.testPerspectiveForGl_FragDepth?`${m} == 0.0 ? gl_FragCoord.z : `:""}log2(${h(b)}) * ${_} * 0.5;`):c.cleanerEdges&&g.push("gl_FragDepth = gl_FragCoord.z + length(vec2(dFdx(gl_FragCoord.z), dFdy(gl_FragCoord.z)));");const y=a.createFragmentDefinition("linearToGamma",((e,t)=>{t.push(`vec4 ${e}(in vec4 value, in float gammaFactor) {`),t.push(" return vec4(pow(value.xyz, vec3(1.0 / gammaFactor)), value.w);"),t.push("}")})),w=c.sectionPlanesState,v=w&&function(){const e=function(e){const t=[];for(let i=0;i<e;++i)t.push(i);return t}(w.getNumAllocatedSectionPlanes()).map((e=>{const t=(t,i,s)=>a.createUniform(t,`sectionPlane${i}${e}`,((t,i)=>{const r=w.sectionPlanes,n=r.length,A=(i.mesh.layerIndex||0)*n,o=e<n&&i.mesh.renderFlags.sectionPlanesActivePerLayer[A+e];return s(t,o,r[e],i.mesh.origin)}));return{act:t("bool","Active",((e,t)=>e(t?1:0))),dir:t("vec3","Dir",((e,t,i)=>t&&e(i.dir))),pos:t("vec3","Pos",((e,t,i,s)=>t&&e(s?d.mulVec3Scalar(d.normalizeVec3(i.dir,fi),-(d.dotVec3(i.dir,s)+i.dist),fi):i.pos)))}}));return e.length>0&&(t=>e.map((e=>`(${e.act} ? clamp(dot(-${e.dir}, ${t} - ${e.pos}), 0.0, 1000.0) : 0.0)`)).join(" + "))}(),B=c.crossSections,C=v?function(){const e=a.createUniform("vec4","sliceColor",(e=>e(B.sliceColor))),t=i=>(t.needed=!0,`(sliced ? ${e} : ${i})`);return t}():e=>e,M=c.getGammaFactor,E=a.createUniform("float","gammaFactor",(e=>e(M())));c.appendFragmentOutputs(g,M&&(e=>`${y}(${e}, ${E})`),"gl_FragCoord",C);const F=function(){const e=[],t=a.createUniform("float","sliceThickness",(e=>e(B.sliceThickness)));if(v){C.needed&&e.push(" bool sliced = false;"),e.push(` if (${c.clippableTest()}) {`);const i=a.createVarying("highp vec3","vHighpWorldPosition",(()=>`${c.worldPositionAttribute}.xyz`));if(e.push(` float dist = ${v(i)};`),c.clippingCaps){const t=a.createVarying("float","vClipPositionW",(()=>"gl_Position.w"));e.push(` if (dist > (0.002 * ${t})) { discard; }`),e.push(" if (dist > 0.0) { "),e.push(` ${c.clippingCaps} = vec4(1.0, 0.0, 0.0, 1.0);`),h&&e.push(` gl_FragDepth = log2(${h(b)}) * ${_} * 0.5;`),e.push(" return;"),e.push(" }")}else e.push(` if (dist > ${C.needed?t:"0.0"}) { discard; }`);C.needed&&e.push(" sliced = dist > 0.0;"),e.push(" }")}return e}(),U=function(){const e=[];return s.forEach((t=>t(e))),e}(),x=[...function(){const e=[];return i.forEach((t=>t(e))),e}(),...U,"void main(void) {",...c.discardPoints?[" vec2 cxy = 2.0 * gl_PointCoord - 1.0;"," if (dot(cxy, cxy) > 1.0) { discard; }"]:[],...F,...g,"}"],I=[`gl_Position = ${p};`,...c.getPointSize?[`gl_PointSize = ${c.getPointSize()};`]:[],...function(){const e=[];return t.forEach((t=>t(e))),e}()],T=c.getVertexData?c.getVertexData():[],P=[...function(){const t=[];return e.forEach((e=>e(t))),t}(),"void main(void) {",...T,...I,"}"],S=e=>["#version 300 es","// "+l+" "+e+" shader","#ifdef GL_FRAGMENT_PRECISION_HIGH","precision highp float;","precision highp int;","precision highp usampler2D;","precision highp isampler2D;","precision highp sampler2D;","#else","precision mediump float;","precision mediump int;","precision mediump usampler2D;","precision mediump isampler2D;","precision mediump sampler2D;","#endif"],D=S("vertex").concat(P),k=S("fragment").concat(["vec4 sRGBToLinear(in vec4 value) {"," return vec4(mix(pow(value.rgb * 0.9478672986 + 0.0521327014, vec3(2.4)), value.rgb * 0.0773993808, vec3(lessThanEqual(value.rgb, vec3(0.04045)))), value.w);","}"]).concat(x),Q=(e,t)=>{const i=t.join("\n"),s=o.createShader(e);return o.shaderSource(s,i),o.compileShader(s),o.getShaderParameter(s,o.COMPILE_STATUS)?[s]:[null,["Failed to compile",o.getShaderInfoLog(s),i.split("\n").map(((e,t)=>t+1+": "+e+"\n")).join("")]]},[R,O]=Q(o.VERTEX_SHADER,D),[V,L]=Q(o.FRAGMENT_SHADER,k),H=e=>(console.error(e.join("\n")),[null,e]);if(O)return H(["Vertex shader error"].concat(O));if(L)return H(["Fragment shader error"].concat(L));{const e=o.createProgram();if(e){if(o.attachShader(e,R),o.attachShader(e,V),o.linkProgram(e),o.getProgramParameter(e,o.LINK_STATUS)){const t=yi(o,e);r.forEach((e=>e(t)));const i=A.map((e=>e(t))).filter((e=>e)),s=di.addItem({});return[{id:s,bind:()=>o.useProgram(e),inputSetters:{attributesHash:n.sort().join(", "),setUniforms:(e,t)=>{f&&f.setClipPosInputValue(e),i.forEach((e=>e(t)))}},destroy:()=>{di.removeItem(s),o.deleteProgram(e),o.deleteShader(R),o.deleteShader(V)}}]}return H(["",o.getProgramInfoLog(this.program),"","Vertex shader:","",...D,"","Fragment shader:","",...k])}return H(["Failed to allocate program"])}}}},_i=function(e,t){const i=e.createUniform("vec4","lightAmbient",(e=>e(t.getAmbientColorAndIntensity()))),s=t.lights,r=s.map(((t,i)=>{const r={color:e.createUniform("vec4",`lightColor${i}`,(e=>{const t=s[i];pi[0]=t.color[0],pi[1]=t.color[1],pi[2]=t.color[2],pi[3]=t.intensity,e(pi)})),position:e.createUniform("vec3",`lightPos${i}`,(e=>e(s[i].pos))),direction:e.createUniform("vec3",`lightDir${i}`,(e=>e(s[i].dir))),shadowProjMatrix:e.createUniform("mat4",`shadowProjMatrix${i}`,(e=>e(s[i].getShadowViewMatrix()))),shadowViewMatrix:e.createUniform("mat4",`shadowViewMatrix${i}`,(e=>e(s[i].getShadowViewMatrix()))),shadowMap:e.createUniform("sampler2D",`shadowMap${i}`,(e=>e(s[i].getShadowRenderBuf().colorTextures[0])))},n=e=>({glslLight:{isWorldSpace:"world"===t.space,getColor:()=>`${r.color}.rgb * ${r.color}.a`,getDirection:(t,i)=>`normalize(${e(t,i)})`,shadowParameters:t.castsShadow&&{getShadowProjMatrix:()=>r.shadowProjMatrix,getShadowViewMatrix:()=>r.shadowViewMatrix,getShadowMap:()=>r.shadowMap}},setupLightsInputs:()=>{const e=Object.values(r).map((e=>e.setupLightsInputs())).filter((e=>e));return()=>e.forEach((e=>e()))}});return"dir"===t.type?"view"===t.space?n(((e,t)=>`-${r.direction}`)):n(((e,t)=>`-(${e} * vec4(${r.direction}, 0.0)).xyz`)):"point"===t.type?"view"===t.space?n(((e,t)=>`${r.position} - ${t}`)):n(((e,t)=>`(${e} * vec4(${r.position}, 1.0)).xyz - ${t}`)):null})).filter((e=>e)),n=(t,i)=>{const s=()=>{const e=i();return e.length>0&&e[0]},r=s();return r&&bi(e,"samplerCube",t,r.encoding,(e=>{const t=s();t&&e(t.texture)}))},A=n("light",(()=>t.lightMaps)),o=n("reflection",(()=>t.reflectionMaps));return{getHash:()=>t.getHash(),getAmbientColor:()=>`${i}.rgb * ${i}.a`,directionalLights:r.map((e=>e.glslLight)),getIrradiance:A&&(e=>`${A(e)}.rgb`),getReflection:o&&((e,t)=>`${o(e,t)}.rgb`)}},bi=(e,t,i,s,r)=>{const n=e.createUniform(t,i+"Map",r);return(e,t)=>{const i=t?`texture(${n}, ${e}, ${t})`:`texture(${n}, ${e})`;return 3e3!==s?`${gi[s]}(${i})`:i}},yi=function(e,t){const i={},s=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<s;++r){const n=e.getActiveAttrib(t,r),A=e.getAttribLocation(t,n.name);i[n.name]=function(t){t.bindAtLocation(A),e.enableVertexAttribArray(A);const i=t.attributeDivisor;i&&e.vertexAttribDivisor(A,i)},i[n.name].attributeHash=`${A.toString().padStart(1+Math.floor(Math.log10(s)),"0")}:${n.name}`}const r=e.getProgramParameter(t,e.ACTIVE_UNIFORM_BLOCKS);for(let s=0;s<r;++s){const r=e.getActiveUniformBlockName(t,s),n=e.getUniformBlockIndex(t,r),A=s;e.uniformBlockBinding(t,n,A);const o=e.createBuffer();i[r]=function(t){e.bindBuffer(e.UNIFORM_BUFFER,o),e.bufferData(e.UNIFORM_BUFFER,t,e.DYNAMIC_DRAW),e.bindBufferBase(e.UNIFORM_BUFFER,A,o)}}const n=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);let A=0;for(let s=0;s<n;++s){const r=e.getActiveUniform(t,s);let n=r.name;n.endsWith("[0]")&&(n=n.substr(0,n.length-3)),"\0"===n[n.length-1]&&(n=n.substr(0,n.length-1));const o=e.getUniformLocation(t,n);if(function(){for(let t in e)if(r.type===e[t])return t}(),r.type===e.SAMPLER_2D||r.type===e.SAMPLER_CUBE||r.type===e.SAMPLER_2D_SHADOW||e instanceof window.WebGL2RenderingContext&&(r.type===e.UNSIGNED_INT_SAMPLER_2D||r.type===e.INT_SAMPLER_2D)){const t=A++;i[n]=function(i){const s=i.bind(t);return s&&e.uniform1i(o,t),s}}else i[n]=function(){if(1===r.size)switch(r.type){case e.BOOL:case e.INT:return t=>e.uniform1i(o,t);case e.FLOAT:return t=>e.uniform1f(o,t);case e.FLOAT_VEC2:return t=>e.uniform2fv(o,t);case e.FLOAT_VEC3:return t=>e.uniform3fv(o,t);case e.FLOAT_VEC4:return t=>e.uniform4fv(o,t);case e.FLOAT_MAT3:return t=>e.uniformMatrix3fv(o,!1,t);case e.FLOAT_MAT4:return t=>e.uniformMatrix4fv(o,!1,t)}else if(r.size>1)switch(r.type){case e.FLOAT:return t=>e.uniform1fv(o,t);case e.FLOAT_VEC2:return t=>e.uniform2fv(o,t);case e.FLOAT_VEC3:return t=>e.uniform3fv(o,t);case e.FLOAT_VEC4:return t=>e.uniform4fv(o,t)}throw`Unhandled uniform ${n}`}()}return function(e){const t=i[e];if(!t)throw`Missing input "${e}"`;return t}},wi=d.vec4(),vi=d.vec4();class Bi{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const Ci=d.OBB3(),Mi=d.vec4(),Ei=d.vec4(),Fi=d.vec4(),Ui=d.vec3([1,0,0]),xi=d.vec3([0,1,0]),Ii=d.vec3([0,0,1]),Ti=d.vec3(3),Pi=d.vec3(3),Si=d.identityMat4(),Di=new e({}),ki={};class Qi extends D{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new Bi,this._state=new oe({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,occluder:!1!==t.occluder,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,background:!!t.background,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickOcclusionHash:"",offset:d.vec3(),origin:null,originHash:null,isUI:t.isUI});const i=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,s=this,r=e=>{let t=null;const i=()=>{if(!t){const i=mi(),r=i.programVariables.createAttribute,n=s._geometry._state,A={position:r("vec3","position"),color:n.colorsBuf&&r("vec4","color"),pickColor:r("vec4","pickColor"),uv:n.uvBuf&&r("vec2","uv"),normal:(n.autoVertexNormals||n.normalsBuf)&&["triangles","triangle-strip","triangle-fan"].includes(n.primitiveName)&&r("vec3","normal")},o=function(e){const t={toString:()=>(t.needed=!0,e)};return t},a=A.normal&&o("worldNormal"),l=a&&o("viewNormal"),c=A.uv&&o("decodedUv"),h=e(i.programVariables,{attributes:{position:{world:"worldPosition",view:"viewPosition"},color:A.color,pickColor:A.pickColor,uv:c,normal:A.normal&&{world:a,view:l}},viewMatrix:"viewMatrix2"}),u=[h.programName,s.scene.canvas.canvas.id,s.scene._sectionPlanesState.getHash(),s._geometry._state.hash].concat(h.getHash()).join(";");if(!(u in ki)){const e=Oi(s,A,{decodedUv:c,worldNormal:a,viewNormal:l},h,i);if(e.errors)return void console.log(e.errors.join("\n"));const t=Di.addItem({});ki[u]={drawMesh:e.drawMesh,id:t,useCount:0,delete:()=>{Di.removeItem(t),e.destroy(),delete ki[u],m.memory.programs--}},m.memory.programs++}t=ki[u],t.useCount++}};return{get:i,getId:()=>t.id,put:()=>{t&&(0==--t.useCount&&t.delete(),t=null)},drawMesh:(e,s,r)=>{i(),t&&t.drawMesh(e,s,r)}}},n=s.scene,A=e=>(t,i)=>function(e,t,i,s,r){const n=r&&_i(t,s._lightsState),A=t.createUniform("vec3","uColor",((e,t)=>e(r?t.material.fillColor:t.material.edgeColor))),o=t.createUniform("float","uAlpha",((e,t)=>e(r?t.material.fillAlpha:t.material.edgeAlpha))),a=t.createVarying("vec4","vColor",(()=>{const e=i.attributes,t=r&&[n.getAmbientColor()].concat(e.normal?n.directionalLights.map((t=>`(max(dot(${e.normal.view}, ${t.getDirection(i.viewMatrix,e.position.view)}), 0.0) * ${t.getColor()})`)):[]);return`vec4(${A}${t?` * (${t.join(" + ")})`:""}, ${o})`})),l=t.createOutput("vec4","outColor");return{getHash:()=>[e,s.gammaOutput?"go":"",n&&n.getHash()],programName:r?"EmphasisFill":"EmphasisEdges",dontSetFrontFace:!0,discardPoints:r,drawEdges:!r,appendFragmentOutputs:(e,t)=>e.push(`${l} = ${t?t(a):a};`)}}(s._state.hash,t,i,n,e);this._renderers={_drawRenderer:r(((e,t)=>"LambertMaterial"===i.type?function(e,t,i,s,r){const n=_i(t,r._lightsState),A=t.createUniform("vec4","colorize",((e,t)=>e(t.meshColorize))),o=t.createUniform("float","materialAlpha",((e,t)=>e(t.material.alpha))),a=t.createUniform("vec3","materialColor",((e,t)=>e(t.material.color))),l=t.createUniform("vec3","materialEmissive",((e,t)=>e(t.material.emissive))),c=t.createVarying("vec4","vColor",(()=>{const e=i.attributes,t=[n.getAmbientColor()].concat(e.normal?n.directionalLights.map((t=>`(max(dot(${e.normal.view}, ${t.getDirection(i.viewMatrix,e.position.view)}), 0.0) * ${t.getColor()})`)):[]);return`${A} * vec4((${t.join(" + ")}) * ${a} + ${l}, ${o});`})),h=t.createOutput("vec4","outColor");return{getHash:()=>[e,r.gammaOutput?"go":"",n.getHash(),s._state.hash],programName:"Lambert",canActAsBackground:!0,discardPoints:!0,setupPointSize:!0,setsLineWidth:!0,appendFragmentOutputs:(e,t)=>e.push(`${h} = ${t?t(c):c};`)}}(s._state.drawHash,e,t,i,n):function(e,t,i,s,r){const n=s._state,A="PhongMaterial"===n.type,o="MetallicMaterial"===n.type,a="SpecularMaterial"===n.type,l=i.attributes,c=_i(t,r._lightsState),h=t.createUniform("vec4","colorize",((e,t)=>e(t.meshColorize))),u=t.createFragmentDefinition("fresnel",((e,t)=>{t.push(`float ${e}(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {`),t.push(" float fr = abs(dot(eyeDir, normal));"),t.push(" float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),t.push(" return pow(finalFr, power);"),t.push("}")})),d=(e,i,r)=>{const n=(i,s,n)=>t.createUniform(i,e+"Fresnel"+s,((e,t)=>e(n(r(t.material))))),A=n("float","EdgeBias",(e=>e.edgeBias)),o=n("float","CenterBias",(e=>e.centerBias)),a=n("float","Power",(e=>e.power)),l=n("vec3","EdgeColor",(e=>e.edgeColor)),c=n("vec3","CenterColor",(e=>e.centerColor));return r(s)&&((e,t)=>`mix(${l+i}, ${c+i}, ${u}(${e}, ${t}, ${A}, ${o}, ${a}))`)},f=d("diffuse","",(e=>e._diffuseFresnel)),p=d("specular","",(e=>e._specularFresnel)),g=d("emissive","",(e=>e._emissiveFresnel)),m=d("alpha",".r",(e=>e._alphaFresnel)),_=(e,i)=>{const r=l.uv&&i(s),n=r&&bi(t,"sampler2D",e,r.encoding,((e,t)=>e(i(t.material)._state.texture)));return n&&function(){const s=r._state.matrix&&t.createUniform("mat4",e+"MapMatrix",((e,t)=>e(i(t.material)._state.matrix))),A=s?e=>`(${s} * ${e}).st`:e=>`${e}.st`,o=(e,t)=>n(A(e));return o.getTexCoordExpression=A,o}()},b=_("ambient",(e=>e._ambientMap)),y=_("baseColor",(e=>e._baseColorMap)),w=_("diffuse",(e=>e._diffuseMap)),v=_("emissive",(e=>e._emissiveMap)),B=_("occlusion",(e=>e._occlusionMap)),C=_("alpha",(e=>e._alphaMap)),M=_("metallic",(e=>e._metallicMap)),E=_("roughness",(e=>e._roughnessMap)),F=_("metallicRoughness",(e=>e._metallicRoughnessMap)),U=_("specular",(e=>e._specularMap)),x=_("glossiness",(e=>e._glossinessMap)),I=_("specularGlossiness",(e=>e._specularGlossinessMap)),T=_("normal",(e=>e._normalMap)),P=(e,i,r)=>{const n=r(s);return("float"===i?null!=n:n)&&t.createUniform(i,e,((e,t)=>e(r(t.material))))},S=P("materialAmbient","vec3",(e=>e.ambient)),D=P("materialDiffuse","vec3",(e=>e.diffuse)),k=P("materialBaseColor","vec3",(e=>e.baseColor)),Q=P("materialEmissive","vec3",(e=>e.emissive)),R=P("materialSpecular","vec3",(e=>e.specular)),O=P("materialGlossiness","float",(e=>e.glossiness)),V=P("materialMetallic","float",(e=>e.metallic)),L=P("materialRoughness","float",(e=>e.roughness)),H=P("materialShininess","float",(e=>e.shininess)),N=P("materialSpecularF0","float",(e=>e.specularF0)),G=P("materialAlphaModeCutoff","vec4",(e=>{const t=e.alpha;return null!=t?(wi[0]=t,wi[1]=1===e.alphaMode?1:0,wi[2]=e.alphaCutoff,wi):null})),j=t.createVarying("vec3","vViewPosition",(()=>`${l.position.view}.xyz`)),W=t.createVarying("vec4","texturePos",(()=>`vec4(${l.uv}, 1.0, 1.0)`)),z=l.color&&t.createVarying("vec4","vColor",(()=>l.color)),X=t.createVarying("vec3","vViewNormal",(()=>l.normal.view)),K=c.directionalLights.map(((e,s)=>({vViewLightReverseDir:t.createVarying("vec3",`vViewLightReverseDir${s}`,(()=>e.getDirection(i.viewMatrix,null))),vShadowPosFromLight:t.createVarying("vec3",`vShadowPosFromLight${s}`,(()=>`(mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0) * ${e.shadowParameters.getShadowProjMatrix()} * (${e.shadowParameters.getShadowViewMatrix()} * ${l.position.world})).xyz`))}))),Z=t.createVarying("vec3","vWorldNormal",(()=>l.normal.world)),J=t.createOutput("vec4","outColor"),Y=t.createFragmentDefinition("saturate",((e,t)=>t.push(`float ${e}(const in float a) { return clamp(a, 0.0, 1.0); }`))),$=t.createFragmentDefinition("BRDF_Specular_GGX",((e,t)=>{t.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),t.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),t.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),t.push("}"),t.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),t.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),t.push(" return 1.0 / ( gl * gv );"),t.push("}"),t.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),t.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),t.push(" return 0.5 / max( gv + gl, 1e-6 );"),t.push("}"),t.push("float D_GGX(const in float alpha, const in float dotNH) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),t.push(" return 0.31830988618 * a2 / ( denom * denom);"),t.push("}"),t.push(`vec3 ${e}(const in vec3 incidentLightDirection, const in vec3 viewNormal, const in vec3 viewEyeDir, const in vec3 specularColor, const in float roughness) {`),t.push(" float alpha = ( roughness * roughness );"),t.push(" vec3 halfDir = normalize( incidentLightDirection + viewEyeDir );"),t.push(` float dotNL = ${Y}( dot( viewNormal, incidentLightDirection ) );`),t.push(` float dotNV = ${Y}( dot( viewNormal, viewEyeDir ) );`),t.push(` float dotNH = ${Y}( dot( viewNormal, halfDir ) );`),t.push(` float dotLH = ${Y}( dot( incidentLightDirection, halfDir ) );`),t.push(" vec3 F = F_Schlick( specularColor, dotLH );"),t.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),t.push(" float D = D_GGX( alpha, dotNH );"),t.push(" return F * (G * D);"),t.push("}")})),q=t.createFragmentDefinition("BRDF_Specular_GGX_Environment",((e,t)=>{t.push(`vec3 ${e}(const in vec3 viewNormal, const in vec3 viewEyeDir, const in vec3 specularColor, const in float roughness) {`),t.push(` float dotNV = ${Y}(dot(viewNormal, viewEyeDir));`),t.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),t.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),t.push(" vec4 r = roughness * c0 + c1;"),t.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),t.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),t.push(" return specularColor * AB.x + AB.y;"),t.push("}")})),ee=t.createFragmentDefinition("perturbNormal2Arb",((e,t)=>{t.push(`vec3 ${e}( vec3 eye_pos, vec3 surf_norm, vec2 uv, vec4 texel ) {`),t.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),t.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),t.push(" vec2 st0 = dFdx( uv.st );"),t.push(" vec2 st1 = dFdy( uv.st );"),t.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),t.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),t.push(" vec3 N = normalize( surf_norm );"),t.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),t.push(" mat3 tsn = mat3( S, T, N );"),t.push(" return normalize( tsn * mapN );"),t.push("}")}));return{getHash:()=>[e,r.gammaOutput?"go":"",c.getHash(),s._state.hash],programName:"Draw",canActAsBackground:!0,discardPoints:!0,setupPointSize:!0,setsLineWidth:!0,appendFragmentOutputs:(e,t,s)=>{const r=l.normal&&(c.directionalLights.length>0||c.getIrradiance||c.getReflection);if(e.push(`vec3 diffuseColor = ${r&&(A||a)&&D||o&&k||"vec3(1.0)"};`),e.push(`vec4 alphaModeCutoff = ${(A||o||a)&&G||"vec4(1.0, 0.0, 0.0, 0.0)"};`),e.push("float alpha = alphaModeCutoff[0];"),(A||o||a)&&C&&e.push(`alpha *= ${C(W)}.r;`),z&&(e.push(`diffuseColor *= ${z}.rgb;`),e.push(`alpha *= ${z}.a;`)),o&&y&&(e.push("vec4 baseColorTexel = "+y(W)+";"),e.push("diffuseColor *= baseColorTexel.rgb;"),e.push("alpha *= baseColorTexel.a;")),(A||a)&&w&&(e.push("vec4 diffuseTexel = "+w(W)+";"),e.push("diffuseColor *= diffuseTexel.rgb;"),e.push("alpha *= diffuseTexel.a;")),e.push(`vec3 emissiveColor = ${(A||o||a)&&Q||"vec3(0.0)"};`),(A||o||a)&&v&&e.push(`emissiveColor = ${v(W)}.rgb;`),r){e.push(`vec3 specular = ${(A||a)&&R||"vec3(1.0)"};`),e.push(`float glossiness = ${a&&O||"1.0"};`),e.push(`float metallic = ${o&&V||"1.0"};`),e.push(`float roughness = ${(o||a)&&L||"1.0"};`),e.push(`float shininess = ${A&&H||"1.0"};`),e.push(`float specularF0 = ${o&&N||"1.0"};`),e.push(`float occlusion = ${(A||o||a)&&B?`${B(W)}.r`:"1.0"};`),o&&M&&e.push(`metallic *= ${M(W)}.r;`),o&&E&&e.push(`roughness *= ${E(W)}.r;`),o&&F&&(e.push("vec4 metalRoughTexel = "+F(W)+";"),e.push("metallic *= metalRoughTexel.b;"),e.push("roughness *= metalRoughTexel.g;")),(A||a)&&U&&e.push(`specular *= ${U(W)}.rgb;`),a&&x&&e.push(`glossiness *= ${x(W)}.r;`),a&&I&&(e.push("vec4 specGlossTexel = "+I(W)+";"),e.push("specular *= specGlossTexel.rgb;"),e.push("glossiness *= specGlossTexel.a;"));const t=`normalize(${X})`,s=(A||o||a)&&T?`${ee}(${j}, ${t}, ${T.getTexCoordExpression(W)}, ${T(W)})`:t;if(e.push(`vec3 viewNormal = ${s};`),e.push(`vec3 viewEyeDir = normalize(-${j});`),f&&e.push(`diffuseColor *= ${f("viewEyeDir","viewNormal")};`),p&&e.push(`specular *= ${p("viewEyeDir","viewNormal")};`),g&&e.push(`emissiveColor *= ${g("viewEyeDir","viewNormal")};`),m&&e.push(`alpha *= ${m("viewEyeDir","viewNormal")};`),e.push("if (alphaModeCutoff[1] == 1.0 && alpha < alphaModeCutoff[2]) {"),e.push(" discard;"),e.push("}"),e.push("vec3 material_diffuseColor;"),A&&(e.push("material_diffuseColor = diffuseColor;"),e.push("roughness = 0.0;")),a&&(e.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),e.push("material_diffuseColor = diffuseColor * oneMinusSpecularStrength;"),e.push("roughness = clamp(1.0 - glossiness, 0.04, 1.0);")),o&&(e.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),e.push("material_diffuseColor = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),e.push("roughness = clamp(roughness, 0.04, 1.0);"),e.push("specular = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),A||o||a){if(e.push("const float PI = 3.14159265359;"),e.push("vec3 reflDiff = vec3(0.0);"),e.push("vec3 reflSpec = vec3(0.0);"),c.getIrradiance&&e.push(`reflDiff += ${c.getIrradiance(`normalize(${Z})`)};`),c.getReflection){const t="reflect(-viewEyeDir, viewNormal)",s=A?`0.2 * PI * ${c.getReflection(t)}`:function(){const e=`${q}(viewNormal, viewEyeDir, specular, roughness)`,s=`normalize((vec4(${t}, 0.0) * ${i.viewMatrix}).xyz)`;return`${e} * ${c.getReflection(s,"clamp(4.0 - 0.39624 - 0.25 * log2(pow(2.0 / pow(roughness + 0.0001, 2.0) - 2.0, 2.0) + 1.0), 0.0, 4.0)")}`}();e.push(`reflSpec += ${s};`)}c.directionalLights.some((e=>e.shadowParameters))&&(e.push("const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),e.push("const float texelSize = 1.0 / 1024.0;"),e.push("float shadow;"),e.push("float fragmentDepth;")),c.directionalLights.forEach(((t,i)=>{if(t.shadowParameters){const s="0.007";e.push(`fragmentDepth = ${K[i].vShadowPosFromLight}.z - ${s};`),e.push("shadow = 0.0;"),e.push("for (int x = -3; x <= 3; x++) {"),e.push(" for (int y = -3; y <= 3; y++) {"),e.push(` float texelDepth = dot(texture(${t.getShadowMap()}, ${K[i].vShadowPosFromLight}.xy + vec2(x, y) * texelSize), bitShift);`),e.push(" if (fragmentDepth < texelDepth) {"),e.push(" shadow += 1.0;"),e.push(" }"),e.push(" }"),e.push("}"),e.push("shadow /= 9.0;")}e.push(`vec3 lightColor${i} = ${t.getColor()}${t.shadowParameters?" * shadow":""};`),e.push(`vec3 lightDirection${i} = ${t.isWorldSpace?K[i].vViewLightReverseDir:t.getDirection(null,j)};`);const s=`${Y}(dot(viewNormal, lightDirection${i}))`;e.push(`vec3 irradiance${i} = ${s} * lightColor${i};`),e.push(`reflDiff += irradiance${i};`);const r=A?`lightColor${i} * specular * pow(max(dot(reflect(-lightDirection${i}, -viewNormal), viewEyeDir), 0.0), shininess)`:`irradiance${i} * PI * ${$}(lightDirection${i}, viewNormal, viewEyeDir, specular, roughness)`;e.push(`reflSpec += ${r};`)}))}const r=A&&`${c.getAmbientColor()} * diffuseColor`;e.push("vec3 outgoingLight = emissiveColor + occlusion * (reflDiff * material_diffuseColor + reflSpec)"+(r?" + "+r:"")+";")}else e.push(`vec3 ambientColor = ${A&&S||"vec3(1.0)"};`),A&&b&&e.push(`ambientColor *= ${b(W)}.rgb;`),e.push(`ambientColor *= ${c.getAmbientColor()};`),e.push("vec3 outgoingLight = emissiveColor + ambientColor;");e.push(`vec4 fragColor = ${h} * vec4(outgoingLight, alpha);`),e.push(`${J} = ${t?t("fragColor"):"fragColor"};`)}}}(s._state.drawHash,e,t,i,n))),_shadowRenderer:r((e=>function(e,t){const i=t.createFragmentDefinition("encodeFloat",((e,t)=>{t.push(`vec4 ${e}( const in float depth ) {`),t.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),t.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),t.push(" vec4 comp = fract(depth * bitShift);"),t.push(" comp -= comp.xxyz * bitMask;"),t.push(" return comp;"),t.push("}")})),s=t.createOutput("vec4","outColor");return{getHash:()=>[e],programName:"Shadow",setsLineWidth:!0,useShadowView:!0,dontBillboardAnything:!0,dontGetLogDepth:!0,appendFragmentOutputs:(e,t,r)=>e.push(`${s} = ${i}(${r}.z);`)}}(s._state.hash,e))),_emphasisEdgesRenderer:r(A(!1)),_emphasisFillRenderer:r(A(!0)),_pickMeshRenderer:r((e=>function(e,t){const i=t.createUniform("vec4","pickColor",((e,t)=>{var i=t.meshPickID;vi[0]=255&i,vi[1]=i>>8&255,vi[2]=i>>16&255,vi[3]=i>>24&255,d.mulVec4Scalar(vi,1/255,vi),e(vi)})),s=t.createOutput("vec4","outColor");return{getHash:()=>[e],programName:"PickMesh",isPick:!0,dontBillboardAnything:!0,appendFragmentOutputs:e=>e.push(`${s} = ${i};`)}}(s._state.hash,e))),_pickTriangleRenderer:r(((e,t)=>function(e,t,i){const s=t.createVarying("vec4","vColor",(()=>i.attributes.pickColor)),r=t.createOutput("vec4","outColor");return{getHash:()=>[e],programName:"PickTriangle",isPick:!0,trianglePick:!0,dontBillboardAnything:!0,appendFragmentOutputs:e=>e.push(`${r} = ${s};`)}}(s._state.hash,e,t))),_occlusionRenderer:r((e=>function(e,t){const i=t.createOutput("vec4","outColor");return{getHash:()=>[e],programName:"Occlusion",skipIfTransparent:!0,appendFragmentOutputs:e=>e.push(`${i} = vec4(0.0, 0.0, 1.0, 1.0);`)}}(s._state.pickOcclusionHash,e)))},this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=i,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=d.vec3(),this._quaternion=d.identityQuaternion(),this._rotation=d.vec3(),this._position=d.vec3(),this._worldMatrix=d.identityMat4(),this._worldNormalMatrix=d.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0;const o=t.origin||t.rtcCenter;if(o&&(this._state.origin=d.vec3(o),this._state.originHash=o.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get type(){return"Mesh"}get isMesh(){return!0}get parent(){return this._parentNode}get geometry(){return this._geometry}get material(){return this._material}get position(){return this._position}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=d.identityMat4()),d.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}set matrix(e){this.__localMatrix||(this.__localMatrix=d.identityMat4()),this.__localMatrix.set(e||Si),d.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get isUI(){return this._state.isUI}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}get origin(){return this._state.origin}set origin(e){e?(this._state.origin||(this._state.origin=d.vec3()),this._state.origin.set(e),this._state.originHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.origin&&(this._state.origin=null,this._state.originHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this.origin}set rtcCenter(e){this.origin=e}get numTriangles(){return this._numTriangles}get visible(){return this._state.visible}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this,e),this.glRedraw()}get xrayed(){return this._state.xrayed}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this,e),this.glRedraw())}get highlighted(){return this._state.highlighted}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this,e),this.glRedraw())}get selected(){return this._state.selected}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this,e),this.glRedraw())}get edges(){return this._state.edges}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get culled(){return this._state.culled}set culled(e){this._state.culled=!!e,this.glRedraw()}get clippable(){return this._state.clippable}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get collidable(){return this._state.collidable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get pickable(){return this._state.pickable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get castsShadow(){return this._state.castsShadow}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get receivesShadow(){return this._state.receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get saoEnabled(){return!1}get colorize(){return this._state.colorize}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}get opacity(){return this._state.colorize[3]}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}get layer(){return this._state.layer}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}get offset(){return this._state.offset}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get isDrawable(){return!0}get isStateSortable(){return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this.scene,t=this._state,i=[e.canvas.canvas.id,e._sectionPlanesState.getHash()];t.stationary&&i.push("/s"),"none"===t.billboard?i.push("/n"):"spherical"===t.billboard?i.push("/s"):"cylindrical"===t.billboard&&i.push("/c"),i.push(";");const s=i.concat([e.gammaOutput?"go":"",e._lightsState.getHash(),t.receivesShadow?"/rs":""]).join("");this._state.drawHash!==s&&(this._state.drawHash=s,this._renderers._drawRenderer.put(),this._renderers._shadowRenderer.put(),this._renderers._emphasisFillRenderer.put(),this._renderers._emphasisEdgesRenderer.put(),this._renderers._drawRenderer.get(),this._renderers._emphasisFillRenderer.get(),this._renderers._emphasisEdgesRenderer.get());const r=i.join("");this._state.pickOcclusionHash!==r&&(this._state.pickOcclusionHash=r,this._renderers._pickMeshRenderer.put(),this._renderers._pickTriangleRenderer.put(),this._renderers._pickMeshRenderer.get(),this._state.occluder&&(this._renderers._occlusionRenderer.put(),this._renderers._occlusionRenderer.get()))}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)d.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=d.mat4()),d.transposeMat4(this._worldMatrix,this._worldNormalMatrix),d.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=d.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_buildAABB(e,t){d.transformOBB3(e,this._geometry.obb,Ci),d.OBB3ToAABB3(Ci,t);const i=this._state.offset;if(t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[0],t[4]+=i[1],t[5]+=i[2],this._state.origin){const e=this._state.origin;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}rotate(e,t){return Mi[0]=e[0],Mi[1]=e[1],Mi[2]=e[2],Mi[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Mi,Ei),d.mulQuaternions(this.quaternion,Ei,Fi),this.quaternion=Fi,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Mi[0]=e[0],Mi[1]=e[1],Mi[2]=e[2],Mi[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(Mi,Ei),d.mulQuaternions(Ei,this.quaternion,Ei),this}rotateX(e){return this.rotate(Ui,e)}rotateY(e){return this.rotate(xi,e)}rotateZ(e){return this.rotate(Ii,e)}translate(e,t){return d.vec3ApplyQuaternion(this.quaternion,e,Ti),d.mulVec3Scalar(Ti,t,Pi),d.addVec3(this.position,Pi,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(Ui,e)}translateY(e){return this.translate(xi,e)}translateZ(e){return this.translate(Ii,e)}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._renderers._drawRenderer.getId()-t._renderers._drawRenderer.getId()||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else{if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges){this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0}if(t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i],s=this.renderFlags;if(t.active)if(this._state.origin){const e=d.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const r=0===e;s.sectionPlanesActivePerLayer[i]=r}else s.sectionPlanesActivePerLayer[i]=!0;else s.sectionPlanesActivePerLayer[i]=!1}}return!0}drawColorOpaque(e){this._renderers._drawRenderer.drawMesh(e,this,this._material)}drawColorTransparent(e){this._renderers._drawRenderer.drawMesh(e,this,this._material)}drawSilhouetteXRayed(e){this._renderers._emphasisFillRenderer.drawMesh(e,this,this._xrayMaterial)}drawSilhouetteHighlighted(e){this._renderers._emphasisFillRenderer.drawMesh(e,this,this._highlightMaterial)}drawSilhouetteSelected(e){this._renderers._emphasisFillRenderer.drawMesh(e,this,this._selectedMaterial)}drawEdgesColorOpaque(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._edgeMaterial)}drawEdgesColorTransparent(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._edgeMaterial)}drawEdgesXRayed(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._xrayMaterial)}drawEdgesHighlighted(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._highlightMaterial)}drawEdgesSelected(e){this._renderers._emphasisEdgesRenderer.drawMesh(e,this,this._selectedMaterial)}drawOcclusion(e){this._renderers._occlusionRenderer.drawMesh(e,this,this._material)}drawShadow(e){this._renderers._shadowRenderer.drawMesh(e,this,this._material)}drawPickMesh(e){this._renderers._pickMeshRenderer.drawMesh(e,this,this._material)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){this._renderers._pickTriangleRenderer.drawMesh(e,this,this._material)}pickTriangleSurface(e,t,i,s){Ri(this,e,t,i,s)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),Object.values(this._renderers).forEach((e=>e.put())),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.offset.some((e=>0!==e))&&this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const Ri=function(){const e=d.vec3(),t=d.vec3(),i=d.vec3(),s=d.vec3(),r=d.vec3(),n=d.vec3(),A=d.vec4(),o=d.vec3(),a=d.vec3(),l=d.vec3(),c=d.vec3(),h=d.vec3(),u=d.vec3(),f=d.vec3(),p=d.vec3(),g=d.vec3(),m=d.vec4(),_=d.vec4(),b=d.vec4(),y=d.vec3(),w=d.vec3(),v=d.vec3(),B=d.vec3(),C=d.vec3(),M=d.vec3(),E=d.vec3(),F=d.vec3(),U=d.vec3(),x=d.vec3(),I=d.vec3();return function(T,P,S,D,k){var Q=k.primIndex;if(null!=Q&&Q>-1){const L=T.geometry._state,H=T.scene,N=H.camera,G=H.canvas;if("triangles"===L.primitiveName){k.primitive="triangle";const H=Q,j=L.indices,W=L.positions;let z,X,K;if(j){var R=j[H+0],O=j[H+1],V=j[H+2];n[0]=R,n[1]=O,n[2]=V,k.indices=n,z=3*R,X=3*O,K=3*V}else z=3*H,X=z+3,K=X+3;if(i[0]=W[z+0],i[1]=W[z+1],i[2]=W[z+2],s[0]=W[X+0],s[1]=W[X+1],s[2]=W[X+2],r[0]=W[K+0],r[1]=W[K+1],r[2]=W[K+2],L.compressGeometry){const e=L.positionsDecodeMatrix;e&&(ge.decompressPosition(i,e,i),ge.decompressPosition(s,e,s),ge.decompressPosition(r,e,r))}k.canvasPos?d.canvasPosToLocalRay(G.canvas,T.origin?Je(P,T.origin):P,S,D,T.worldMatrix,k.canvasPos,e,t):k.origin&&k.direction&&d.worldRayToLocalRay(T.worldMatrix,k.origin,k.direction,e,t),d.normalizeVec3(t),d.rayPlaneIntersect(e,t,i,s,r,A),k.localPos=A,k.position=A,m[0]=A[0],m[1]=A[1],m[2]=A[2],m[3]=1,d.transformVec4(T.worldMatrix,m,_),o[0]=_[0],o[1]=_[1],o[2]=_[2],k.canvasPos&&T.origin&&(o[0]+=T.origin[0],o[1]+=T.origin[1],o[2]+=T.origin[2]),k.worldPos=o,d.transformVec4(N.matrix,_,b),a[0]=b[0],a[1]=b[1],a[2]=b[2],k.viewPos=a,d.cartesianToBarycentric(A,i,s,r,l),k.bary=l;const Z=L.normals;if(Z){if(L.compressGeometry){const e=3*R,t=3*O,i=3*V;ge.decompressNormal(Z.subarray(e,e+2),c),ge.decompressNormal(Z.subarray(t,t+2),h),ge.decompressNormal(Z.subarray(i,i+2),u)}else c[0]=Z[z],c[1]=Z[z+1],c[2]=Z[z+2],h[0]=Z[X],h[1]=Z[X+1],h[2]=Z[X+2],u[0]=Z[K],u[1]=Z[K+1],u[2]=Z[K+2];const e=d.addVec3(d.addVec3(d.mulVec3Scalar(c,l[0],y),d.mulVec3Scalar(h,l[1],w),v),d.mulVec3Scalar(u,l[2],B),C);k.worldNormal=d.normalizeVec3(d.transformVec3(T.worldNormalMatrix,e,M))}const J=L.uv;if(J){if(f[0]=J[2*R],f[1]=J[2*R+1],p[0]=J[2*O],p[1]=J[2*O+1],g[0]=J[2*V],g[1]=J[2*V+1],L.compressGeometry){const e=L.uvDecodeMatrix;e&&(ge.decompressUV(f,e,f),ge.decompressUV(p,e,p),ge.decompressUV(g,e,g))}k.uv=d.addVec3(d.addVec3(d.mulVec2Scalar(f,l[0],E),d.mulVec2Scalar(p,l[1],F),U),d.mulVec2Scalar(g,l[2],x),I)}}}}}(),Oi=(e,t,i,s,r)=>{const n=r.programVariables,A=i.decodedUv,o=i.worldNormal,a=i.viewNormal,l=e.scene,c=l.canvas.gl,h=e._state.background,u=e._geometry._state,d=u.compressGeometry,f="points"===u.primitiveName,p=n.createUniform("float","pointSize"),g=n.createUniform("mat4","modelMatrix"),m=n.createUniform("mat4","modelNormalMatrix"),_=n.createUniform("vec3","offset"),b=n.createUniform("vec3","scale"),y=n.createUniform("mat4","positionsDecodeMatrix"),w=n.createUniform("mat3","uvDecodeMatrix"),v=n.createUniform("mat4","viewMatrix"),B=n.createUniform("mat4","viewNormalMatrix"),C=n.createUniform("mat4","projMatrix"),M=e.billboard,E=!s.dontBillboardAnything&&("spherical"===M||"cylindrical"===M),F=e.stationary,U=E&&((e,t)=>[`mat4 ${e}(in mat4 matIn) {`," mat4 mat = matIn;",` mat[0].xyz = vec3(${b}[0], 0.0, 0.0);`,..."spherical"===M?[` mat[1].xyz = vec3(0.0, ${b}[1], 0.0);`]:[]," mat[2].xyz = vec3(0.0, 0.0, 1.0);"," return mat;","}"].forEach((e=>t.push(e)))),x=function(){const e=U&&n.createVertexDefinition("billboard",U);return t=>e?`${e}(${t})`:t}(),I=function(){const e=U&&n.createFragmentDefinition("billboard",U);return t=>e?`${e}(${t})`:t}(),T=[];s.dontBillboardAnything?T.push(`mat4 viewMatrix2 = ${v};`):(T.push(`mat4 viewMatrix1 = ${v};`),F?T.push("viewMatrix1[3].xyz = vec3(0.0, 0.0, 0.0);"):h&&T.push("viewMatrix1[3] = vec4(0.0, 0.0, 0.0, 1.0);"),T.push(`mat4 viewMatrix2 = ${I("viewMatrix1")};`));const P="clipPos",S=n.createUniform("bool","clippable"),[D,k]=r.buildProgram(c,s.programName,{appendFragmentOutputs:(e,t,i,r)=>{T.forEach((t=>e.push(t))),s.appendFragmentOutputs(e,t,i,r)},clippableTest:()=>S,clippingCaps:s.clippingCaps,clipPos:h?"clipPos.xyww":P,crossSections:l.crossSections,discardPoints:f&&s.discardPoints,getGammaFactor:l.gammaOutput&&(()=>l.gammaFactor),getLogDepth:!s.dontGetLogDepth&&l.logarithmicDepthBufferEnabled&&(e=>e),getPointSize:s.setupPointSize&&f&&(()=>p),getVertexData:function(){const e=a&&a.needed&&`vec3 ${a} = normalize((${x(B)} * vec4(${o}, 0.0)).xyz);`,i=[];if(i.push(`vec4 localPosition = vec4(${t.position}, 1.0);`),d&&i.push(`localPosition = ${y} * localPosition;`),i.push(`vec4 worldPosition = ${x(g)} * localPosition;`),i.push(`worldPosition.xyz = worldPosition.xyz + ${_};`),s.dontBillboardAnything?i.push(`vec4 viewPosition = ${v} * worldPosition;`):(i.push(`mat4 viewMatrix1 = ${v};`),F?i.push("viewMatrix1[3].xyz = vec3(0.0, 0.0, 0.0);"):h&&i.push("viewMatrix1[3] = vec4(0.0, 0.0, 0.0, 1.0);"),i.push(`mat4 viewMatrix2 = ${x("viewMatrix1")};`),i.push(`vec4 viewPosition = ${E?`${x(`viewMatrix1 * ${g}`)} * localPosition`:"viewMatrix2 * worldPosition"};`)),A&&A.needed&&i.push(`vec2 ${A} = ${d?`(${w} * vec3(${t.uv}, 1.0)).xy`:t.uv};`),o&&o.needed){const e=d?`${n.commonLibrary.octDecode}(${t.normal}.xy)`:t.normal;i.push(`vec3 ${o} = (${x(m)} * vec4(${e}, 0.0)).xyz;`)}return e&&i.push(e),i.push(`vec4 clipPos = ${C} * viewPosition;`),i},projMatrix:C,sectionPlanesState:l._sectionPlanesState,testPerspectiveForGl_FragDepth:!0,usePickClipPos:s.isPick,worldPositionAttribute:"worldPosition"});if(k)return{errors:k};{const e=D.inputSetters;let i=null,r=null;return{destroy:()=>D.destroy(),drawMesh:(n,A,o)=>{if(s.skipIfTransparent&&o.alpha<1)return;const a=o._state,l=A._state,u=A._geometry,d=u._state,f=n.viewParams,M=s.canActAsBackground&&h;n.lastProgramId!==D.id&&(n.lastProgramId=D.id,D.bind(),n.useProgram++,i=null,r=null,M&&c.depthFunc(c.LEQUAL)),a.id!==i&&(n.backfaces!==a.backfaces&&(a.backfaces?c.disable(c.CULL_FACE):c.enable(c.CULL_FACE),n.backfaces=a.backfaces),s.dontSetFrontFace||n.frontface===a.frontface||(c.frontFace(a.frontface?c.CCW:c.CW),n.frontface=a.frontface),s.drawEdges&&n.lineWidth!==a.edgeWidth&&(c.lineWidth(a.edgeWidth),n.lineWidth=a.edgeWidth),s.setsLineWidth&&n.lineWidth!==a.lineWidth&&(c.lineWidth(a.lineWidth),n.lineWidth=a.lineWidth),i=a.id);const E=!s.useShadowView&&A.origin;((t,i)=>{const s=(e,t)=>e.setInputValue&&e.setInputValue(t);s(p,o.pointSize),s(g,A.worldMatrix),s(m,A.worldNormalMatrix),s(_,A.offset),s(b,A.scale),s(y,d.positionsDecodeMatrix),s(w,d.uvDecodeMatrix),s(v,i),s(B,f.viewNormalMatrix),s(C,t),s(S,A.clippable),e.setUniforms(n,{material:o,meshColorize:A.colorize,meshPickID:A._state.pickID,mesh:{origin:A.origin,renderFlags:{sectionPlanesActivePerLayer:A.renderFlags.sectionPlanesActivePerLayer}},view:{far:f.far}})})(f.projMatrix,E?n.getRTCViewMatrix(l.originHash,E):f.viewMatrix);const F=e=>{const i=(e,t)=>{e&&e.setInputValue&&t&&(e.setInputValue(t),n.bindArray++)};i(t.position,(e||d).positionsBuf),i(t.color,d.colorsBuf),i(t.pickColor,e&&e.pickColorsBuf),i(t.uv,d.uvBuf),i(t.normal,d.normalsBuf)};if(s.trianglePick){const e=u._getPickTrianglePositions();d.id!==r&&(F({positionsBuf:e,pickColorsBuf:u._getPickTriangleColors()}),r=d.id),c.drawArrays(d.primitive,0,e.numItems/3)}else if(s.drawEdges){const e=d.primitive===c.TRIANGLES?u._getEdgeIndices():d.primitive===c.LINES&&d.indicesBuf;e&&(d.id!==r&&(F(),e.bind(),n.bindArray++,r=d.id),c.drawElements(c.LINES,e.numItems,e.itemType,0),n.drawElements++)}else d.id!==r&&(F(),d.indicesBuf&&(d.indicesBuf.bind(),n.bindArray++),r=d.id),d.indicesBuf?(c.drawElements(d.primitive,d.indicesBuf.numItems,d.indicesBuf.itemType,0),n.drawElements++):d.positionsBuf&&(c.drawArrays(c.TRIANGLES,0,d.positionsBuf.numItems),n.drawArrays++);M&&c.depthFunc(c.LESS)}}}};class Vi extends D{get type(){return"Material"}constructor(e,t={}){super(e,t),m.memory.materials++}destroy(){super.destroy(),m.memory.materials--}}const Li={opaque:0,mask:1,blend:2},Hi=["opaque","mask","blend"];class Ni extends Vi{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new oe({type:"PhongMaterial",ambient:d.vec3([1,1,1]),diffuse:d.vec3([1,1,1]),specular:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=Li[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Hi[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}function Gi(e,t){if(void 0===e._cachedExtensions&&(e._cachedExtensions={}),void 0!==e._cachedExtensions[t])return e._cachedExtensions[t];let i;switch(t){case"WEBGL_depth_texture":i=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":i=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":i=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":i=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:i=e.getExtension(t)}return e._cachedExtensions[t]=i,i}function ji(e,t,i=null){let s;const r=t;if(1009===r)return e.UNSIGNED_BYTE;if(1017===r)return e.UNSIGNED_SHORT_4_4_4_4;if(1018===r)return e.UNSIGNED_SHORT_5_5_5_1;if(1010===r)return e.BYTE;if(1011===r)return e.SHORT;if(1012===r)return e.UNSIGNED_SHORT;if(1013===r)return e.INT;if(1014===r)return e.UNSIGNED_INT;if(1015===r)return e.FLOAT;if(1016===r)return e.HALF_FLOAT;if(1021===r)return e.ALPHA;if(1023===r)return e.RGBA;if(1024===r)return e.LUMINANCE;if(1025===r)return e.LUMINANCE_ALPHA;if(1026===r)return e.DEPTH_COMPONENT;if(1027===r)return e.DEPTH_STENCIL;if(1028===r)return e.RED;if(1022===r)return e.RGBA;if(1029===r)return e.RED_INTEGER;if(1030===r)return e.RG;if(1031===r)return e.RG_INTEGER;if(1033===r)return e.RGBA_INTEGER;if(33776===r||33777===r||33778===r||33779===r)if(3001===i){const t=Gi(e,"WEBGL_compressed_texture_s3tc_srgb");if(null===t)return null;if(33776===r)return t.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(33777===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(33778===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(33779===r)return t.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(s=Gi(e,"WEBGL_compressed_texture_s3tc"),null===s)return null;if(33776===r)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(33777===r)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(33778===r)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(33779===r)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(35840===r||35841===r||35842===r||35843===r){const t=Gi(e,"WEBGL_compressed_texture_pvrtc");if(null===t)return null;if(35840===r)return t.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(35841===r)return t.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(35842===r)return t.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(35843===r)return t.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(36196===r){const t=Gi(e,"WEBGL_compressed_texture_etc1");return null!==t?t.COMPRESSED_RGB_ETC1_WEBGL:null}if(37492===r||37496===r){const t=Gi(e,"WEBGL_compressed_texture_etc");if(null===t)return null;if(37492===r)return 3001===i?t.COMPRESSED_SRGB8_ETC2:t.COMPRESSED_RGB8_ETC2;if(37496===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:t.COMPRESSED_RGBA8_ETC2_EAC}if(37808===r||37809===r||37810===r||37811===r||37812===r||37813===r||37814===r||37815===r||37816===r||37817===r||37818===r||37819===r||37820===r||37821===r){const t=Gi(e,"WEBGL_compressed_texture_astc");if(null===t)return null;if(37808===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:t.COMPRESSED_RGBA_ASTC_4x4_KHR;if(37809===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:t.COMPRESSED_RGBA_ASTC_5x4_KHR;if(37810===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:t.COMPRESSED_RGBA_ASTC_5x5_KHR;if(37811===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:t.COMPRESSED_RGBA_ASTC_6x5_KHR;if(37812===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:t.COMPRESSED_RGBA_ASTC_6x6_KHR;if(37813===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:t.COMPRESSED_RGBA_ASTC_8x5_KHR;if(37814===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:t.COMPRESSED_RGBA_ASTC_8x6_KHR;if(37815===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:t.COMPRESSED_RGBA_ASTC_8x8_KHR;if(37816===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:t.COMPRESSED_RGBA_ASTC_10x5_KHR;if(37817===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:t.COMPRESSED_RGBA_ASTC_10x6_KHR;if(37818===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:t.COMPRESSED_RGBA_ASTC_10x8_KHR;if(37819===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:t.COMPRESSED_RGBA_ASTC_10x10_KHR;if(37820===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:t.COMPRESSED_RGBA_ASTC_12x10_KHR;if(37821===r)return 3001===i?t.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:t.COMPRESSED_RGBA_ASTC_12x12_KHR}if(36492===r){const t=Gi(e,"EXT_texture_compression_bptc");if(null===t)return null;if(36492===r)return 3001===i?t.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:t.COMPRESSED_RGBA_BPTC_UNORM_EXT}return 1020===r?e.UNSIGNED_INT_24_8:1e3===r?e.REPEAT:1001===r?e.CLAMP_TO_EDGE:1004===r||1005===r?e.NEAREST_MIPMAP_LINEAR:1007===r?e.LINEAR_MIPMAP_NEAREST:1008===r?e.LINEAR_MIPMAP_LINEAR:1003===r?e.NEAREST:1006===r?e.LINEAR:null}const Wi=new Uint8Array([0,0,0,1]);class zi{constructor({gl:e,target:t,format:i,type:s,wrapS:r,wrapT:n,wrapR:A,encoding:o,preloadColor:a,premultiplyAlpha:l,flipY:c}){this.gl=e,this.target=t||e.TEXTURE_2D,this.format=i||1023,this.type=s||1009,this.internalFormat=null,this.premultiplyAlpha=!!l,this.flipY=!!c,this.unpackAlignment=4,this.wrapS=r||1e3,this.wrapT=n||1e3,this.wrapR=A||1e3,this.encoding=o||3001,this.texture=e.createTexture(),a&&this.setPreloadColor(a),this.allocated=!0}setPreloadColor(e){e?(Wi[0]=Math.floor(255*e[0]),Wi[1]=Math.floor(255*e[1]),Wi[2]=Math.floor(255*e[2]),Wi[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Wi[0]=0,Wi[1]=0,Wi[2]=0,Wi[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let i=0,s=e.length;i<s;i++)t.texImage2D(e[i],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Wi)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Wi);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t={}){const i=this.gl;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR);let s=!1;i.bindTexture(this.target,this.texture);const r=i.getParameter(i.UNPACK_FLIP_Y_WEBGL);i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY);const n=i.getParameter(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL);i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha);const A=i.getParameter(i.UNPACK_ALIGNMENT);i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment);const o=i.getParameter(i.UNPACK_COLORSPACE_CONVERSION_WEBGL);i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const a=ji(i,this.minFilter);i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,a),a!==i.NEAREST_MIPMAP_NEAREST&&a!==i.LINEAR_MIPMAP_NEAREST&&a!==i.NEAREST_MIPMAP_LINEAR&&a!==i.LINEAR_MIPMAP_LINEAR||(s=!0);const l=ji(i,this.magFilter);l&&i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,l);const c=ji(i,this.wrapS);c&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,c);const h=ji(i,this.wrapT);h&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,h);const u=ji(i,this.format,this.encoding),d=ji(i,this.type),f=Xi(i,this.internalFormat,u,d,this.encoding,!1);if(this.target===i.TEXTURE_CUBE_MAP){if(w.isArray(e)){const t=e,s=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,r=s.length;e<r;e++)i.texImage2D(s[e],0,f,u,d,t[e])}}else i.texImage2D(i.TEXTURE_2D,0,f,u,d,e);s&&i.generateMipmap(this.target),i.bindTexture(this.target,null),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,r),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n),i.pixelStorei(i.UNPACK_ALIGNMENT,A),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,o)}setCompressedData({mipmaps:e,props:t={}}){const i=this.gl,s=e.length;void 0!==t.format&&(this.format=t.format),void 0!==t.internalFormat&&(this.internalFormat=t.internalFormat),void 0!==t.encoding&&(this.encoding=t.encoding),void 0!==t.type&&(this.type=t.type),void 0!==t.flipY&&(this.flipY=t.flipY),void 0!==t.premultiplyAlpha&&(this.premultiplyAlpha=t.premultiplyAlpha),void 0!==t.unpackAlignment&&(this.unpackAlignment=t.unpackAlignment),void 0!==t.minFilter&&(this.minFilter=t.minFilter),void 0!==t.magFilter&&(this.magFilter=t.magFilter),void 0!==t.wrapS&&(this.wrapS=t.wrapS),void 0!==t.wrapT&&(this.wrapT=t.wrapT),void 0!==t.wrapR&&(this.wrapR=t.wrapR),i.activeTexture(i.TEXTURE0+0),i.bindTexture(this.target,this.texture);let r=e.length>1;i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,this.flipY),i.pixelStorei(i.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this.premultiplyAlpha),i.pixelStorei(i.UNPACK_ALIGNMENT,this.unpackAlignment),i.pixelStorei(i.UNPACK_COLORSPACE_CONVERSION_WEBGL,i.NONE);const n=ji(i,this.wrapS);n&&i.texParameteri(this.target,i.TEXTURE_WRAP_S,n);const A=ji(i,this.wrapT);if(A&&i.texParameteri(this.target,i.TEXTURE_WRAP_T,A),this.type===i.TEXTURE_3D||this.type===i.TEXTURE_2D_ARRAY){const e=ji(i,this.wrapR);e&&i.texParameteri(this.target,i.TEXTURE_WRAP_R,e),i.texParameteri(this.type,i.TEXTURE_WRAP_R,e)}r?(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,Ki(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,Ki(i,this.magFilter))):(i.texParameteri(this.target,i.TEXTURE_MIN_FILTER,ji(i,this.minFilter)),i.texParameteri(this.target,i.TEXTURE_MAG_FILTER,ji(i,this.magFilter)));const o=ji(i,this.format,this.encoding),a=ji(i,this.type),l=Xi(i,this.internalFormat,o,a,this.encoding,!1);i.texStorage2D(i.TEXTURE_2D,s,l,e[0].width,e[0].height);for(let t=0,s=e.length;t<s;t++){const s=e[t];1023!==this.format?null!==o?i.compressedTexSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,o,s.data):console.warn("Attempt to load unsupported compressed texture format in .setCompressedData()"):i.texSubImage2D(i.TEXTURE_2D,t,0,0,s.width,s.height,o,a,s.data)}i.bindTexture(this.target,null)}setProps(e){const t=this.gl;t.bindTexture(this.target,this.texture),this._uploadProps(e),t.bindTexture(this.target,null)}_uploadProps(e){const t=this.gl;if(void 0!==e.format&&(this.format=e.format),void 0!==e.internalFormat&&(this.internalFormat=e.internalFormat),void 0!==e.encoding&&(this.encoding=e.encoding),void 0!==e.type&&(this.type=e.type),void 0!==e.minFilter){const i=ji(t,e.minFilter);i&&(this.minFilter=e.minFilter,t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,i),i!==t.NEAREST_MIPMAP_NEAREST&&i!==t.LINEAR_MIPMAP_NEAREST&&i!==t.NEAREST_MIPMAP_LINEAR&&i!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(void 0!==e.magFilter){const i=ji(t,e.magFilter);i&&(this.magFilter=e.magFilter,t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,i))}if(void 0!==e.wrapS){const i=ji(t,e.wrapS);i&&(this.wrapS=e.wrapS,t.texParameteri(this.target,t.TEXTURE_WRAP_S,i))}if(void 0!==e.wrapT){const i=ji(t,e.wrapT);i&&(this.wrapT=e.wrapT,t.texParameteri(this.target,t.TEXTURE_WRAP_T,i))}}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function Xi(e,t,i,s,r,n=!1){if(null!==t){if(void 0!==e[t])return e[t];console.warn("Attempt to use non-existing WebGL internal format '"+t+"'")}let A=i;return i===e.RED&&(s===e.FLOAT&&(A=e.R32F),s===e.HALF_FLOAT&&(A=e.R16F),s===e.UNSIGNED_BYTE&&(A=e.R8)),i===e.RG&&(s===e.FLOAT&&(A=e.RG32F),s===e.HALF_FLOAT&&(A=e.RG16F),s===e.UNSIGNED_BYTE&&(A=e.RG8)),i===e.RGBA&&(s===e.FLOAT&&(A=e.RGBA32F),s===e.HALF_FLOAT&&(A=e.RGBA16F),s===e.UNSIGNED_BYTE&&(A=3001===r&&!1===n?e.SRGB8_ALPHA8:e.RGBA8),s===e.UNSIGNED_SHORT_4_4_4_4&&(A=e.RGBA4),s===e.UNSIGNED_SHORT_5_5_5_1&&(A=e.RGB5_A1)),A!==e.R16F&&A!==e.R32F&&A!==e.RG16F&&A!==e.RG32F&&A!==e.RGBA16F&&A!==e.RGBA32F||Gi(e,"EXT_color_buffer_float"),A}function Ki(e,t){return 1003===t||1004===t||1005===t?e.NEAREST:e.LINEAR}function Zi(e){if(!Ji(e.width)||!Ji(e.height)){const t=document.createElement("canvas");t.width=Yi(e.width),t.height=Yi(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Ji(e){return 0==(e&e-1)}function Yi(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class $i extends D{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new oe({texture:new zi({gl:this.scene.canvas.gl}),matrix:d.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=d.vec2([0,0]),this._scale=d.vec2([1,1]),this._rotate=d.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),m.memory.textures++}_checkMinFilter(e){return 1006!==(e=e||1008)&&1007!==e&&1008!==e&&1005!==e&&1004!==e&&(this.error("Unsupported value for 'minFilter' - supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, NearestMipMapLinearFilter and LinearMipMapLinearFilter. Defaulting to LinearMipMapLinearFilter."),e=1008),e}_checkMagFilter(e){return 1006!==(e=e||1006)&&1003!==e&&(this.error("Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),e=1006),e}_checkWrapS(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkWrapT(e){return 1001!==(e=e||1e3)&&1002!==e&&1e3!==e&&(this.error("Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),e=1e3),e}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=d.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=d.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?d.mulMat4(t,i):i),0!==this._rotate&&(i=d.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?d.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=Zi(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=Zi(i),t._state.texture.setImage(i,t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),m.memory.textures--}}const qi=d.vec3(),es=d.vec3();d.vec3();const ts=d.vec3([0,-1,0]),is=d.vec4([0,0,0,1]);class ss extends D{constructor(e,t={}){super(e,t),this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new $i(this),this._plane=new Qi(this,{geometry:new be(this,Te({center:[0,0,0],xSize:1,zSize:1,xSegments:10,zSegments:10})),material:new Ni(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0}),clippable:t.clippable}),this._grid=new Qi(this,{geometry:new be(this,Ie({size:1,divisions:10})),material:new Ni(this,{diffuse:[0,0,0],ambient:[0,0,0],emissive:[.2,.8,.2]}),position:[0,.001,0],clippable:t.clippable}),this._node=new Ke(this,{rotation:[0,0,0],position:[0,0,0],scale:[1,1,1],clippable:!1,children:[this._plane,this._grid]}),this._gridVisible=!1,this.visible=!0,this.gridVisible=t.gridVisible,this.position=t.position,this.rotation=t.rotation,this.dir=t.dir,this.size=t.size,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,t.image?this.image=t.image:this.src=t.src}set visible(e){this._plane.visible=e,this._grid.visible=this._gridVisible&&e}get visible(){return this._plane.visible}set gridVisible(e){e=!1!==e,this._gridVisible=e,this._grid.visible=this._gridVisible&&this.visible}get gridVisible(){return this._gridVisible}set image(e){this._image=e,this._image&&(this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set position(e){this._pos.set(e||[0,0,0]),Ye(this._pos,this._origin,this._rtcPos),this._node.origin=this._origin,this._node.position=this._rtcPos}get position(){return this._pos}set rotation(e){this._node.rotation=e}get rotation(){return this._node.rotation}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set dir(e){if(this._dir.set(e||[0,0,-1]),e){const t=this.scene.center,i=[-this._dir[0],-this._dir[1],-this._dir[2]];d.subVec3(t,this.position,qi);const s=-d.dotVec3(i,qi);d.normalizeVec3(i),d.mulVec3Scalar(i,s,es),d.vec3PairToQuaternion(ts,e,is),this._node.quaternion=is}}get dir(){return this._dir}set collidable(e){this._node.collidable=!1!==e}get collidable(){return this._node.collidable}set clippable(e){this._node.clippable=!1!==e}get clippable(){return this._node.clippable}set pickable(e){this._node.pickable=!1!==e}get pickable(){return this._node.pickable}set opacity(e){this._node.opacity=e}get opacity(){return this._node.opacity}destroy(){super.destroy()}_updatePlaneSizeFromImage(){const e=this._size,t=this._imageSize[0],i=this._imageSize[1];if(t>i){const s=i/t;this._node.scale=[e,1,e*s]}else{const s=t/i;this._node.scale=[e*s,1,e]}}}class rs extends Vi{get type(){return"LambertMaterial"}constructor(e,t={}){super(e,t),this._state=new oe({type:"LambertMaterial",ambient:d.vec3([1,1,1]),color:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),alpha:null,alphaMode:0,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:"/lam;"}),this.ambient=t.ambient,this.color=t.color,this.emissive=t.emissive,this.alpha=t.alpha,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this.backfaces=t.backfaces,this.frontface=t.frontface}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set color(e){let t=this._state.color;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.color=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get color(){return this._state.color}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this._state.alphaMode=e<1?2:0,this.glRedraw())}get alpha(){return this._state.alpha}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}const ns={opaque:0,mask:1,blend:2},As=["opaque","mask","blend"];class os extends Vi{get type(){return"MetallicMaterial"}constructor(e,t={}){super(e,t),this._state=new oe({type:"MetallicMaterial",baseColor:d.vec4([1,1,1]),emissive:d.vec4([0,0,0]),metallic:null,roughness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.baseColor=t.baseColor,this.metallic=t.metallic,this.roughness=t.roughness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.baseColorMap&&(this._baseColorMap=this._checkComponent("Texture",t.baseColorMap)),t.metallicMap&&(this._metallicMap=this._checkComponent("Texture",t.metallicMap)),t.roughnessMap&&(this._roughnessMap=this._checkComponent("Texture",t.roughnessMap)),t.metallicRoughnessMap&&(this._metallicRoughnessMap=this._checkComponent("Texture",t.metallicRoughnessMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/met"];this._baseColorMap&&(t.push("/bm"),this._baseColorMap._state.hasMatrix&&t.push("/mat"),t.push("/"+this._baseColorMap._state.encoding)),this._metallicMap&&(t.push("/mm"),this._metallicMap._state.hasMatrix&&t.push("/mat")),this._roughnessMap&&(t.push("/rm"),this._roughnessMap._state.hasMatrix&&t.push("/mat")),this._metallicRoughnessMap&&(t.push("/mrm"),this._metallicRoughnessMap._state.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap._state.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap._state.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/am"),this._alphaMap._state.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap._state.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set baseColor(e){let t=this._state.baseColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.baseColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get baseColor(){return this._state.baseColor}get baseColorMap(){return this._baseColorMap}set metallic(e){e=null!=e?e:1,this._state.metallic!==e&&(this._state.metallic=e,this.glRedraw())}get metallic(){return this._state.metallic}get metallicMap(){return this._attached.metallicMap}set roughness(e){e=null!=e?e:1,this._state.roughness!==e&&(this._state.roughness=e,this.glRedraw())}get roughness(){return this._state.roughness}get roughnessMap(){return this._attached.roughnessMap}get metallicRoughnessMap(){return this._attached.metallicRoughnessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._attached.emissiveMap}get occlusionMap(){return this._attached.occlusionMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._attached.alphaMap}get normalMap(){return this._attached.normalMap}set alphaMode(e){let t=ns[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return As[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const as={opaque:0,mask:1,blend:2},ls=["opaque","mask","blend"];class cs extends Vi{get type(){return"SpecularMaterial"}constructor(e,t={}){super(e,t),this._state=new oe({type:"SpecularMaterial",diffuse:d.vec3([1,1,1]),emissive:d.vec3([0,0,0]),specular:d.vec3([1,1,1]),glossiness:null,specularF0:null,alpha:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.diffuse=t.diffuse,this.specular=t.specular,this.glossiness=t.glossiness,this.specularF0=t.specularF0,this.emissive=t.emissive,this.alpha=t.alpha,t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.glossinessMap&&(this._glossinessMap=this._checkComponent("Texture",t.glossinessMap)),t.specularGlossinessMap&&(this._specularGlossinessMap=this._checkComponent("Texture",t.specularGlossinessMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,this._makeHash()}_makeHash(){const e=this._state,t=["/spe"];this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat")),this._glossinessMap&&(t.push("/gm"),this._glossinessMap.hasMatrix&&t.push("/mat")),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._specularGlossinessMap&&(t.push("/sgm"),this._specularGlossinessMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),t.push(";"),e.hash=t.join("")}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}get diffuseMap(){return this._diffuseMap}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}get specularMap(){return this._specularMap}get specularGlossinessMap(){return this._specularGlossinessMap}set glossiness(e){e=null!=e?e:1,this._state.glossiness!==e&&(this._state.glossiness=e,this.glRedraw())}get glossiness(){return this._state.glossiness}get glossinessMap(){return this._glossinessMap}set specularF0(e){e=null!=e?e:0,this._state.specularF0!==e&&(this._state.specularF0=e,this.glRedraw())}get specularF0(){return this._state.specularF0}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}get emissiveMap(){return this._emissiveMap}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}get alphaMap(){return this._alphaMap}get normalMap(){return this._normalMap}get occlusionMap(){return this._occlusionMap}set alphaMode(e){let t=as[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return ls[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}destroy(){super.destroy(),this._state.destroy()}}const hs={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class us extends Vi{get type(){return"EmphasisMaterial"}get presets(){return hs}constructor(e,t={}){super(e,t),this._state=new oe({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0,glowThrough:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces),void 0!==t.glowThrough&&(this.glowThrough=t.glowThrough)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces,this.glowThrough=t.glowThrough)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set glowThrough(e){e=!1!==e,this._state.glowThrough!==e&&(this._state.glowThrough=e,this.glRedraw())}get glowThrough(){return this._state.glowThrough}set preset(e){if(console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),e=e||"default",this._preset===e)return;const t=hs[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.glowThrough=t.glowThrough,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(hs).join(", "))}get preset(){return console.warn("EmphasisMaterial.preset is deprecated and will be removed in future versions."),this._preset}destroy(){super.destroy(),this._state.destroy()}}const ds={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class fs extends Vi{get type(){return"EdgeMaterial"}get presets(){return ds}constructor(e,t={}){super(e,t),this._state=new oe({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=ds[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ds).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}class ps extends D{get type(){return"Fresnel"}constructor(e,t={}){super(e,t),this._state=new oe({edgeColor:d.vec3([0,0,0]),centerColor:d.vec3([1,1,1]),edgeBias:0,centerBias:1,power:1}),this.edgeColor=t.edgeColor,this.centerColor=t.centerColor,this.edgeBias=t.edgeBias,this.centerBias=t.centerBias,this.power=t.power}set edgeColor(e){this._state.edgeColor.set(e||[0,0,0]),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set centerColor(e){this._state.centerColor.set(e||[1,1,1]),this.glRedraw()}get centerColor(){return this._state.centerColor}set edgeBias(e){this._state.edgeBias=e||0,this.glRedraw()}get edgeBias(){return this._state.edgeBias}set centerBias(e){this._state.centerBias=null!=e?e:1,this.glRedraw()}get centerBias(){return this._state.centerBias}set power(e){this._state.power=null!=e?e:1,this.glRedraw()}get power(){return this._state.power}destroy(){super.destroy(),this._state.destroy()}}class gs extends D{constructor(e,t={}){super(e,t),this._type=t.type||(t.src?t.src.split(".").pop():null)||"jpg",this._pos=d.vec3(t.pos||[0,0,0]),this._up=d.vec3(t.up||[0,1,0]),this._normal=d.vec3(t.normal||[0,0,1]),this._height=t.height||1,this._origin=d.vec3(),this._rtcPos=d.vec3(),this._imageSize=d.vec2(),this._texture=new $i(this,{flipY:!0}),this._image=new Image,"jpg"!==this._type&&"png"!==this._type&&(this.error('Unsupported type - defaulting to "jpg"'),this._type="jpg"),this._node=new Ke(this,{matrix:d.inverseMat4(d.lookAtMat4v(this._pos,d.subVec3(this._pos,this._normal,d.mat4()),this._up,d.mat4())),children:[this._bitmapMesh=new Qi(this,{scale:[1,1,1],rotation:[-90,0,0],collidable:t.collidable,pickable:t.pickable,opacity:t.opacity,clippable:t.clippable,geometry:new be(this,Te({center:[0,0,0],xSize:1,zSize:1,xSegments:2,zSegments:2})),material:new Ni(this,{diffuse:[0,0,0],ambient:[0,0,0],specular:[0,0,0],diffuseMap:this._texture,emissiveMap:this._texture,backfaces:!0})})]}),t.image?this.image=t.image:t.src?this.src=t.src:t.imageData&&(this.imageData=t.imageData),this.scene._bitmapCreated(this)}set visible(e){this._bitmapMesh.visible=e}get visible(){return this._bitmapMesh.visible}set image(e){this._image=e,this._image&&(this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale())}get image(){return this._image}set src(e){if(e){this._image.onload=()=>{this._texture.image=this._image,this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updateBitmapMeshScale()},this._image.src=e;switch(e.split(".").pop()){case"jpeg":case"jpg":this._type="jpg";break;case"png":this._type="png"}}}get src(){return this._image.src}set imageData(e){this._image.onload=()=>{this._texture.image=image,this._imageSize[0]=image.width,this._imageSize[1]=image.height,this._updateBitmapMeshScale()},this._image.src=e}get imageData(){const e=document.createElement("canvas"),t=e.getContext("2d");return e.width=this._image.width,e.height=this._image.height,t.drawImage(this._image,0,0),e.toDataURL("jpg"===this._type?"image/jpeg":"image/png")}set type(e){"png"===(e=e||"jpg")&&"jpg"===e||(this.error("Unsupported value for `type` - supported types are `jpg` and `png` - defaulting to `jpg`"),e="jpg"),this._type=e}get type(){return this._type}get pos(){return this._pos}get normal(){return this._normal}get up(){return this._up}set height(e){this._height=null==e?1:e,this._image&&this._updateBitmapMeshScale()}get height(){return this._height}set collidable(e){this._bitmapMesh.collidable=!1!==e}get collidable(){return this._bitmapMesh.collidable}set clippable(e){this._bitmapMesh.clippable=!1!==e}get clippable(){return this._bitmapMesh.clippable}set pickable(e){this._bitmapMesh.pickable=!1!==e}get pickable(){return this._bitmapMesh.pickable}set opacity(e){this._bitmapMesh.opacity=e}get opacity(){return this._bitmapMesh.opacity}destroy(){super.destroy(),this.scene._bitmapDestroyed(this)}_updateBitmapMeshScale(){const e=this._imageSize[1]/this._imageSize[0];this._bitmapMesh.scale=[this._height/e,1,this._height]}}const ms=(e,t)=>{const i=[];let s=[];function r(e,i){let s,r;for(let n=0;n<3;n++)if(s=t[3*e+n],r=t[3*i+n],s!==r)return r-s;return 0}let n=e.slice().sort(r),A=null;for(let e=0,t=n.length;e<t;e++)0!==e&&0===r(n[e],n[e-1])||(A=n[e]),i[n[e]]=A;for(let t=0,r=e.length;t<r;t+=3){const r=i[e[t]],n=i[e[t+1]],A=i[e[t+2]];let o=r,a=n,l=A;if(r>n&&r>A?n>A?(o=r,a=n,l=A):(o=r,a=A,l=n):n>r&&n>A?r>A?(o=n,a=r,l=A):(o=n,a=A,l=r):A>r&&A>n&&(r>n?(o=A,a=r,l=n):(o=A,a=n,l=r)),s[t+0]=[o,a],s[t+1]=[a,l],o>l){const e=l;l=o,o=e}s[t+2]=[l,o]}function o(e,t){let i,s;for(let r=0;r<2;r++)if(i=e[r],s=t[r],s!==i)return s-i;return 0}s=s.slice(0,e.length),s.sort(o);let a=0;for(let e=0;e<s.length;e++)if(0===e||0!==o(s[e],s[e-1])){if(0!==e&&2!==a)return!1;a=1}else a++;return!(s.length>0&&2!==a)},_s=d.vec3(),bs=d.vec3(),ys=d.vec3();class ws{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0,this.primitive=null}setPrimitive(e){this.primitive=e}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get volume(){const e=this.vertices,t=this.indices;if("solid"!==this.primitive&&"surface"!==this.primitive&&"triangles"!==this.primitive)return-1;if("solid"!==this.primitive&&!ms(t,e))return-1;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],n=3*t[s+1],A=3*t[s+2];_s[0]=e[r],_s[1]=e[r+1],_s[2]=e[r+2],bs[0]=e[n],bs[1]=e[n+1],bs[2]=e[n+2],ys[0]=e[A],ys[1]=e[A+1],ys[2]=e[A+2],d.cross3Vec3(_s,bs,_s),i+=d.dotVec3(_s,ys)}return i/6}}const vs=new ws,Bs=d.vec3(),Cs=d.vec3(),Ms=d.vec3(),Es=d.vec3(),Fs=d.vec3(),Us=d.vec3();class xs{constructor(){this.vertices=[],this.indices=[],this.reset()}reset(){this.lenVertices=0,this.lenIndices=0}addVertex(e){this.vertices[this.lenVertices++]=e[0],this.vertices[this.lenVertices++]=e[1],this.vertices[this.lenVertices++]=e[2]}addIndex(e){this.indices[this.lenIndices++]=e}get surfaceArea(){const e=this.vertices,t=this.indices;let i=0;for(let s=0;s<this.lenIndices;s+=3){const r=3*t[s],n=3*t[s+1],A=3*t[s+2];Bs[0]=e[r],Bs[1]=e[r+1],Bs[2]=e[r+2],Cs[0]=e[n],Cs[1]=e[n+1],Cs[2]=e[n+2],Ms[0]=e[A],Ms[1]=e[A+1],Ms[2]=e[A+2],d.subVec3(Bs,Cs,Es),d.subVec3(Ms,Cs,Fs),i+=.5*d.lenVec3(d.cross3Vec3(Es,Fs,Us))}return i}}const Is=new xs,Ts=d.OBB3(),Ps=d.OBB3(),Ss=d.OBB3();class Ds{constructor(e,t,i,s,r,n,A=null,o=0){this.model=e,this.object=null,this.parent=null,this.transform=r,this.textureSet=n,this._matrixDirty=!1,this._matrixUpdateScheduled=!1,this.id=t,this.obb=null,this._aabbLocal=null,this._aabbWorld=d.AABB3(),this._aabbWorldDirty=!1,this.layer=A,this.portionId=o,this._color=new Uint8Array([i[0],i[1],i[2],s]),this._colorize=new Uint8Array([i[0],i[1],i[2],s]),this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.origin=null,this.entity=null,r&&r._addMesh(this),this._volume=null,this._surfaceArea=null}_sceneModelDirty(){this._aabbWorldDirty=!0,this.layer.aabbChanged()}_transformDirty(){this._matrixDirty||this._matrixUpdateScheduled||(this.model._meshMatrixDirty(this),this._matrixDirty=!0,this._matrixUpdateScheduled=!0),this._aabbWorldDirty=!0,this.layer.aabbChanged(),this.entity&&this.entity._transformDirty()}_updateMatrix(){this.transform&&this._matrixDirty&&this.layer.setMatrix(this.portionId,this.transform.worldMatrix),this._matrixDirty=!1,this._matrixUpdateScheduled=!1}_finalize(e){this.layer.initFlags(this.portionId,e,this._transparent)}_finalize2(){this.layer.flushInitFlags&&this.layer.flushInitFlags()}_setVisible(e){this.layer.setVisible(this.portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this.layer.setColor(this.portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this.layer.setColor(this.portionId,this._colorize,false),this._colorizing=!0):(this.layer.setColor(this.portionId,this._color,false),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this.layer.setColor(this.portionId,this._colorize):this.layer.setColor(this.portionId,this._color),s&&this.layer.setTransparent(this.portionId,t,i)}_setOffset(e){this.layer.setOffset(this.portionId,e)}_setHighlighted(e){this.layer.setHighlighted(this.portionId,e,this._transparent)}_setXRayed(e){this.layer.setXRayed(this.portionId,e,this._transparent)}_setSelected(e){this.layer.setSelected(this.portionId,e,this._transparent)}_setEdges(e){this.layer.setEdges(this.portionId,e,this._transparent)}_setClippable(e){this.layer.setClippable(this.portionId,e,this._transparent)}_setCollidable(e){this.layer.setCollidable(this.portionId,e)}_setPickable(e){this.layer.setPickable(this.portionId,e,this._transparent)}_setCulled(e){this.layer.setCulled(this.portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}precisionRayPickSurface(e,t,i,s){return this.layer.precisionRayPickSurface(this.portionId,e,t,i,s)}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}getEachVertex(e){this.layer.getEachVertex&&this.layer.getEachVertex(this.portionId,e)}getEachIndex(e){this.layer.getEachIndex&&this.layer.getEachIndex(this.portionId,e)}isSolid(){return this.layer.solid}get volume(){if(null!==this._volume)return this._volume;switch(this.layer.primitive){case"solid":case"surface":case"triangles":vs.reset(),vs.setPrimitive(this.layer.primitive),this.getEachVertex((e=>{vs.addVertex(e)})),this.getEachIndex((e=>{vs.addIndex(e)})),this._volume=vs.volume;break;default:this._volume=0}return this._volume}get surfaceArea(){if(null!==this._surfaceArea)return this._surfaceArea;switch(this.layer.primitive){case"solid":case"surface":case"triangles":Is.reset(),this.getEachVertex((e=>{Is.addVertex(e)})),this.getEachIndex((e=>{Is.addIndex(e)})),this._surfaceArea=Is.surfaceArea;break;default:this._surfaceArea=0}return this._surfaceArea}set aabb(e){if(this._aabbLocal=e,this.origin){this._aabbLocal=e.slice(0);const t=this.origin;this._aabbLocal[0]+=t[0],this._aabbLocal[1]+=t[1],this._aabbLocal[2]+=t[2],this._aabbLocal[3]+=t[0],this._aabbLocal[4]+=t[1],this._aabbLocal[5]+=t[2]}}get aabb(){return this._aabbWorldDirty&&(d.AABB3ToOBB3(this._aabbLocal,Ts),this.transform?(d.transformOBB3(this.transform.worldMatrix,Ts,Ps),d.transformOBB3(this.model.worldMatrix,Ps,Ss),d.OBB3ToAABB3(Ss,this._aabbWorld)):(d.transformOBB3(this.model.worldMatrix,Ts,Ps),d.OBB3ToAABB3(Ps,this._aabbWorld)),this._aabbWorldDirty=!1),this._aabbWorld}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const ks=1,Qs=4,Rs=8,Os=16,Vs=32,Ls=256,Hs=512,Ns=1024,Gs=2048,js=function(e,t,i,s){const r=s&&e.createUniform("vec4","edgeColor",((e,t)=>e(t.legacyFrameCtx.programColor))),n=t.attributes.color,A=!s&&e.createVarying("vec4","vColor",(()=>`vec4(${n}.rgb * 0.5, ${n}.a)`)),o=e.createOutput("vec4","outColor");return{programName:s?"Edges":"EdgesColor",getLogDepth:i&&(e=>e),renderPassFlag:2,appendFragmentOutputs:e=>e.push(`${o} = ${r||A};`)}},Ws=function(e,t){const i=e.createOutput("vec4","outColor");return{programName:"Occlusion",getLogDepth:!1,renderPassFlag:0,appendFragmentOutputs:e=>e.push(`${i} = vec4(0.0, 0.0, 1.0, 1.0);`)}},zs=function(e,t,i,s){const r=e.createUniform("vec4","silhouetteColor",((e,t)=>e(t.legacyFrameCtx.programColor))),n=e.createVarying("float","vAlpha",(()=>`${t.attributes.color}.a`)),A=e.createOutput("vec4","outColor");return{programName:"Silhouette",getLogDepth:i&&(e=>e),renderPassFlag:1,appendFragmentOutputs:(e,t,i,o)=>{e.push(`${A} = ${s?r:o(`vec4(${r}.rgb, min(${r}.a, ${n}))`)};`)}}},Xs=d.vec2(),Ks=d.vec3(),Zs=d.vec4(),Js=d.mat4(),Ys=d.vec3([0,0,0]),$s=0,qs=1,er=2,tr=3,ir=4,sr=5,rr=6,nr=7,Ar=8,or=9,ar=10,lr=11,cr=e=>[d.safeInv(e[0]),d.safeInv(e[1]),d.safeInv(e[2])],hr=(e,t,i,s,r)=>{const n=!!(e&ks),A=!!(e&Ls),o=!!(e&Hs),a=!!(e&Ns),l=!!(e&Gs),c=!!(e&Rs),h=!!(e&Qs);let u,d;u=!n||h||A||o&&!s.highlightMaterial.glowThrough||a&&!s.selectedMaterial.glowThrough?$s:t?er:qs,d=!n||h?$s:a?ir:o?tr:A?sr:$s;let f=0;f=i&&n&&!h?a?or:o?Ar:A?ar:l?t?nr:rr:$s:$s;const p=n&&!h&&c?lr:$s;r[0]=u,r[1]=d,r[2]=f,r[3]=p},ur=function(){const e={};return function(t,i,s,r,n,A,o,a){const l=[i,"points"===s||"lines"===s?s:"triangles",!!r,!!n,!!A,!!o].join(":");l in e||(e[l]={});const c=e[l],h=t.id;if(!(h in c)){const e=t.canvas.gl,l=function(r,n,A){const o=function(){const A=mi(),o=A.programVariables,l=a(o,n);return r(o,l.geometryParameters,(function(r,a){const c=t.pointsMaterial,h="points"===s&&!n,u=()=>[t._sectionPlanesState.getHash()].concat(h?[c.hash]:[]).concat(r.getHash?r.getHash():[]).join(";"),f=u(),p=()=>f===u(),g=l.geometryParameters,m=r.incrementDrawState,_=r.isShadowProgram,b=g.attributes,y=b.position.world,w="clipPos",[v,B]=A.buildProgram(e,i+" "+s+" "+r.programName,{appendFragmentOutputs:r.appendFragmentOutputs,cleanerEdges:r.cleanerEdges,clipPos:w,clippableTest:function(){const e=o.createVarying("float","vClippable",(()=>`${b.clippable} ? 1.0 : 0.0`),"flat");return()=>`${e} > 0.0`}(),clippingCaps:r.clippingCaps,crossSections:t.crossSections,discardPoints:h&&c.roundPoints,getGammaFactor:t.gammaOutput&&(()=>t.gammaFactor),getLogDepth:r.getLogDepth,getPointSize:function(){const e=[];if(h){const t=o.createUniform("float","pointSize",(e=>e(c.pointSize)));if(c.perspectivePoints){const i=o.createUniform("float","nearPlaneHeight",((e,t)=>e(t.legacyFrameCtx.nearPlaneHeight))),s=`${Math.floor(c.minPerspectivePointSize)}.0`,r=`${Math.floor(c.maxPerspectivePointSize)}.0`;e.push(`clamp((${i} * ${t}) / gl_Position.w, ${s}, ${r})`)}else e.push(t)}else n&&n.vertices&&e.push("1.0");return r.incPointSizeBy10&&"points"===s&&e.push("10.0"),e.length>0&&(()=>e.join(" + "))}(),getVertexData:()=>{const e=b.color,t=b.flags[r.renderPassFlag],i=o.createUniform("int","renderPass",((e,t)=>e(t.renderPass))),n=[`if (${_?`(${t} <= 0) || (${e}.a < 1.0)`:`${t} != ${i}`}) {`," gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"," return;","}"].concat(l.dontCullOnAlphaZero||r.dontCullOnAlphaZero?[]:[`if (${e}.a == 0.0) {`," gl_Position = vec4(0.0, 0.0, 0.0, 1.0);"," return;","}"]).concat(r.filterIntensityRange&&"points"===s&&c.filterIntensity?function(){const t=o.createUniform("vec2","intensityRange",(e=>{Xs[0]=c.minIntensity,Xs[1]=c.maxIntensity,e(Xs)}));return[`if ((${e}.a < ${t}[0]) || (${e}.a > ${t}[1])) {`," gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"," return;","}"]}():[]),A=[];l.ensureColorAndFlagAvailable&&l.ensureColorAndFlagAvailable(A),n.forEach((e=>A.push(e))),l.appendVertexData(A);const a=g.attributes.position.view;return A.push(`vec4 ${a} = ${g.viewMatrix} * ${y};`),A.push(`vec4 clipPos = ${g.projMatrix} * ${a};`),A},projMatrix:g.projMatrix,sectionPlanesState:t._sectionPlanesState,testPerspectiveForGl_FragDepth:"points"!==s&&"lines"!==s||n,usePickClipPos:a,worldPositionAttribute:y});return B?(console.error(B),{getValid:p,destroy:()=>{},drawLayer:(e,t,i)=>{}}):{getValid:p,destroy:()=>v.destroy(),drawLayer:(e,t,i)=>{e.lastProgramId!==v.id&&(e.lastProgramId=v.id,v.bind());const s=t.origin,r=t.model,A=e.viewParams,o=Ks;d.transformPoint3(r.matrix,s,o);const a=A.viewMatrix,c=A.projMatrix;e.snapPickOrigin&&(e.snapPickOrigin[0]=o[0],e.snapPickOrigin[1]=o[1],e.snapPickOrigin[2]=o[2]);const h={legacyFrameCtx:e,layerTextureSet:t.layerTextureSet,mesh:{layerIndex:t.layerIndex,origin:o,renderFlags:{sectionPlanesActivePerLayer:r.renderFlags.sectionPlanesActivePerLayer}},renderPass:i,view:{eye:A.eye,far:A.far,projMatrix:c,viewMatrix:d.compareVec3(o,Ys)?a:Je(a,o,Js),viewNormalMatrix:A.viewNormalMatrix}};v.inputSetters.setUniforms(e,h),t.drawCalls[n?n.vertices?"drawVertices":"drawEdges":"drawSurface"](v.inputSetters.attributesHash,l.layerTypeInputs,{projMatrix:c,viewMatrix:d.compareVec3(o,Ys)?a:Je(a,o,Js),viewNormalMatrix:A.viewNormalMatrix,eye:A.eye}),m&&e.drawElements++}}}))};let l=A&&o();return{drawLayer:(e,t,i)=>{l||(l=o()),l.drawLayer(e,t,i)},revalidate:e=>{!l||!e&&l.getValid()||(l.destroy(),l=A&&o())}}},u=(e,t)=>l(e,t,!0),f=(e,t)=>l(e,t,!1),p=(e,i,r,n)=>function(e,t,i,s,r,n){const A=e.createVarying("vec4","vColor",(()=>{const e=t.attributes,i="points"===n?`vec4(${e.color}.rgb, 1.0)`:`${e.color}`;return s?`vec4(${[s.getAmbientColor()].concat(s.directionalLights.map((i=>`max(dot(${e.normal.view}, ${i.getDirection(t.viewMatrix,e.position.view)}), 0.0) * ${i.getColor()}`))).join(" + ")}, 1) * ${i}`:i})),o=e.createOutput("vec4","outColor");return{programName:"Color",getHash:()=>[s?s.getHash():"-",r?"sao":"nosao"],cleanerEdges:!0,getLogDepth:i&&(e=>"points"!==n&&"lines"!==n?`${e} + length(vec2(dFdx(${e}), dFdy(${e})))`:e),renderPassFlag:0,appendFragmentOutputs:(e,t,i,s)=>{"points"===n||"lines"===n?e.push(`${o} = ${A};`):(e.push(`vec4 fragColor = ${s(A)};`),e.push(`${o} = ${r?`vec4(fragColor.rgb * ${r.getAmbient(i)}, fragColor.a)`:"fragColor"};`))},filterIntensityRange:!0,incrementDrawState:!0}}(e,i,t.logarithmicDepthBufferEnabled,r,n,s),g=(e,i,s)=>s(function(e,t,i){const s=e.createUniform("float","far",((e,t)=>e(t.legacyFrameCtx.viewParams.far))),r=e.createUniform("float","near",((e,t)=>e(t.legacyFrameCtx.viewParams.near))),n=e.createVarying("vec3","vViewPosition",(()=>`${t.attributes.position.view}.xyz`)),A=e.createOutput("vec4","outPackedDepth"),o=e.createFragmentDefinition("packDepth",((e,t)=>{t.push(`vec4 ${e}(const in float depth) {`),t.push(" const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),t.push(" const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),t.push(" vec4 res = fract(depth * bitShift);"),t.push(" res -= res.xxyz * bitMask;"),t.push(" return res;"),t.push("}")}));return{programName:"PickDepth",getLogDepth:i&&(e=>e),renderPassFlag:3,incPointSizeBy10:!0,appendFragmentOutputs:e=>{e.push(`float zNormalizedDepth = abs((${r} + ${n}.z) / (${s} - ${r}));`),e.push(`${A} = ${o}(zNormalizedDepth);`)}}}(e,i,t.logarithmicDepthBufferEnabled),!0),m=(e,i,s)=>s(function(e,t,i){const s=e.createVarying("vec4","vPickColor",(()=>`${t.attributes.pickColor} / 255.0`)),r=e.createOutput("vec4","outPickColor");return{programName:"PickMesh",getLogDepth:i&&(e=>e),renderPassFlag:3,incPointSizeBy10:!0,dontCullOnAlphaZero:!0,appendFragmentOutputs:e=>e.push(`${r} = ${s};`)}}(e,i,t.logarithmicDepthBufferEnabled),!0),_=(e,i,s,r)=>s(function(e,t,i,s){const r=e.createVarying("vec3","vWorldPosition",(()=>`${t.attributes.position.world}.xyz`)),n=e.createVarying("vec3","vWorldNormal",(()=>t.attributes.normal.world)),A=e.createOutput("highp ivec4","outNormal");return{programName:s?"PickNormalsFlat":"PickNormals",getLogDepth:i&&(e=>e),renderPassFlag:3,appendFragmentOutputs:e=>{const t=s?`normalize(cross(dFdx(${r}), dFdy(${r})))`:n;e.push(`${A} = ivec4(${t} * float(${d.MAX_INT}), 1.0);`)}}}(e,i,t.logarithmicDepthBufferEnabled,r),!0),b=(e,t,i,s,r)=>i(function(e,t,i,s){const r=e.createUniform("int","layerNumber",((e,t)=>e(t.legacyFrameCtx.snapPickLayerParams.length))),n=e.createUniform("vec3","coordinateScaler",((e,t)=>e(t.legacyFrameCtx.snapPickCoordinateScale))),A=e.createVarying("vec3","vWorldPosition",(()=>`${t.attributes.position.world}.xyz`)),o=e.createVarying("vec4","vPickColor",(()=>t.attributes.pickColor),"flat"),a=e.createOutput("highp ivec4","outCoords",0),l=e.createOutput("highp ivec4","outNormal",1),c=e.createOutput("lowp uvec4","outPickColor",2);return{programName:i?"SnapInit":"Snap",getLogDepth:e=>i?`${e} + length(vec2(dFdx(${e}), dFdy(${e})))`:e,renderPassFlag:3,dontCullOnAlphaZero:!i,appendFragmentOutputs:e=>{e.push(`${a} = ivec4(${A} * ${n}.xyz, ${i?"-":""}${r});`),i&&(e.push(`${l} = ${s?"ivec4(1.0)":`ivec4(normalize(cross(dFdx(${A}), dFdy(${A}))) * float(${d.MAX_INT}), 1.0)`};`),e.push(`${c} = uvec4(${o});`))}}}(e,t,s,r),!0);c[h]="points"===s?{colorRenderers:{"sao-":{vertex:f(((e,t,i)=>i(p(e,t,null,null))))}},occlusionRenderer:f(((e,i,s)=>s(Ws(e,t.logarithmicDepthBufferEnabled)))),pickDepthRenderer:f(g),pickMeshRenderer:f(m),silhouetteRenderer:f(((e,i,s)=>s(zs(e,i,t.logarithmicDepthBufferEnabled,!0)))),snapInitRenderer:f(((e,t,i)=>b(e,t,i,!0,!0))),snapVertexRenderer:f(((e,t,i)=>b(e,t,i,!1,!0)),{vertices:!0})}:"lines"===s?{colorRenderers:{"sao-":{vertex:f(((e,t,i)=>i(p(e,t,null,null))))}},silhouetteRenderer:f(((e,i,s)=>s(zs(e,i,t.logarithmicDepthBufferEnabled,!0)))),snapInitRenderer:f(((e,t,i)=>b(e,t,i,!0,!1))),snapEdgeRenderer:f(((e,t,i)=>b(e,t,i,!1,!1)),{vertices:!1}),snapVertexRenderer:f(((e,t,i)=>b(e,t,i,!1,!1)),{vertices:!0})}:{colorRenderers:function(){const e=e=>_i(e,t._lightsState),i=e=>{const t=e.createUniform("vec4","uSAOParams",((e,t)=>e(t.legacyFrameCtx.saoParams))),i=bi(e,"sampler2D","uOcclusionTexture",3e3,((e,t)=>e(t.legacyFrameCtx.occlusionTexture)));return{getAmbient:e=>{const s=`${t}.w`;return`(smoothstep(${`${t}.z`}, 1.0, dot(${i(`${e}.xy / ${t}.xy`)}, (255. / 256.) / vec4(256. * 256. * 256., 256. * 256., 256., 1.))) * ${s})`}}},s=function(s){const r=(r,n,A)=>function(e,t,i,s,r,n,A){const o=bi(e,"sampler2D","uColorMap",3001,((e,t)=>{const i=t.layerTextureSet.colorTexture;i&&e(i.texture)})),a=n&&e.createUniform("float","materialAlphaCutoff",((e,t)=>e(t.layerTextureSet.alphaCutoff))),l=t.attributes,c=e.createVarying("vec3","vViewPosition",(()=>`${l.position.view}.xyz`)),h=e.createVarying("vec2","vUV",(()=>l.uv)),u=e.createVarying("vec4","vColor",(()=>l.color)),d=e.createOutput("vec4","outColor");return{programName:"ColorTexture",getHash:()=>[s.getHash(),r?"sao":"nosao",!!A,n?"alphaCutoffYes":"alphaCutoffNo"],getLogDepth:i.logarithmicDepthBufferEnabled&&(e=>e),renderPassFlag:0,appendFragmentOutputs:(e,i,n,A)=>{e.push(`vec3 viewNormal = normalize(cross(dFdx(${c}), dFdy(${c})));`),e.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),s.directionalLights.forEach((i=>{e.push(`reflectedColor += max(dot(viewNormal, ${i.getDirection(t.viewMatrix,c)}), 0.0) * ${i.getColor()};`)})),e.push(`vec4 color = vec4(${s.getAmbientColor()} + reflectedColor, 1) * ${A(u)};`),e.push(`vec4 sampleColor = ${o(h)};`),a&&e.push(`if (sampleColor.a < ${a}) { discard; }`),e.push("vec4 colorTexel = color * sampleColor;"),e.push(`${d} = vec4(colorTexel.rgb${r?" * "+r.getAmbient(n):""}, color.a);`),i&&e.push(`${d} = ${i(d)};`)},incrementDrawState:!0}}(r,n,t,e(r),s&&i(r),A,t.gammaOutput);return{PBR:n&&f(((r,n,A)=>A(function(e,t,i,s,r){const n=(t,i,s)=>bi(e,"sampler2D",t,i?3001:3e3,((e,t)=>{const i=s(t.layerTextureSet);i&&e(i.texture)})),A=t.attributes,o=s.getIrradiance,a=n("uColorMap",!0,(e=>e.colorTexture)),l=n("uMetallicRoughMap",!1,(e=>e.metallicRoughnessTexture)),c=n("uEmissiveMap",!0,(e=>e.emissiveTexture)),h=n("uNormalMap",!1,(e=>e.normalsTexture)),u=n("uAOMap",!1,(e=>e.occlusionTexture)),d=e.createVarying("vec3","vViewPosition",(()=>`${A.position.view}.xyz`)),f=e.createVarying("vec3","vViewNormal",(()=>A.normal.view)),p=e.createVarying("vec4","vColor",(()=>A.color)),g=e.createVarying("vec2","vUV",(()=>A.uv)),m=e.createVarying("vec2","vMetallicRoughness",(()=>A.metallicRoughness)),_=e.createVarying("vec3","vWorldNormal",(()=>`${A.normal.world}.xyz`)),b=e.createOutput("vec4","outColor"),y=e.createFragmentDefinition("saturate",((e,t)=>t.push(`float ${e}(const in float a) { return clamp(a, 0.0, 1.0); }`))),w=e.createFragmentDefinition("BRDF_Specular_GGX",((e,t)=>{t.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),t.push(" float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),t.push(" return ( 1.0 - specularColor ) * fresnel + specularColor;"),t.push("}"),t.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),t.push(" float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),t.push(" return 1.0 / ( gl * gv );"),t.push("}"),t.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),t.push(" float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),t.push(" return 0.5 / max( gv + gl, 1e-6 );"),t.push("}"),t.push("float D_GGX(const in float alpha, const in float dotNH) {"),t.push(" float a2 = ( alpha * alpha );"),t.push(" float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),t.push(" return 0.31830988618 * a2 / ( denom * denom);"),t.push("}"),t.push(`vec3 ${e}(const in vec3 incidentLightDirection, const in vec3 viewNormal, const in vec3 viewEyeDir, const in vec3 specularColor, const in float roughness) {`),t.push(" float alpha = ( roughness * roughness );"),t.push(" vec3 halfDir = normalize( incidentLightDirection + viewEyeDir );"),t.push(` float dotNL = ${y}( dot( viewNormal, incidentLightDirection ) );`),t.push(` float dotNV = ${y}( dot( viewNormal, viewEyeDir ) );`),t.push(` float dotNH = ${y}( dot( viewNormal, halfDir ) );`),t.push(` float dotLH = ${y}( dot( incidentLightDirection, halfDir ) );`),t.push(" vec3 F = F_Schlick( specularColor, dotLH );"),t.push(" float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),t.push(" float D = D_GGX( alpha, dotNH );"),t.push(" return F * (G * D);"),t.push("}")})),v=e.createFragmentDefinition("BRDF_Specular_GGX_Environment",((e,t)=>{t.push(`vec3 ${e}(const in vec3 viewNormal, const in vec3 viewEyeDir, const in vec3 specularColor, const in float roughness) {`),t.push(` float dotNV = ${y}(dot(viewNormal, viewEyeDir));`),t.push(" const vec4 c0 = vec4( -1, -0.0275, -0.572, 0.022);"),t.push(" const vec4 c1 = vec4( 1, 0.0425, 1.04, -0.04);"),t.push(" vec4 r = roughness * c0 + c1;"),t.push(" float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),t.push(" vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;"),t.push(" return specularColor * AB.x + AB.y;"),t.push("}")})),B=e.createFragmentDefinition("perturbNormal2Arb",((e,t)=>{t.push(`vec3 ${e}( vec3 eye_pos, vec3 surf_norm, vec2 uv, vec4 texel ) {`),t.push(" if (texel.r == 0.0 && texel.g == 0.0 && texel.b == 0.0) {"),t.push(" return surf_norm;"),t.push(" }"),t.push(" vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),t.push(" vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),t.push(" vec2 st0 = dFdx( uv.st );"),t.push(" vec2 st1 = dFdy( uv.st );"),t.push(" vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),t.push(" vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),t.push(" vec3 N = normalize( surf_norm );"),t.push(" vec3 mapN = texel.xyz * 2.0 - 1.0;"),t.push(" mat3 tsn = mat3( S, T, N );"),t.push(" return normalize( tsn * mapN );"),t.push("}")}));return{programName:"PBR",getHash:()=>[s.getHash(),r?"sao":"nosao",!!i.gammaOutput],getLogDepth:i.logarithmicDepthBufferEnabled&&(e=>e),renderPassFlag:0,clippingCaps:i._sectionPlanesState.clippingCaps&&b,incrementDrawState:!0,appendFragmentOutputs:(e,i,n)=>{if(e.push("const float PI = 3.14159265359;"),e.push("vec3 reflDiff = vec3(0.0);"),e.push("vec3 reflSpec = vec3(0.0);"),e.push(`vec3 rgb = ${p}.rgb;`),e.push(`float opacity = ${p}.a;`),e.push("vec3 baseColor = rgb;"),e.push("float specularF0 = 1.0;"),e.push(`float metallic = float(${m}.r) / 255.0;`),e.push(`float roughness = float(${m}.g) / 255.0;`),e.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),e.push(`vec4 colorTexel = ${a(g)};`),e.push("baseColor *= colorTexel.rgb;"),e.push(`vec3 metalRoughTexel = ${l(g)}.rgb;`),e.push("metallic *= metalRoughTexel.b;"),e.push("roughness *= metalRoughTexel.g;"),e.push("vec3 diffuseColor = baseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),e.push("float specularRoughness = clamp(roughness, 0.04, 1.0);"),e.push("vec3 specularColor = mix(vec3(dielectricSpecular), baseColor, metallic);"),e.push(`vec3 viewNormal = -${B}(${d}, normalize(${f}), ${g}, ${h(g)});`),e.push(`vec3 viewEyeDir = normalize(${d});`),o&&e.push(`reflDiff += ${o(`normalize(${_})`)};`),s.getReflection){const i=`normalize((vec4(reflect(viewEyeDir, viewNormal), 0.0) * ${t.viewMatrix}).xyz)`,r="8.0",n=`0.5 * clamp(${r} - 0.79248 - 0.5 * log2(pow((2.0 / pow(specularRoughness + 0.0001, 2.0) - 2.0), 2.0) + 1.0), 0.0, ${r})`,A=s.getReflection(i,n),o=`${v}(viewNormal, viewEyeDir, specularColor, specularRoughness)`;e.push(`reflSpec += ${A} * ${o};`)}s.directionalLights.forEach(((i,s)=>{e.push(`vec3 lightDirection${s} = -${i.getDirection(t.viewMatrix,d)};`);const r=`${y}(dot(viewNormal, lightDirection${s}))`;e.push(`vec3 irradiance${s} = ${r} * ${i.getColor()};`),e.push(`reflDiff += irradiance${s};`),e.push(`reflSpec += irradiance${s} * PI * ${w}(lightDirection${s}, viewNormal, viewEyeDir, specularColor, specularRoughness);`)})),e.push(`vec3 emissiveColor = ${c(g)}.rgb;`),e.push(`float aoFactor = ${u(g)}.r;`);const A=`${s.getAmbientColor()} * baseColor * opacity * rgb`;e.push(`vec3 outgoingLight = emissiveColor + reflDiff * diffuseColor + reflSpec + ${A};`),e.push(`${b} = vec4(outgoingLight * aoFactor${r?` * ${r.getAmbient(n)}`:""}, opacity);`),i&&e.push(`${b} = ${i(b)};`)}}}(r,n,t,e(r),s&&i(r))))),texture:A&&{"alphaCutoff-":f(((e,t,i)=>i(r(e,t,!1)))),"alphaCutoff+":f(((e,t,i)=>i(r(e,t,!0))))},vertex:f(o?(t,r,n)=>n(p(t,r,e(t),s&&i(t))):(r,n,A)=>A(function(e,t,i,s,r){const n=t.attributes,A=e.createVarying("vec3","vViewPosition",(()=>`${n.position.view}.xyz`)),o=e.createVarying("vec4","vColor",(()=>n.color)),a=e.createOutput("vec4","outColor");return{programName:"FlatColor",getHash:()=>[s.getHash(),r?"sao":"nosao"],cleanerEdges:!0,getLogDepth:i&&(e=>e),renderPassFlag:0,appendFragmentOutputs:(e,i,n,l)=>{e.push(`vec3 viewNormal = normalize(cross(dFdx(${A}), dFdy(${A})));`);const c=[s.getAmbientColor()].concat(s.directionalLights.map((e=>`max(dot(viewNormal, ${e.getDirection(t.viewMatrix,A)}), 0.0) * ${e.getColor()}`)));e.push(`vec4 fragColor = vec4(${c.join(" + ")}, 1) * ${l(o)};`),e.push(`${a} = ${r?`vec4(fragColor.rgb * ${r.getAmbient(n)}, fragColor.a)`:"fragColor"};`)}}}(r,n,t.logarithmicDepthBufferEnabled,e(r),s&&i(r))))}};return{"sao-":s(!1),"sao+":r&&s(!0)}}(),depthRenderer:f(((e,i,s)=>s(function(e,t,i){const s=e.createVarying("highp vec2","vHighPrecisionZW",(()=>`${t.attributes.position.clip}.zw`)),r=e.createOutput("vec4","outColor");return{programName:"Depth",getLogDepth:i&&(e=>e),renderPassFlag:0,appendFragmentOutputs:e=>e.push(`${r} = vec4(vec3((1.0 - ${s}[0] / ${s}[1]) / 2.0), 1.0);`)}}(e,i,t.logarithmicDepthBufferEnabled)))),edgesRenderers:{uniform:f(((e,i,s)=>s(js(e,i,t.logarithmicDepthBufferEnabled,!0))),{vertices:!1}),vertex:f(((e,i,s)=>s(js(e,i,t.logarithmicDepthBufferEnabled,!1))),{vertices:!1})},occlusionRenderer:f(((e,i,s)=>s(Ws(e,t.logarithmicDepthBufferEnabled)))),pickDepthRenderer:u(g),pickMeshRenderer:u(m),pickNormalsFlatRenderer:u(((e,t,i)=>_(e,t,i,!0))),pickNormalsRenderer:u(((e,t,i)=>_(e,t,i,!1))),shadowRenderer:f(((e,i,s)=>s(function(e,t){const i=e.createOutput("vec4","outColor"),s=e.createFragmentDefinition("encodeFloat",((e,t)=>{t.push(`vec4 ${e}(const in float v) {`),t.push(" const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),t.push(" const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),t.push(" vec4 comp = fract(v * bitShift);"),t.push(" comp -= comp.xxyz * bitMask;"),t.push(" return comp;"),t.push("}")}));return{programName:"Shadow",getLogDepth:t&&(e=>e),renderPassFlag:0,isShadowProgram:!0,appendFragmentOutputs:(e,t,r)=>e.push(`${i} = ${s}(${r}.z);`)}}(e,t)))),silhouetteRenderer:u(((e,i,s)=>s(zs(e,i,t.logarithmicDepthBufferEnabled,!1)))),snapInitRenderer:u(((e,t,i)=>b(e,t,i,!0,!1))),snapEdgeRenderer:u(((e,t,i)=>b(e,t,i,!1,!1)),{vertices:!1}),snapVertexRenderer:u(((e,t,i)=>b(e,t,i,!1,!1)),{vertices:!0})};const y=e=>{!function t(i){i.revalidate?i.revalidate(e):Object.values(i).forEach((e=>e&&t(e)))}(c[h])},w=()=>y(!1);w(),t.on("compile",w),t.on("destroyed",(()=>{delete c[h]}))}return c[h]}}();class dr{constructor(e,t,i){this.model=e,this.primitive=t,this.origin=i,this._meshes=[],this._aabb=d.collapseAABB3(),this._aabbDirty=!0}finalize(){if(!this._compiledPortions){this._compiledPortions=this.compilePortions(),this.solid=this._compiledPortions.solid,this.sortId=this._compiledPortions.sortId,this.layerTextureSet=this._compiledPortions.layerTextureSet,this.drawCalls=this._compiledPortions.drawCalls,this._renderers=this._compiledPortions.renderers,this._setFlags=this._compiledPortions.setFlags,this.setColor=this._compiledPortions.setColor,this.setMatrix=this._compiledPortions.setMatrix,this.setOffset=this._compiledPortions.setOffset,this.getEachIndex=this._compiledPortions.getEachIndex,this.getEachVertex=this._compiledPortions.getEachVertex,this.readGeometryData=this._compiledPortions.readGeometryData,this.precisionRayPickSurface=this._compiledPortions.precisionRayPickSurface,this._countsByFlag={};const e=(e,t)=>{const i={count:0,fromFlags:(s,r)=>{s&e?(i.count++,this.model[t]++):r||(i.count--,this.model[t]--)}};this._countsByFlag[e]=i};e(ks,"numVisibleLayerPortions"),e(Qs,"numCulledLayerPortions"),e(Rs,"numPickableLayerPortions"),e(Os,"numClippableLayerPortions"),e(Ls,"numXRayedLayerPortions"),e(Hs,"numHighlightedLayerPortions"),e(Ns,"numSelectedLayerPortions"),this._renderers.edgesRenderers&&e(Gs,"numEdgesLayerPortions"),this._countsByFlagArr=Object.values(this._countsByFlag),this._numTransparentLayerPortions=0}}aabbChanged(){this._aabbDirty=!0}__drawLayer(e,t,i,s){if(this._countsByFlag[Qs].count<this._portions.length&&this._countsByFlag[ks].count>0){const e="points"!==this.primitive&&"lines"!==this.primitive&&[qs,er,lr,tr,ir,sr];if(e&&e.includes(s)){const e=!0;if(t.backfaces!==e){const i=this.model.scene.canvas.gl;i.disable(i.CULL_FACE),t.backfaces=e}}t.textureUnit=0,i.drawLayer(t,this,s)}}__setVec4FromMaterialColorAlpha(e,t,i){return i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=t,i}__drawColor(e,t,i){if((i?this._numTransparentLayerPortions<this._portions.length:this._numTransparentLayerPortions>0)&&this._countsByFlag[Ls].count<this._portions.length){const s=i&&t.withSAO&&this._renderers.colorRenderers["sao+"]||this._renderers.colorRenderers["sao-"],r=t.pbrEnabled&&s.PBR?s.PBR:t.colorTextureEnabled&&s.texture?s.texture[this.layerTextureSet&&"number"==typeof this.layerTextureSet.alphaCutoff?"alphaCutoff+":"alphaCutoff-"]:s.vertex,n=i?qs:er;this.__drawLayer(e,t,r,n)}}drawColorOpaque(e,t){this.__drawColor(e,t,!0)}drawColorTransparent(e,t){this.__drawColor(e,t,!1)}drawDepth(e,t){const i=this._renderers.depthRenderer;i&&this._numTransparentLayerPortions<this._portions.length&&this._countsByFlag[Ls].count<this._portions.length&&this.__drawLayer(e,t,i,qs)}__drawSilhouette(e,t,i,s){t.programColor=this.__setVec4FromMaterialColorAlpha(i.fillColor,i.fillAlpha,Zs),this.__drawLayer(e,t,this._renderers.silhouetteRenderer,s)}drawSilhouetteXRayed(e,t){this._countsByFlag[Ls].count>0&&this.__drawSilhouette(e,t,this.model.scene.xrayMaterial,sr)}drawSilhouetteHighlighted(e,t){this._countsByFlag[Hs].count>0&&this.__drawSilhouette(e,t,this.model.scene.highlightMaterial,tr)}drawSilhouetteSelected(e,t){this._countsByFlag[Ns].count>0&&this.__drawSilhouette(e,t,this.model.scene.selectedMaterial,ir)}__drawVertexEdges(e,t,i){const s=this._renderers.edgesRenderers&&this._renderers.edgesRenderers.vertex;s&&this._countsByFlag[Gs].count>0&&this.__drawLayer(e,t,s,i)}drawEdgesColorOpaque(e,t){this._compiledPortions.edgesColorOpaqueAllowed()&&this.__drawVertexEdges(e,t,rr)}drawEdgesColorTransparent(e,t){this._numTransparentLayerPortions>0&&this.__drawVertexEdges(e,t,nr)}__drawUniformEdges(e,t,i,s){const r=this._renderers.edgesRenderers&&this._renderers.edgesRenderers.uniform;r&&(t.programColor=this.__setVec4FromMaterialColorAlpha(i.edgeColor,i.edgeAlpha,Zs),this.__drawLayer(e,t,r,s))}drawEdgesHighlighted(e,t){this._countsByFlag[Hs].count>0&&this.__drawUniformEdges(e,t,this.model.scene.highlightMaterial,Ar)}drawEdgesSelected(e,t){this._countsByFlag[Ns].count>0&&this.__drawUniformEdges(e,t,this.model.scene.selectedMaterial,or)}drawEdgesXRayed(e,t){this._countsByFlag[Ls].count>0&&this.__drawUniformEdges(e,t,this.model.scene.xrayMaterial,ar)}__drawPick(e,t,i){i&&this.__drawLayer(e,t,i,lr)}drawPickMesh(e,t){this.__drawPick(e,t,this._renderers.pickMeshRenderer)}drawPickDepths(e,t){this.__drawPick(e,t,this._renderers.pickDepthRenderer)}drawPickNormals(e,t){const i=this._renderers.pickNormalsFlatRenderer;this.__drawPick(e,t,i)}drawSnap(e,t,i){t.snapPickOrigin=[0,0,0],this._aabbDirty&&(d.collapseAABB3(this._aabb),this._meshes.forEach((e=>d.expandAABB3(this._aabb,e.aabb))),this._aabbDirty=!1);const s=this._aabb;t.snapPickCoordinateScale=d.mulVec3Scalar(cr([s[3]-s[0],s[4]-s[1],s[5]-s[2]]),d.MAX_INT);const r=i?this._renderers.snapInitRenderer:"edge"===t.snapMode?this._renderers.snapEdgeRenderer:this._renderers.snapVertexRenderer;this.__drawPick(e,t,r),t.snapPickLayerParams.push({origin:t.snapPickOrigin.slice(),coordinateScale:cr(t.snapPickCoordinateScale)})}drawOcclusion(e,t){const i=this._renderers.occlusionRenderer;i&&this.__drawLayer(e,t,i,qs)}drawShadow(e,t){const i=this._renderers.shadowRenderer;i&&this.__drawLayer(e,t,i,qs)}initFlags(e,t,i){this._countsByFlagArr.forEach((e=>e.fromFlags(t,!0))),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++);const s="points"!==this.primitive;this._setFlags(e,t,i,s),this._compiledPortions.setFlags2(e,t,s)}flushInitFlags(){this._compiledPortions.setDeferredFlags()}setVisible(e,t,i){this._countsByFlag[ks].fromFlags(t),this._setFlags(e,t,i)}setCulled(e,t,i){this._countsByFlag[Qs].fromFlags(t),this._setFlags(e,t,i)}setPickable(e,t,i){this._countsByFlag[Rs].fromFlags(t),this._setFlags(e,t,i)}setClippable(e,t){this._countsByFlag[Os].fromFlags(t),this._compiledPortions.setClippableFlags(e,t)}setCollidable(e,t){}setXRayed(e,t,i){this._countsByFlag[Ls].fromFlags(t),this._setFlags(e,t,i)}setHighlighted(e,t,i){this._countsByFlag[Hs].fromFlags(t),this._setFlags(e,t,i)}setSelected(e,t,i){this._countsByFlag[Ns].fromFlags(t),this._setFlags(e,t,i)}setEdges(e,t,i){this._countsByFlag[Gs]&&(this._countsByFlag[Gs].fromFlags(t),this._setFlags(e,t,i))}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}destroy(){this._compiledPortions&&this._compiledPortions.destroy()}}let fr=65536,pr=5e6;class gr{constructor(){}set doublePrecisionEnabled(e){d.setDoublePrecisionEnabled(e)}get doublePrecisionEnabled(){return d.getDoublePrecisionEnabled()}set maxDataTextureHeight(e){(e=1024*Math.ceil(e/1024))>4096?e=4096:e<1024&&(e=1024),fr=e}get maxDataTextureHeight(){return fr}set maxGeometryBatchSize(e){e<1e5?e=1e5:e>5e6&&(e=5e6),pr=e}get maxGeometryBatchSize(){return pr}}const mr=e=>{const t=[];for(let i=0;i<e;++i)t.push(i);return t},_r={sizeDataColorsAndFlags:0,sizeDataInstancesMatrices:0,sizeDataPositionDecodeMatrices:0,sizeDataTextureOffsets:0,sizeDataTexturePositions:0,sizeDataTextureIndices:0,sizeDataTextureEdgeIndices:0,sizeDataTexturePortionIds:0,numberOfGeometries:0,numberOfPortions:0,numberOfLayers:0,numberOfTextures:0,totalPolygons:0,totalPolygons8Bits:0,totalPolygons16Bits:0,totalPolygons32Bits:0,totalEdges:0,totalEdges8Bits:0,totalEdges16Bits:0,totalEdges32Bits:0,cannotCreatePortion:{because10BitsObjectId:0,becauseTextureSize:0},overheadSizeAlignementIndices:0,overheadSizeAlignementEdgeIndices:0};window.printDataTextureRamStats=function(){console.log(JSON.stringify(_r,null,4));let e=0;Object.keys(_r).forEach((t=>{t.startsWith("size")&&(e+=_r[t])})),console.log(`Total size ${e} bytes (${(e/1e3/1e3).toFixed(2)} MB)`),console.log(`Avg bytes / triangle: ${(e/_r.totalPolygons).toFixed(2)}`);let t={};Object.keys(_r).forEach((i=>{i.startsWith("size")&&(t[i]=`${(_r[i]/e*100).toFixed(2)} % of total`)})),console.log(JSON.stringify({percentualRamUsage:t},null,4))};const br=new gr,yr=br.maxDataTextureHeight,wr=d.vec3(),vr=d.vec3(),Br=d.vec4();d.vec4();const Cr=new Float32Array(16),Mr=new Uint8Array(4),Er=d.identityMat4();class Fr extends dr{constructor(e,t,i){super(e,t,i),_r.numberOfLayers++,this._sortId=`TriDTX-${_r.numberOfLayers}`;const s=e.scene.canvas.gl,r=(e,t)=>{const i=[];let r=0;const A=[];let o=0;const a=[];let l=0;const c=[];let h=0;return{len:()=>o,accumulateIndices:(s,u)=>{const d=s&&s.length>0&&function(){const t=r/3;r+=s.length,i.push(s);const a=s.length/3;return i=>{const s=o;o+=3*a,n.perObjectIndexBaseOffsets.push(s/3-t);for(let e=0;e<a;e+=8)A.push(i);_r[e]+=a,_r.totalPolygons+=a}}(),f=u&&u.length>0&&function(){const e=l/2;l+=u.length,a.push(u);const i=u.length/2;return s=>{const r=h;h+=2*i,n.perObjectEdgeIndexBaseOffsets.push(r/2-e);for(let e=0;e<i;e+=8)c.push(s);_r[t]+=i,_r.totalEdges+=i}}();return _r.numberOfGeometries++,{numTriangles:s?s.length/3:0,accumulateSubPortionId:e=>{d&&d(e),f&&f(e)}}},createDrawers:(e,t)=>{const n=function(t,i){return t.length>0?e([t],t.length,1,s.UNSIGNED_SHORT,"sizeDataTexturePortionIds"):i},u=n(A,{texture:null}),d=r>0&&e(i,r,3,t,"sizeDataTextureIndices"),f=n(c),p=l>0&&e(a,l,2,t,"sizeDataTextureEdgeIndices");return{indices:function(e,t){o>0&&(e.perPrimIndices.setInputValue(d),e.perPrimIdPorIds.setInputValue(u),s.drawArrays(t,0,o))},edges:function(e,t){h>0&&(e.perPrimIndices.setInputValue(p),e.perPrimIdPorIds.setInputValue(f),s.drawArrays(t,0,h))}}}}},n=this._buffer={positionsCompressed:[],lenPositionsCompressed:0,geometry8Bits:r("totalPolygons8Bits","totalEdges8Bits"),geometry16Bits:r("totalPolygons16Bits","totalEdges16Bits"),geometry32Bits:r("totalPolygons32Bits","totalEdges32Bits"),perObjectColors:[],perObjectPickColors:[],perObjectSolid:[],perObjectPositionsDecodeMatrices:[],perObjectInstancePositioningMatrices:[],perObjectVertexBases:[],perObjectIndexBaseOffsets:[],perObjectEdgeIndexBaseOffsets:[]};this._numVertices=0,this._portions=[],this._subPortionReadableGeometries=this.model.scene.readableGeometryEnabled&&{},this._portionToSubPortionsMap=[],this._bucketGeometries={},this._primitive=t}canCreatePortion(e){const t=e.buckets.length;this._portions.length+t>65536&&_r.cannotCreatePortion.because10BitsObjectId++;let i=this._portions.length+t<=65536;const s=void 0!==e.geometryId&&null!==e.geometryId?`${e.geometryId}#0`:`${e.id}#0`;if(!this._bucketGeometries[s]){const t=this._buffer,s=Math.max(t.geometry8Bits.len(),t.geometry16Bits.len(),t.geometry32Bits.len());let r=0,n=0;e.buckets.forEach((e=>{r+=e.positionsCompressed.length/3,n+=e.indices.length/3})),(this._numVertices+r>4096*yr||s+n>4096*yr)&&_r.cannotCreatePortion.becauseTextureSize++,i&&=this._numVertices+r<=4096*yr&&s+n<=4096*yr}return i}createPortion(e,t){const i=this._buffer,s=t.buckets.map(((e,s)=>{const r=(t.geometryId??t.id)+"#"+s;if(!(r in this._bucketGeometries)){const t=(e,t,i)=>{if(e){const s=8*Math.ceil(e.length/t/8)*t,r=new Uint32Array(s);return r.set(e),_r[i]+=2*(r.length-e.length),r}return e};e.indices=t(e.indices,3,"overheadSizeAlignementIndices"),e.edgeIndices=t(e.edgeIndices,2,"overheadSizeAlignementEdgeIndices");const s=e.positionsCompressed;i.positionsCompressed.push(s);const n=s.length/3;this._numVertices+=n;const A=i.lenPositionsCompressed/3;i.lenPositionsCompressed+=s.length,this._bucketGeometries[r]={vertexBase:A,geometryData:function(){const t=e.indices,s=e.edgeIndices;return n<=256?i.geometry8Bits.accumulateIndices(t,s):n<=65536?i.geometry16Bits.accumulateIndices(t,s):i.geometry32Bits.accumulateIndices(t,s)}()}}const n=this._bucketGeometries[r];i.perObjectPositionsDecodeMatrices.push(t.positionsDecodeMatrix),i.perObjectInstancePositioningMatrices.push(t.meshMatrix||Er),i.perObjectSolid.push(!!t.solid),i.perObjectPickColors.push(t.pickColor),i.perObjectVertexBases.push(n.vertexBase);const A=t.colors,o=t.color;i.perObjectColors.push(A?[255*A[0],255*A[1],255*A[2],255]:[o[0],o[1],o[2],t.opacity]);const a=this._portions.length;return this._portions.push({}),n.geometryData.accumulateSubPortionId(a),this._subPortionReadableGeometries&&(this._subPortionReadableGeometries[a]={indices:e.indices,positionsCompressed:e.positionsCompressed,positionsDecodeMatrix:t.positionsDecodeMatrix}),_r.numberOfPortions++,a})),r=this._portionToSubPortionsMap.length;return this._portionToSubPortionsMap.push(s),this.model.numPortions++,this._meshes.push(e),r}compilePortions(){const e=this._buffer,t=this.model,i=this._portions.length,s=this.origin,r=this._portionToSubPortionsMap,n=this._primitive,A=this._sortId,o=this._subPortionReadableGeometries,a=t.scene,l=a.canvas.gl,c=Ur(l,i,32,l.UNSIGNED_BYTE,512,(t=>{const s=e=>[e>>24&255,e>>16&255,e>>8&255,255&e];for(let r=0;r<i;r++)t.set(e.perObjectColors[r],32*r+0),t.set(e.perObjectPickColors[r],32*r+4),t.set([0,0,0,0],32*r+8),t.set([0,0,0,0],32*r+12),t.set(s(e.perObjectVertexBases[r]),32*r+16),t.set(s(e.perObjectIndexBaseOffsets[r]),32*r+20),t.set(s(e.perObjectEdgeIndexBaseOffsets[r]),32*r+24),t.set([e.perObjectSolid[r]?1:0,0,0,0],32*r+28)}),"sizeDataColorsAndFlags",!0),h=c.textureData,u=function(e,t,i,s,r,n,A){return Ur(l,t,i,s,r,(t=>{for(let i=0,s=0,r=e.length;i<r;i++){const r=e[i];t.set(r,s),s+=r.length}}),n,A)},f=function(e,t,i){const s=e.length;if(0===s)throw"num "+t+" matrices===0";return u(e,s,16,l.FLOAT,512,t,i)},p=f(e.perObjectInstancePositioningMatrices,"sizeDataInstancesMatrices",!0),g=p.textureData,m=f(e.perObjectPositionsDecodeMatrices,"sizeDataPositionDecodeMatrices",!1),_=function(e,t,i,s,r){return u(e,t/i,i,s,4096,r,!1)},b=_(e.positionsCompressed,e.lenPositionsCompressed,3,l.UNSIGNED_SHORT,"sizeDataTexturePositions"),y=e.geometry8Bits.createDrawers(_,l.UNSIGNED_BYTE),w=e.geometry16Bits.createDrawers(_,l.UNSIGNED_SHORT),v=e.geometry32Bits.createDrawers(_,l.UNSIGNED_INT);this._buffer=null;let B=!1,C=!1,M=!1,E=0;const F=()=>{B=!0},U=a.on("rendering",(()=>{C&&(B=!1,C=!1,h.reloadData()),E=0})),x=(e,i)=>{const s=r[e];if(s)for(let e=0,t=s.length;e<t;e++)i(s[e]);else t.error("portion not found: "+e)},I=(e,t,i,s)=>{const r=B||s;r?C=!0:++E>=10&&F(),h.setData(i,e,t,!r)},T=(e,t,i=!1)=>{Mr.set([t&Os?255:0,0,1,2]),x(e,(e=>I(e,3,Mr,i)))};return{edgesColorOpaqueAllowed:()=>!a.logarithmicDepthBufferEnabled||(a._loggedWarning||(console.log("Edge enhancement for SceneModel data texture layers currently disabled with logarithmic depth buffer"),a._loggedWarning=!0),!1),sortId:A,setClippableFlags:T,setFlags:(e,t,i,s=!1)=>{hr(t,i,!0,a,Mr),x(e,(e=>I(e,2,Mr,s)))},setFlags2:T,setDeferredFlags:()=>{},setColor:(e,t)=>{Mr.set(t),x(e,(e=>I(e,0,Mr,!1)))},setMatrix:(e,t)=>{x(e,(e=>{const i=B;i?C=!0:++E>=10&&F(),Cr.set(t),g.setData(Cr,e,0,!i)}))},setOffset:(e,t)=>{},getEachIndex:(e,t)=>{o&&x(e,(e=>o[e].indices.forEach((e=>t(e)))))},getEachVertex:(e,i)=>{o&&x(e,(e=>{const r=o[e],n=r.positionsCompressed,A=r.positionsDecodeMatrix,a=Br;for(let e=0,r=n.length;e<r;e+=3)a[0]=n[e],a[1]=n[e+1],a[2]=n[e+2],a[3]=1,d.decompressPosition(a,A),d.mulMat4v4(t.worldMatrix,a,a),d.addVec3(s,a,a),i(a)}))},precisionRayPickSurface:(e,t,i,s,r)=>!1,renderers:ur(a,"dtx",n,t.saoEnabled,!1,!1,!0,((e,t)=>xr(e,!t))),drawCalls:function(){const e=function(e){const i=(e,t)=>e.setInputValue&&e.setInputValue(t);return(r,n,A)=>{i(n.worldMatrix,t.rotationMatrix),i(n.viewMatrix,A.viewMatrix),i(n.projMatrix,A.projMatrix);const o=d.transformPoint3(t.matrix,s,wr);i(n.uCameraEyeRtc,d.subVec3(A.eye,o,vr)),i(n.perObjPosDecode,m),i(n.perVertIdCoords,b),i(n.perObjColsFlags,c),i(n.perObjectMatrix,p),e(n)}},i=function(t){return e((e=>{y.edges(e,t),w.edges(e,t),v.edges(e,t)}))};return{drawVertices:i(l.POINTS),drawEdges:i(l.LINES),drawSurface:e((e=>{const t=l.TRIANGLES;y.indices(e,t),w.indices(e,t),v.indices(e,t)}))}}(),destroy:()=>{M||(a.off(U),M=!0)}}}}const Ur=function(e,t,i,s,r,n,A,o){if(i>4&&i%4>0)throw"Unhandled data size "+i;const a=Math.ceil(i/4),l=i/a,[c,h,u]=function(){switch(s){case e.UNSIGNED_BYTE:return[Uint8Array,...1===l?[e.R8UI,e.RED_INTEGER]:2===l?[e.RG8UI,e.RG_INTEGER]:3===l?[e.RGB8UI,e.RGB_INTEGER]:[e.RGBA8UI,e.RGBA_INTEGER]];case e.UNSIGNED_SHORT:return[Uint16Array,...1===l?[e.R16UI,e.RED_INTEGER]:2===l?[e.RG16UI,e.RG_INTEGER]:3===l?[e.RGB16UI,e.RGB_INTEGER]:[e.RGBA16UI,e.RGBA_INTEGER]];case e.UNSIGNED_INT:return[Uint32Array,...1===l?[e.R32UI,e.RED_INTEGER]:2===l?[e.RG32UI,e.RG_INTEGER]:3===l?[e.RGB32UI,e.RGB_INTEGER]:[e.RGBA32UI,e.RGBA_INTEGER]];case e.FLOAT:return[Float32Array,...1===l?[e.R32F,e.RED]:2===l?[e.RG32F,e.RG]:3===l?[e.RGB32F,e.RGB]:[e.RGBA32F,e.RGBA]];default:throw"Unhandled data type "+s}}(),d=r*a,f=Math.ceil(t/r);if(0===f)throw"texture height===0";const p=new c(d*f*l);_r[A]+=p.byteLength,_r.numberOfTextures++,n(p);const g=e.createTexture();return e.bindTexture(e.TEXTURE_2D,g),e.texStorage2D(e.TEXTURE_2D,1,h,d,f),e.texSubImage2D(e.TEXTURE_2D,0,0,0,d,f,u,s,p),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.bindTexture(e.TEXTURE_2D,null),{bind:t=>(e.activeTexture(e["TEXTURE"+t]),e.bindTexture(e.TEXTURE_2D,g),!0),unbind(e){},textureData:o&&{setData(t,n,A=0,o=!1){if(p.set(t,n*i+A*l),o){e.bindTexture(e.TEXTURE_2D,g);const i=n%r*a+A,o=Math.floor(n/r),c=t.length/l;e.texSubImage2D(e.TEXTURE_2D,0,i,o,c,1,u,s,t)}},reloadData(){e.bindTexture(e.TEXTURE_2D,g),e.texSubImage2D(e.TEXTURE_2D,0,0,0,d,f,u,s,p)}}}},xr=function(e,t){const i=(t,i)=>{const s=e.createUniform(t,i),r=e=>`texelFetch(${s}, ${e}, 0)`;return r.map=s,r},s=i("highp usampler2D","perPrimIndices"),r=i("mediump usampler2D","perPrimIdPorIds"),n=i("highp sampler2D","perObjPosDecode"),A=i("mediump usampler2D","perVertIdCoords"),o=i("lowp usampler2D","perObjColsFlags"),a=i("highp sampler2D","perObjectMatrix"),l=e.createUniform("mat4","worldMatrix"),c=e.createUniform("mat4","viewMatrix"),h=e.createUniform("mat4","projMatrix"),u=e.createUniform("vec3","uCameraEyeRtc"),d=function(e){const t={toString:()=>(t.needed=!0,e)};return t},f=d("colorA"),p=d("pickColor"),g=d("worldNormal"),m=d("viewNormal"),_=e=>o(`ivec2(objectIndexCoords.x*8+${e}, objectIndexCoords.y)`);return{geometryParameters:{attributes:{clippable:"(flags2.r > 0u)",color:f,flags:mr(4).map((e=>`int(flags[${e}])`)),metallicRoughness:null,normal:{view:m,world:g},pickColor:p,position:{clip:"gl_Position",view:"viewPosition",world:"worldPosition"},uv:null},projMatrix:h,viewMatrix:c},ensureColorAndFlagAvailable:e=>{e.push("int primitiveIndex = gl_VertexID / "+(t?3:2)+";"),e.push("int h_packed_object_id_index = (primitiveIndex >> 3) & 4095;"),e.push("int v_packed_object_id_index = (primitiveIndex >> 3) >> 12;"),e.push(`int objectIndex = int(${r("ivec2(h_packed_object_id_index, v_packed_object_id_index)")}.r);`),e.push("ivec2 objectIndexCoords = ivec2(objectIndex % 512, objectIndex / 512);"),e.push(`uvec4 flags = ${_(2)};`),e.push(`uvec4 flags2 = ${_(3)};`),f.needed&&e.push(`vec4 ${f} = vec4(${_(0)}) / 255.0;`)},appendVertexData:e=>{const i=e=>a(`ivec2(objectIndexCoords.x*4+${e}, objectIndexCoords.y)`);e.push(`mat4 objectInstanceMatrix = mat4(${i(0)}, ${i(1)}, ${i(2)}, ${i(3)});`);const r=e=>n(`ivec2(objectIndexCoords.x*4+${e}, objectIndexCoords.y)`);if(e.push(`mat4 objectDecodeAndInstanceMatrix = objectInstanceMatrix * mat4(${r(0)}, ${r(1)}, ${r(2)}, ${r(3)});`),e.push(`ivec4 packedVertexBase = ivec4(${_(4)});`),e.push(`ivec4 packedIndexBaseOffset = ivec4(${_(t?5:6)});`),e.push("int indexBaseOffset = (packedIndexBaseOffset.r << 24) + (packedIndexBaseOffset.g << 16) + (packedIndexBaseOffset.b << 8) + packedIndexBaseOffset.a;"),e.push("int h_index = (primitiveIndex - indexBaseOffset) & 4095;"),e.push("int v_index = (primitiveIndex - indexBaseOffset) >> 12;"),e.push(`ivec3 vertexIndices = ivec3(${s("ivec2(h_index, v_index)")});`),e.push("ivec3 uniqueVertexIndexes = vertexIndices + (packedVertexBase.r << 24) + (packedVertexBase.g << 16) + (packedVertexBase.b << 8) + packedVertexBase.a;"),t){e.push("ivec3 indexPositionH = uniqueVertexIndexes & 4095;"),e.push("ivec3 indexPositionV = uniqueVertexIndexes >> 12;"),e.push(`uint solid = ${_(7)}.r;`);const t=e=>`vec3(${A(`ivec2(indexPositionH[${e}], indexPositionV[${e}])`)})`;e.push(`vec3 positions[] = vec3[](${t(0)}, ${t(1)}, ${t(2)});`),e.push("vec3 normal = normalize(cross(positions[2] - positions[0], positions[1] - positions[0]));"),e.push("vec3 position = positions[gl_VertexID % 3];"),g.needed&&e.push(`vec3 worldNormal = -normalize((transpose(inverse(${l} * objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);`),m.needed&&e.push(`vec3 viewNormal = -normalize((transpose(inverse(${c} * objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);`),e.push("if (solid != 1u) {"),e.push(` if (${o=h,`(${o}[2][3] == - 1.0)`}) {`),e.push(` vec3 uCameraEyeRtcInQuantizedSpace = (inverse(${l} * objectDecodeAndInstanceMatrix) * vec4(${u}, 1)).xyz;`),e.push(" if (dot(position.xyz - uCameraEyeRtcInQuantizedSpace, normal) < 0.0) {"),e.push(" position = positions[2 - (gl_VertexID % 3)];"),g.needed&&e.push(" worldNormal = -worldNormal;"),m.needed&&e.push(" viewNormal = -viewNormal;"),e.push(" }"),e.push(" } else {"),m.needed||e.push(` vec3 viewNormal = -normalize((transpose(inverse(${c} * objectDecodeAndInstanceMatrix)) * vec4(normal,1)).xyz);`),e.push(" if (viewNormal.z < 0.0) {"),e.push(" position = positions[2 - (gl_VertexID % 3)];"),g.needed&&e.push(" worldNormal = -worldNormal;"),m.needed&&e.push(" viewNormal = -viewNormal;"),e.push(" }"),e.push(" }"),e.push("}")}else e.push("int indexPositionH = uniqueVertexIndexes[gl_VertexID % 2] & 4095;"),e.push("int indexPositionV = uniqueVertexIndexes[gl_VertexID % 2] >> 12;"),e.push(`vec3 position = vec3(${A("ivec2(indexPositionH, indexPositionV)")});`);var o;p.needed&&e.push(`vec4 pickColor = vec4(${_(1)});`),e.push(`vec4 worldPosition = ${l} * (objectDecodeAndInstanceMatrix * vec4(position, 1.0));`)},layerTypeInputs:{perPrimIndices:s.map,perPrimIdPorIds:r.map,perObjPosDecode:n.map,perVertIdCoords:A.map,perObjColsFlags:o.map,perObjectMatrix:a.map,worldMatrix:l,viewMatrix:c,projMatrix:h,uCameraEyeRtc:u}}},Ir=d.mat4(),Tr=d.mat4();function Pr(e,t,i){const s=e.length,r=new Uint16Array(s),n=t[0],A=t[1],o=t[2],a=t[3]-n,l=t[4]-A,c=t[5]-o,h=65525,u=h/a,f=h/l,p=h/c,g=e=>e>=0?e:0;for(let t=0;t<s;t+=3)r[t+0]=Math.floor(g(e[t+0]-n)*u),r[t+1]=Math.floor(g(e[t+1]-A)*f),r[t+2]=Math.floor(g(e[t+2]-o)*p);return d.identityMat4(Ir),d.translationMat4v(t,Ir),d.identityMat4(Tr),d.scalingMat4v([a/h,l/h,c/h],Tr),d.mulMat4(Ir,Tr,i),r}function Sr(e,t){const i=e[0],s=e[1],r=e[2],n=e[3]-i,A=e[4]-s,o=e[5]-r,a=65525;return d.identityMat4(Ir),d.translationMat4v(e,Ir),d.identityMat4(Tr),d.scalingMat4v([n/a,A/a,o/a],Tr),d.mulMat4(Ir,Tr,t),t}function Dr(e,t,i){let s=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),r=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=s,t=r;e=(1-Math.abs(r))*(s>=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function kr(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}const Qr=new Float32Array(1),Rr=new Float32Array(4),Or=new Float32Array(3),Vr=d.mat4(),Lr=d.vec4([0,0,0,1]),Hr=d.vec4(),Nr=d.vec3(),Gr=d.vec3(),jr=d.vec3(),Wr=d.vec3(),zr=d.vec3(),Xr=d.vec3(),Kr=d.vec3(),Zr=new Uint8Array(4),Jr=new Float32Array(96),Yr=function(e){const t=[];for(let i=0;i<e;++i)t.push(i);return t},$r=function(e,t){e.set(t);let i=t.length;const s=e.length;for(;i<s;){const t=Math.min(i,s-i);e.set(e.subarray(0,t),i),i+=t}},qr=function(){let e=0;const t=new Map;return{acquire:()=>e++,release:()=>{e--,0===e&&t.clear()},getTypeArray:function(e,i){t.has(e)||t.set(e,{});const s=t.get(e);return i in s||(s[i]=new e(i)),s[i]}}}();class en extends dr{constructor(e,t,i,s){super(e,t,i);const r=!!s.geometry;this._maxVerts=s.maxGeometryBatchSize;const n=r?s.geometry.positionsDecodeMatrix:s.positionsDecodeMatrix;this._positionsDecodeMatrix=n&&d.mat4(n),this._cfgUvDecodeMatrix=s.uvDecodeMatrix&&d.mat3(s.uvDecodeMatrix),this._instancedGeometry=s.geometry,this._textureSet=s.textureSet,this._modelAABB=!r&&d.collapseAABB3(),this._portions=[];const A=function(){let e=0;const t=[];return{length:()=>e,append:function(i,s=1,r=1,n=0){e+=s*i.length,t.push({data:i,times:s,denormalizeScale:r,increment:n})},compileBuffer:function(e){let i=0;t.forEach((e=>{i+=e.times*e.data.length}));const s=new e(i);let r=0;return t.forEach((e=>{const t=e.data,i=e.denormalizeScale,n=e.increment,A=s.subarray(r);if(1===i&&0===n)A.set(t);else for(let e=0;e<t.length;++e)A[e]=n+t[e]*i;let o=t.length;const a=e.times*t.length;for(;o<a;){const e=Math.min(o,a-o);A.set(A.subarray(0,e),o),o+=e}r+=o})),s}}};this._buffer={colors:A(),metallicRoughness:A(),pickColors:A(),...r?{modelMatrixCol:[A(),A(),A()],modelNormalMatrixCol:[A(),A(),A()]}:{positions:A(),indices:A(),uv:A(),normals:A(),edgeIndices:A()}}}canCreatePortion(e,t){return this._instancedGeometry||this._buffer.positions.length()+e<=3*this._maxVerts&&this._buffer.indices.length()+t<=3*this._maxVerts}createPortion(e,t){const i=this._buffer,s=this._instancedGeometry,r=this.model,n=this._portions.length,A=this.primitive,o=!!this._positionsDecodeMatrix,a=r.scene,l=t.meshMatrix,c=(s,o,l,c,h)=>{const u=this._portions.length>0&&this._portions[this._portions.length-1],f={indicesBaseIndex:u?u.indicesBaseIndex+u.numIndices:0,numIndices:l?l.length:0,portionBase:s,portionSize:o,retainedGeometry:a.readableGeometryEnabled&&"points"!==A&&"lines"!==A&&{indices:l,quantizedPositions:c,offset:a.entityOffsetsEnabled&&d.vec3(),matrix:h&&h.slice(),inverseMatrix:null,normalMatrix:null}};return"points"!==A&&"lines"!==A&&i.metallicRoughness.append([t.metallic??0,t.roughness??255],o),"lines"!==A&&i.pickColors.append(t.pickColor.slice(0,4),o),this._portions.push(f),r.numPortions++,this._meshes.push(e),n};if(s){if(i.modelMatrixCol.forEach(((e,t)=>e.append([l[t+0],l[t+4],l[t+8],l[t+12]]))),"points"!==A){const e=t.color;i.colors.append([e[0],e[1],e[2],t.opacity??255])}if("points"!==A&&"lines"!==A&&s.normals){const e=d.inverseMat4(d.transposeMat4(l,d.mat4()));i.modelNormalMatrixCol.forEach(((t,i)=>t.append([e[i+0],e[i+4],e[i+8],e[i+12]])))}return c(n,1,s.indices,s.positionsCompressed,l)}{const e=i.positions.length()/3,s=o?t.positionsCompressed:t.positions;if(!s)throw(o?"positionsCompressed":"positions")+" expected";i.positions.append(s);const r=s.length/3,n=t.indices;n&&i.indices.append(n,1,1,e);const a=t.normalsCompressed,h=t.normals;if(a&&a.length>0)i.normals.append(a);else if(h&&h.length>0){const e=Vr;l?(d.transposeMat4(l,e),d.inverseMat4(e,e)):d.identityMat4(e);const t=[];!function(e,t,i,s,r){function n(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}let A,o,a,l,c,h,u=new Float32Array([0,0,0,0]),f=new Float32Array([0,0,0,0]);for(h=0;h<i;h+=3)u[0]=t[h],u[1]=t[h+1],u[2]=t[h+2],d.transformVec3(e,u,f),d.normalizeVec3(f,f),a=A=Dr(f,"floor","floor"),o=kr(A),l=c=n(f,o),A=Dr(f,"ceil","floor"),o=kr(A),l=n(f,o),l>c&&(a=A,c=l),A=Dr(f,"floor","ceil"),o=kr(A),l=n(f,o),l>c&&(a=A,c=l),A=Dr(f,"ceil","ceil"),o=kr(A),l=n(f,o),l>c&&(a=A,c=l),s[r+h+0]=a[0],s[r+h+1]=a[1],s[r+h+2]=0}(e,h,h.length,t,0),i.normals.append(t)}const u=t.colors,f=t.colorsCompressed,p=t.color;if(u)if("points"===A)i.colors.append(u,1,255);else{const e=[];for(let t=0,i=u.length;t<i;t+=3)e.push(255*u[t]),e.push(255*u[t+1]),e.push(255*u[t+2]),e.push(255);i.colors.append(e)}else if(f)if("points"===A)i.colors.append(f);else{const e=[];for(let t=0,i=f.length;t<i;t+=3)e.push(f[t]),e.push(f[t+1]),e.push(f[t+2]),e.push(255);i.colors.append(e)}else p&&i.colors.append([p[0],p[1],p[2],"points"===A?1:t.opacity],r);const g=e=>e&&e.length>0&&e,m=g(t.uv)||g(t.uvCompressed);m&&i.uv.append(m);const _=t.edgeIndices;return _&&i.edgeIndices.append(_,1,1,e),d.expandAABB3(this._modelAABB,t.aabb),c(e,r,n)}}compilePortions(){const e=this._buffer,t=this._instancedGeometry,i=this.model,s=this._modelAABB,r=this.origin,n=this._portions,A=this.primitive,o=this._textureSet;let a=this._positionsDecodeMatrix;const l=this._cfgUvDecodeMatrix,c=i.scene,h=c.canvas.gl,u=!!t,f=[],p=(e,t,i,s)=>{if(t.length>0){const r=t.constructor,[n,A]={[Uint8Array]:[1,h.UNSIGNED_BYTE],[Int8Array]:[1,h.BYTE],[Uint16Array]:[2,h.UNSIGNED_SHORT],[Int16Array]:[2,h.SHORT],[Uint32Array]:[4,h.UNSIGNED_INT],[Int32Array]:[4,h.INT],[Float32Array]:[4,h.FLOAT]}[r],o=h.createBuffer();f.push((()=>h.deleteBuffer(o)));const a=()=>h.bindBuffer(e,o),l=t=>{a(),h.bufferData(e,t,s)};l(t);const c=t.BYTES_PER_ELEMENT,u=t.length/i;return{bindBuffer:a,getData:(t=0,s=u-t)=>{a();const A=new r(s*i);return h.getBufferSubData(e,t*n*i,A,0,s*i),A},numItems:u,setData:l,setSubData:(t,i)=>{a(),h.bufferSubData(e,i*c,t)},type:A}}return null},g=(e,t,i,s=!1,r=!1)=>{const n=p(h.ARRAY_BUFFER,e,t,i);return n&&{getData:n.getData,numItems:n.numItems,setData:n.setData,setSubData:n.setSubData,attributeDivisor:s&&1,bindAtLocation:e=>{n.bindBuffer(),h.vertexAttribPointer(e,t,n.type,!!r,0,0)}}},m=e=>{const t=p(h.ELEMENT_ARRAY_BUFFER,e,1,h.STATIC_DRAW);return t&&{getData:t.getData,bindIndicesBuffer:t.bindBuffer,indicesCount:e.length,indicesType:t.type}},_=n.reduce(((e,t)=>e+t.portionSize),0),b=g(new Float32Array(_),1,h.DYNAMIC_DRAW,u),y=(e,t)=>g(e,4,t,u&&"points"!==A,!0),w=u&&t.colorsCompressed?y(new Uint8Array(t.colorsCompressed),h.STATIC_DRAW):y(e.colors.compileBuffer(Uint8Array),h.DYNAMIC_DRAW),v=c.entityOffsetsEnabled&&g(new Float32Array(3*_),3,h.DYNAMIC_DRAW,u),B=g(e.metallicRoughness.compileBuffer(Uint8Array),2,h.STATIC_DRAW,u),C=g(e.pickColors.compileBuffer(Uint8Array),4,h.STATIC_DRAW,u),M=m(u?new Uint32Array(t.edgeIndices):e.edgeIndices.compileBuffer(Uint32Array)),E=u?"points"!==A&&t.indices&&new Uint32Array(t.indices):e.indices.compileBuffer(Uint32Array),F=E&&m(E),U=u?t.positionsCompressed:a?e.positions.compileBuffer(Uint16Array):Pr(e.positions.compileBuffer(Float64Array),s,a=d.mat4()),x=U&&g(U,3,h.STATIC_DRAW);u||n.forEach((e=>{if(e.retainedGeometry){const t=3*e.portionBase;e.retainedGeometry.quantizedPositions=U.subarray(t,t+3*e.portionSize)}}));const I=u&&e.modelMatrixCol.map((e=>g(e.compileBuffer(Float32Array),4,h.STATIC_DRAW,!0))),T=!u&&e.normals.compileBuffer(Int8Array),P=T&&g(T,3,h.STATIC_DRAW,!1,!0),S=I&&P&&e.modelNormalMatrixCol.map((e=>g(e.compileBuffer(Float32Array),4,h.STATIC_DRAW,!0))),D=u?"points"!==A&&"lines"!==A&&t.uvCompressed&&{buf:g(t.uvCompressed,2,h.STATIC_DRAW),mat:t.uvDecodeMatrix}:function(){const t=e.uv.compileBuffer(Float32Array);if(0===t.length)return null;if(l)return{buf:g(t,2,h.STATIC_DRAW),mat:l};{const e=ge.getUVBounds(t),i=ge.compressUVs(t,e.min,e.max);return{buf:g(i.quantized,2,h.STATIC_DRAW),mat:d.mat3(i.decodeMatrix)}}}();this._buffer=null,qr.acquire(),f.push((()=>qr.release()));let k=null;const Q=(e,i,s,r=!1)=>{hr(i,s,"points"!==A&&"lines"!==A,c,Zr);const o=i&Os?1:0;let a=0;a|=Zr[0],a|=Zr[1]<<4,a|=Zr[2]<<8,a|=Zr[3]<<12,a|=o<<16,Qr[0]=a;const l=n[e],h=l.portionBase,u=l.portionSize;if(r&&!t)k||(k=new Float32Array(_)),$r(k.subarray(h,h+u),Qr);else if(b){const e=qr.getTypeArray(Float32Array,u);$r(e,Qr),b.setSubData(e,h)}},R="solid"===A;return{edgesColorOpaqueAllowed:()=>!0,solid:R,sortId:("points"===A?"Points":"lines"===A?"Lines":"Triangles")+(u?"Instancing":"Batching")+"Layer"+("points"!==A&&"lines"!==A?(R?"-solid":"-surface")+"-autoNormals"+(u?"":(o&&o.colorTexture?"-colorTexture":"")+(o&&o.metallicRoughnessTexture?"-metallicRoughnessTexture":"")):""),setClippableFlags:Q,setFlags:Q,setFlags2:(e,t,i)=>{},setDeferredFlags:()=>{k&&(b.setData(k),k=null)},setColor:(e,t)=>{if(w){const i=n[e],s=qr.getTypeArray(Uint8Array,4*i.portionSize);$r(s,t.slice(0,4)),w.setSubData(s,4*i.portionBase)}},setMatrix:(e,t)=>{I&&I.forEach(((i,s)=>{Rr[0]=t[s+0],Rr[1]=t[s+4],Rr[2]=t[s+8],Rr[3]=t[s+12],i.setSubData(Rr,4*e)}))},setOffset:(e,t)=>{if(c.entityOffsetsEnabled){const i=n[e];if(v){Or.set(t);const e=qr.getTypeArray(Float32Array,3*i.portionSize);$r(e,Or),v.setSubData(e,3*i.portionBase)}i.retainedGeometry&&i.retainedGeometry.offset.set(t)}else i.error("Entity#offset not enabled for this Viewer")},getEachIndex:(e,t)=>{const i=n[e].retainedGeometry;i&&i.indices.forEach((e=>t(e)))},getEachVertex:(e,t)=>{const s=n[e].retainedGeometry;if(s){const e=Hr;r?e.set(r,0):e[0]=e[1]=e[2]=0,e[3]=1;const n=i.matrix;d.mulMat4v4(n,e,e);const A=s.quantizedPositions,o=Lr;for(let i=0,r=A.length;i<r;i+=3)o[0]=A[i],o[1]=A[i+1],o[2]=A[i+2],d.decompressPosition(o,a),s.matrix&&d.transformPoint3(s.matrix,o,o),o[3]=1,d.mulMat4v4(n,o,o),d.addVec3(e,o,o),t(o)}},readGeometryData:"points"!==A&&"lines"!==A&&(e=>{const t=!u&&n[e],s=t?F.getData(t.indicesBaseIndex,t.numIndices).map((e=>e-t.portionBase)):F.getData(),A=i.matrix,o=d.vec4();o.set(r,0),o[3]=1,d.mulMat4v4(A,o,o);const l=I&&d.mat4();if(l){const t=I[0].getData(e,1),i=I[1].getData(e,1),s=I[2].getData(e,1);l.set([t[0],i[0],s[0],0,t[1],i[1],s[1],0,t[2],i[2],s[2],0,t[3],i[3],s[3],1])}const c=d.mat4();d.mulMat4(A,l?d.mulMat4(l,a,c):a,c),c[12]+=o[0],c[13]+=o[1],c[14]+=o[2];const h=t?x.getData(t.portionBase,t.portionSize):x.getData();return{indices:s,positions:d.transformPositions3(c,h,new Float64Array(h.length))}}),precisionRayPickSurface:(e,t,s,A,o)=>{const l=n[e].retainedGeometry;if(l){l.matrix&&!l.inverseMatrix&&(l.inverseMatrix=d.inverseMat4(l.matrix,d.mat4())),o&&l.inverseMatrix&&!l.normalMatrix&&(l.normalMatrix=d.transposeMat4(l.inverseMatrix,d.mat4()));const e=l.quantizedPositions,n=l.indices,c=l.offset,h=Nr,u=Gr;h.set(r?d.subVec3(t,r,jr):t),u.set(s),c&&d.subVec3(h,c),d.transformRay(i.worldNormalMatrix,h,u,h,u),l.inverseMatrix&&d.transformRay(l.inverseMatrix,h,u,h,u);const f=Wr,p=zr,g=Xr;let m=!1,_=0;const b=Kr;for(let s=0,y=n.length;s<y;s+=3){const y=3*n[s],w=3*n[s+1],v=3*n[s+2];if(f[0]=e[y],f[1]=e[y+1],f[2]=e[y+2],p[0]=e[w],p[1]=e[w+1],p[2]=e[w+2],g[0]=e[v],g[1]=e[v+1],g[2]=e[v+2],d.decompressPosition(f,a),d.decompressPosition(p,a),d.decompressPosition(g,a),d.rayTriangleIntersect(h,u,f,p,g,b)){l.matrix&&d.transformPoint3(l.matrix,b,b),d.transformPoint3(i.worldMatrix,b,b),c&&d.addVec3(b,c),r&&d.addVec3(b,r);const e=Math.abs(d.lenVec3(d.subVec3(b,t,[])));(!m||e>_)&&(_=e,A.set(b),o&&d.triangleNormal(f,p,g,o),m=!0)}}return m&&o&&(l.normalMatrix&&d.transformVec3(l.normalMatrix,o,o),d.transformVec3(i.worldNormalMatrix,o,o),d.normalizeVec3(o)),m}return!1},layerTextureSet:o,renderers:ur(c,u?"instancing":"batching",A,i.saoEnabled,i.pbrEnabled&&D&&o&&o.colorTexture&&P&&B&&o.metallicRoughnessTexture,i.colorTextureEnabled&&D&&o&&o.colorTexture,!!P,(e=>sn(e,u&&{hasModelNormalMat:!!S},c.entityOffsetsEnabled))),drawCalls:function(){const e={},t=t=>(s,r,o)=>{let l=0;Jr.set(i.rotationMatrix,0),Jr.set(o.viewMatrix,l+=16),Jr.set(o.projMatrix,l+=16),Jr.set(a,l+=16),r.needNormal()&&(Jr.set(i.worldNormalMatrix,l+=16),Jr.set(o.viewNormalMatrix,l+=16)),r.matrices.setInputValue(Jr),r.uvDecodeMatrix.setInputValue&&r.uvDecodeMatrix.setInputValue(D.mat),s in e||(e[s]=[null,null,null]);const c=e[s],d=t?t.vertices?0:1:2;if(!c[d]){const e=h.createVertexArray();h.bindVertexArray(e);const i=(e,t)=>{e&&e.setInputValue&&t&&e.setInputValue(t)},s=r.attributes;i(s.position,x),i(s.normal,P),i(s.color,w),i(s.pickColor,C),i(s.uV,D&&D.buf),i(s.metallicRoughness,B),i(s.flags,b),i(s.offset,v),s.modelMatrixCol&&s.modelMatrixCol.forEach(((e,t)=>i(e,I[t]))),s.modelNormalMatrixCol&&s.modelNormalMatrixCol.forEach(((e,t)=>i(e,S[t])));const o=function(){const e=()=>{u?h.drawArraysInstanced(h.POINTS,0,x.numItems,n.length):h.drawArrays(h.POINTS,0,x.numItems)},i=(e,t)=>{t.bindIndicesBuffer();const i=t.indicesCount,s=t.indicesType;return()=>{u?h.drawElementsInstanced(e,i,s,0,n.length):h.drawElements(e,i,s,0)}};return"points"===A?e:"lines"===A?t&&t.vertices?e:i(h.LINES,F):t&&t.vertices?e:t&&M?i(h.LINES,M):i(h.TRIANGLES,F)}();h.bindVertexArray(null),f.push((()=>h.deleteVertexArray(e))),c[d]=()=>{h.bindVertexArray(e),o(),h.bindVertexArray(null)}}c[d]()};return{drawVertices:t({vertices:!0}),drawEdges:t({}),drawSurface:t(null)}}(),destroy:()=>{f.forEach((e=>e())),f.length=0}}}}const tn=function(e){const t={toString:()=>(t.needed=!0,e)};return t},sn=function(e,t,i){const s=e.createAttribute,r={position:s("vec3","positionA"),normal:s("vec3","normalA"),color:s("vec4","colorA"),pickColor:s("vec4","pickColor"),uV:s("vec2","uvApremul"),metallicRoughness:s("vec2","metallicRoughness"),flags:s("float","flagsA"),offset:i&&s("vec3","offset"),modelMatrixCol:t&&Yr(3).map((e=>s("vec4","modelMatrixCol"+e))),modelNormalMatrixCol:t&&t.hasModelNormalMat&&Yr(3).map((e=>s("vec4","modelNormalMatrixCol"+e)))},n=tn("aUv"),A=tn("viewNormal"),o=tn("worldNormal"),a=e.createUniform("mat3","uvDecodeMatrix"),l=()=>A.needed||o.needed,c=e.createUniformBlock("Matrices",{worldMatrix:"mat4",viewMatrix:"mat4",projMatrix:"mat4",positionsDecodeMatrix:"mat4",worldNormalMatrix:"mat4",viewNormalMatrix:"mat4"});return{dontCullOnAlphaZero:!0,geometryParameters:{attributes:{clippable:`((int(${r.flags}) >> 16 & 0xF) == 1)`,color:r.color,flags:Yr(4).map((e=>({toString:()=>`(int(${r.flags}) >> ${4*e} & 0xF)`}))),metallicRoughness:r.metallicRoughness,normal:{view:A,world:o},pickColor:r.pickColor,position:{clip:"gl_Position",view:"viewPosition",world:"worldPosition"},uv:n},projMatrix:c.projMatrix,viewMatrix:c.viewMatrix},appendVertexData:t=>{n.needed&&t.push(`vec2 ${n} = (${a} * vec3(${r.uV}, 1.0)).xy;`);const i=r.modelMatrixCol&&`mat4(${r.modelMatrixCol[0]}, ${r.modelMatrixCol[1]}, ${r.modelMatrixCol[2]}, vec4(0.0,0.0,0.0,1.0))`;if(t.push(`vec4 worldPosition = ${c.worldMatrix} * (${c.positionsDecodeMatrix} * vec4(${r.position}, 1.0)${i?" * "+i:""});`),r.offset&&t.push(`worldPosition.xyz = worldPosition.xyz + ${r.offset};`),l()){const i=r.modelNormalMatrixCol&&`* mat4(${r.modelNormalMatrixCol[0]}, ${r.modelNormalMatrixCol[1]}, ${r.modelNormalMatrixCol[2]}, vec4(0.0,0.0,0.0,1.0))`;t.push(`vec4 modelNormal = vec4(${e.commonLibrary.octDecode}(${r.normal}.xy), 0.0)${i||""};`),t.push(`vec3 ${o} = (${c.worldNormalMatrix} * modelNormal).xyz;`),A.needed&&t.push(`vec3 ${A} = normalize((${c.viewNormalMatrix} * vec4(${o}, 0.0)).xyz);`)}},layerTypeInputs:{attributes:r,matrices:c,uvDecodeMatrix:a,needNormal:l}}};class rn{constructor(e){this.id=e.id,this.colorTexture=e.colorTexture,this.alphaCutoff=e.alphaCutoff,this.metallicRoughnessTexture=e.metallicRoughnessTexture,this.normalsTexture=e.normalsTexture,this.emissiveTexture=e.emissiveTexture,this.occlusionTexture=e.occlusionTexture}destroy(){}}class nn{constructor(e){this.id=e.id,this.texture=e.texture}destroy(){this.texture&&(this.texture.destroy(),this.texture=null)}}const An={enabled:!1,files:{},add:function(e,t){!1!==this.enabled&&(this.files[e]=t)},get:function(e){if(!1!==this.enabled)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}};class on{constructor(e,t,i){this.isLoading=!1,this.itemsLoaded=0,this.itemsTotal=0,this.urlModifier=void 0,this.handlers=[],this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=i}itemStart(e){this.itemsTotal++,!1===this.isLoading&&void 0!==this.onStart&&this.onStart(e,this.itemsLoaded,this.itemsTotal),this.isLoading=!0}itemEnd(e){this.itemsLoaded++,void 0!==this.onProgress&&this.onProgress(e,this.itemsLoaded,this.itemsTotal),this.itemsLoaded===this.itemsTotal&&(this.isLoading=!1,void 0!==this.onLoad&&this.onLoad())}itemError(e){void 0!==this.onError&&this.onError(e)}resolveURL(e){return this.urlModifier?this.urlModifier(e):e}setURLModifier(e){return this.urlModifier=e,this}addHandler(e,t){return this.handlers.push(e,t),this}removeHandler(e){const t=this.handlers.indexOf(e);return-1!==t&&this.handlers.splice(t,2),this}getHandler(e){for(let t=0,i=this.handlers.length;t<i;t+=2){const i=this.handlers[t],s=this.handlers[t+1];if(i.global&&(i.lastIndex=0),i.test(e))return s}return null}}const an=new on;class ln{constructor(e){this.manager=void 0!==e?e:an,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){const i=this;return new Promise((function(s,r){i.load(e,s,t,r)}))}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}}const cn={};class hn extends ln{constructor(e){super(e)}load(e,t,i,s){void 0===e&&(e=""),void 0!==this.path&&(e=this.path+e),e=this.manager.resolveURL(e);const r=An.get(e);if(void 0!==r)return this.manager.itemStart(e),I.scheduleTask((()=>{t&&t(r),this.manager.itemEnd(e)}),0),r;if(void 0!==cn[e])return void cn[e].push({onLoad:t,onProgress:i,onError:s});cn[e]=[],cn[e].push({onLoad:t,onProgress:i,onError:s});const n=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),A=this.mimeType,o=this.responseType;fetch(n).then((t=>{if(200===t.status||0===t.status){if(0===t.status&&console.warn("FileLoader: HTTP Status 0 received."),"undefined"==typeof ReadableStream||void 0===t.body.getReader)return t;const i=cn[e],s=t.body.getReader(),r=t.headers.get("Content-Length"),n=r?parseInt(r):0,A=0!==n;let o=0;const a=new ReadableStream({start(e){!function t(){s.read().then((({done:s,value:r})=>{if(s)e.close();else{o+=r.byteLength;const s=new ProgressEvent("progress",{lengthComputable:A,loaded:o,total:n});for(let e=0,t=i.length;e<t;e++){const t=i[e];t.onProgress&&t.onProgress(s)}e.enqueue(r),t()}}))}()}});return new Response(a)}throw Error(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`)})).then((e=>{switch(o){case"arraybuffer":return e.arrayBuffer();case"blob":return e.blob();case"document":return e.text().then((e=>(new DOMParser).parseFromString(e,A)));case"json":return e.json();default:if(void 0===A)return e.text();{const t=/charset="?([^;"\s]*)"?/i.exec(A),i=t&&t[1]?t[1].toLowerCase():void 0,s=new TextDecoder(i);return e.arrayBuffer().then((e=>s.decode(e)))}}})).then((t=>{An.add(e,t);const i=cn[e];delete cn[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onLoad&&s.onLoad(t)}})).catch((t=>{const i=cn[e];if(void 0===i)throw this.manager.itemError(e),t;delete cn[e];for(let e=0,s=i.length;e<s;e++){const s=i[e];s.onError&&s.onError(t)}this.manager.itemError(e)})).finally((()=>{this.manager.itemEnd(e)})),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}}class un{constructor(e=4){this.pool=e,this.queue=[],this.workers=[],this.workersResolve=[],this.workerStatus=0}_initWorker(e){if(!this.workers[e]){const t=this.workerCreator();t.addEventListener("message",this._onMessage.bind(this,e)),this.workers[e]=t}}_getIdleWorker(){for(let e=0;e<this.pool;e++)if(!(this.workerStatus&1<<e))return e;return-1}_onMessage(e,t){const i=this.workersResolve[e];if(i&&i(t),this.queue.length){const{resolve:t,msg:i,transfer:s}=this.queue.shift();this.workersResolve[e]=t,this.workers[e].postMessage(i,s)}else this.workerStatus^=1<<e}setWorkerCreator(e){this.workerCreator=e}setWorkerLimit(e){this.pool=e}postMessage(e,t){return new Promise((i=>{const s=this._getIdleWorker();-1!==s?(this._initWorker(s),this.workerStatus|=1<<s,this.workersResolve[s]=i,this.workers[s].postMessage(e,t)):this.queue.push({resolve:i,msg:e,transfer:t})}))}destroy(){this.workers.forEach((e=>e.terminate())),this.workersResolve.length=0,this.workers.length=0,this.queue.length=0,this.workerStatus=0}}let dn=0;class fn{constructor({viewer:e,transcoderPath:t,workerLimit:i}){this._transcoderPath=t||"https://cdn.jsdelivr.net/npm/@xeokit/xeokit-sdk/dist/basis/",this._transcoderBinary=null,this._transcoderPending=null,this._workerPool=new un,this._workerSourceURL="",i&&this._workerPool.setWorkerLimit(i);const s=e.capabilities;this._workerConfig={astcSupported:s.astcSupported,etc1Supported:s.etc1Supported,etc2Supported:s.etc2Supported,dxtSupported:s.dxtSupported,bptcSupported:s.bptcSupported,pvrtcSupported:s.pvrtcSupported},this._supportedFileTypes=["xkt2"]}_init(){if(!this._transcoderPending){const e=new hn;e.setPath(this._transcoderPath),e.setWithCredentials(this.withCredentials);const t=e.loadAsync("basis_transcoder.js"),i=new hn;i.setPath(this._transcoderPath),i.setResponseType("arraybuffer"),i.setWithCredentials(this.withCredentials);const s=i.loadAsync("basis_transcoder.wasm");this._transcoderPending=Promise.all([t,s]).then((([e,t])=>{const i=fn.BasisWorker.toString(),s=["/* constants */","let _EngineFormat = "+JSON.stringify(fn.EngineFormat),"let _TranscoderFormat = "+JSON.stringify(fn.TranscoderFormat),"let _BasisFormat = "+JSON.stringify(fn.BasisFormat),"/* basis_transcoder.js */",e,"/* worker */",i.substring(i.indexOf("{")+1,i.lastIndexOf("}"))].join("\n");this._workerSourceURL=URL.createObjectURL(new Blob([s])),this._transcoderBinary=t,this._workerPool.setWorkerCreator((()=>{const e=new Worker(this._workerSourceURL),t=this._transcoderBinary.slice(0);return e.postMessage({type:"init",config:this._workerConfig,transcoderBinary:t},[t]),e}))})),dn>0&&console.warn("KTX2TextureTranscoder: Multiple active KTX2TextureTranscoder may cause performance issues. Use a single KTX2TextureTranscoder instance, or call .dispose() on old instances."),dn++}return this._transcoderPending}transcode(e,t,i={}){return new Promise(((s,r)=>{const n=i;this._init().then((()=>this._workerPool.postMessage({type:"transcode",buffers:e,taskConfig:n},e))).then((e=>{const i=e.data,{mipmaps:n,width:A,height:o,format:a,type:l,error:c,dfdTransferFn:h,dfdFlags:u}=i;if("error"===l)return r(c);t.setCompressedData({mipmaps:n,props:{format:a,minFilter:1===n.length?1006:1008,magFilter:1===n.length?1006:1008,encoding:2===h?3001:3e3,premultiplyAlpha:!!(1&u)}}),s()}))}))}destroy(){URL.revokeObjectURL(this._workerSourceURL),this._workerPool.destroy(),dn--}}fn.BasisFormat={ETC1S:0,UASTC_4x4:1},fn.TranscoderFormat={ETC1:0,ETC2:1,BC1:2,BC3:3,BC4:4,BC5:5,BC7_M6_OPAQUE_ONLY:6,BC7_M5:7,PVRTC1_4_RGB:8,PVRTC1_4_RGBA:9,ASTC_4x4:10,ATC_RGB:11,ATC_RGBA_INTERPOLATED_ALPHA:12,RGBA32:13,RGB565:14,BGR565:15,RGBA4444:16},fn.EngineFormat={RGBAFormat:1023,RGBA_ASTC_4x4_Format:37808,RGBA_BPTC_Format:36492,RGBA_ETC2_EAC_Format:37496,RGBA_PVRTC_4BPPV1_Format:35842,RGBA_S3TC_DXT5_Format:33779,RGB_ETC1_Format:36196,RGB_ETC2_Format:37492,RGB_PVRTC_4BPPV1_Format:35840,RGB_S3TC_DXT1_Format:33776},fn.BasisWorker=function(){let e,t,i;const s=_EngineFormat,r=_TranscoderFormat,n=_BasisFormat;self.addEventListener("message",(function(A){const c=A.data;switch(c.type){case"init":e=c.config,h=c.transcoderBinary,t=new Promise((e=>{i={wasmBinary:h,onRuntimeInitialized:e},BASIS(i)})).then((()=>{i.initializeBasis(),void 0===i.KTX2File&&console.warn("KTX2TextureTranscoder: Please update Basis Universal transcoder.")}));break;case"transcode":t.then((()=>{try{const{width:t,height:A,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:f,dfdFlags:p}=function(t){const A=new i.KTX2File(new Uint8Array(t));function c(){A.close(),A.delete()}if(!A.isValid())throw c(),new Error("KTX2TextureTranscoder: Invalid or unsupported .ktx2 file");const h=A.isUASTC()?n.UASTC_4x4:n.ETC1S,u=A.getWidth(),d=A.getHeight(),f=A.getLevels(),p=A.getHasAlpha(),g=A.getDFDTransferFunc(),m=A.getDFDFlags(),{transcoderFormat:_,engineFormat:b}=function(t,i,A,c){let h,u;const d=t===n.ETC1S?o:a;for(let s=0;s<d.length;s++){const r=d[s];if(e[r.if]&&(r.basisFormat.includes(t)&&!(c&&r.transcoderFormat.length<2)&&(!r.needsPowerOfTwo||l(i)&&l(A))))return h=r.transcoderFormat[c?1:0],u=r.engineFormat[c?1:0],{transcoderFormat:h,engineFormat:u}}return console.warn("KTX2TextureTranscoder: No suitable compressed texture format found. Decoding to RGBA32."),h=r.RGBA32,u=s.RGBAFormat,{transcoderFormat:h,engineFormat:u}}(h,u,d,p);if(!u||!d||!f)throw c(),new Error("KTX2TextureTranscoder: Invalid texture");if(!A.startTranscoding())throw c(),new Error("KTX2TextureTranscoder: .startTranscoding failed");const y=[];for(let e=0;e<f;e++){const t=A.getImageLevelInfo(e,0,0),i=t.origWidth,s=t.origHeight,r=new Uint8Array(A.getImageTranscodedSizeInBytes(e,0,0,_));if(!A.transcodeImage(r,e,0,0,_,0,-1,-1))throw c(),new Error("KTX2TextureTranscoder: .transcodeImage failed.");y.push({data:r,width:i,height:s})}return c(),{width:u,height:d,hasAlpha:p,mipmaps:y,format:b,dfdTransferFn:g,dfdFlags:m}}(c.buffers[0]),g=[];for(let e=0;e<u.length;++e)g.push(u[e].data.buffer);self.postMessage({type:"transcode",id:c.id,width:t,height:A,hasAlpha:h,mipmaps:u,format:d,dfdTransferFn:f,dfdFlags:p},g)}catch(e){console.error(`[KTX2TextureTranscoder.BasisWorker]: ${e}`),self.postMessage({type:"error",id:c.id,error:e.message})}}))}var h}));const A=[{if:"astcSupported",basisFormat:[n.UASTC_4x4],transcoderFormat:[r.ASTC_4x4,r.ASTC_4x4],engineFormat:[s.RGBA_ASTC_4x4_Format,s.RGBA_ASTC_4x4_Format],priorityETC1S:1/0,priorityUASTC:1,needsPowerOfTwo:!1},{if:"bptcSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.BC7_M5,r.BC7_M5],engineFormat:[s.RGBA_BPTC_Format,s.RGBA_BPTC_Format],priorityETC1S:3,priorityUASTC:2,needsPowerOfTwo:!1},{if:"dxtSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.BC1,r.BC3],engineFormat:[s.RGB_S3TC_DXT1_Format,s.RGBA_S3TC_DXT5_Format],priorityETC1S:4,priorityUASTC:5,needsPowerOfTwo:!1},{if:"etc2Supported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.ETC1,r.ETC2],engineFormat:[s.RGB_ETC2_Format,s.RGBA_ETC2_EAC_Format],priorityETC1S:1,priorityUASTC:3,needsPowerOfTwo:!1},{if:"etc1Supported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.ETC1],engineFormat:[s.RGB_ETC1_Format],priorityETC1S:2,priorityUASTC:4,needsPowerOfTwo:!1},{if:"pvrtcSupported",basisFormat:[n.ETC1S,n.UASTC_4x4],transcoderFormat:[r.PVRTC1_4_RGB,r.PVRTC1_4_RGBA],engineFormat:[s.RGB_PVRTC_4BPPV1_Format,s.RGBA_PVRTC_4BPPV1_Format],priorityETC1S:5,priorityUASTC:6,needsPowerOfTwo:!0}],o=A.sort((function(e,t){return e.priorityETC1S-t.priorityETC1S})),a=A.sort((function(e,t){return e.priorityUASTC-t.priorityUASTC}));function l(e){return e<=2||0==(e&e-1)&&0!==e}};const pn={};function gn(e){const t=e.scene.id;let i=pn[t];return i||(i=new fn({viewer:e}),pn[t]=i,e.scene.on("destroyed",(()=>{delete pn[t],i.destroy()}))),i}
|
|
8
8
|
/**
|
|
9
9
|
* @author https://github.com/tmarti, with support from https://tribia.com/
|
|
10
10
|
* @license MIT
|
|
@@ -20,7 +20,7 @@ class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){
|
|
|
20
20
|
/**
|
|
21
21
|
* @author https://github.com/tmarti, with support from https://tribia.com/
|
|
22
22
|
* @license MIT
|
|
23
|
-
**/let wn=null;function vn(e,t){const i=3*e,s=3*t;let r,n,A,o,a,l;const c=Math.min(r=wn[i],n=wn[i+1],A=wn[i+2]),h=Math.min(o=wn[s],a=wn[s+1],l=wn[s+2]);if(c!==h)return c-h;const u=Math.max(r,n,A),d=Math.max(o,a,l);return u!==d?u-d:0}let Bn=null;function Cn(e,t){let i=Bn[2*e]-Bn[2*t];return 0!==i?i:Bn[2*e+1]-Bn[2*t+1]}function Mn(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e<t;e++)i[e]=e;wn=new Int32Array(e.length);for(let i=0,s=e.length;i<s;i++)wn[i]=e[i]>>t;i.sort(vn);const s=new Int32Array(e.length);for(let t=0,r=i.length;t<r;t++)s[3*t+0]=e[3*i[t]+0],s[3*t+1]=e[3*i[t]+1],s[3*t+2]=e[3*i[t]+2];return s}(e.indices||[],t),n=function(e){if(0===(e||[]).length)return[];let t=new Int32Array(e.length/2);for(let e=0,i=t.length;e<i;e++)t[e]=e;for(let t=0,i=e.length;t<i;t+=2)if(e[t]>e[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}Bn=new Int32Array(e),t.sort(Cn);const i=new Int32Array(e.length);for(let s=0,r=t.length;s<r;s++)i[2*s+0]=e[2*t[s]+0],i[2*s+1]=e[2*t[s]+1];return i}(e.edgeIndices||[]);function A(e,t){if(e>t){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(n.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(n[2*e],n[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const o=new Int32Array(n.length/2);o.fill(0);const a=s.length/3;if(a>8*(1<<t))return[e];const l=new Int32Array(a);l.fill(-1);const c=[];function h(){l.fill(-1);const e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:c.length};return c.push(e),e}let u=h();for(let t=0,i=r.length;t<i;t+=3){let i=0;const a=r[t],c=r[t+1],d=r[t+2];if(-1===l[a]&&i++,-1===l[c]&&i++,-1===l[d]&&i++,i+u.numPositions>u.maxNumPositions&&(u=h()),u.bucketNumber>8)return[e];let f;-1===l[a]&&(l[a]=u.numPositions++,u.positionsCompressed.push(s[3*a]),u.positionsCompressed.push(s[3*a+1]),u.positionsCompressed.push(s[3*a+2])),-1===l[c]&&(l[c]=u.numPositions++,u.positionsCompressed.push(s[3*c]),u.positionsCompressed.push(s[3*c+1]),u.positionsCompressed.push(s[3*c+2])),-1===l[d]&&(l[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(l[a]),u.indices.push(l[c]),u.indices.push(l[d]),(f=A(a,c))>=0&&0===o[f]&&(o[f]=1,u.edgeIndices.push(l[n[2*f]]),u.edgeIndices.push(l[n[2*f+1]])),(f=A(a,d))>=0&&0===o[f]&&(o[f]=1,u.edgeIndices.push(l[n[2*f]]),u.edgeIndices.push(l[n[2*f+1]])),(f=A(c,d))>=0&&0===o[f]&&(o[f]=1,u.edgeIndices.push(l[n[2*f]]),u.edgeIndices.push(l[n[2*f+1]]))}const d=t/8*2,f=t/8,p=2*s.length+(r.length+n.length)*d;let g=0,m=-s.length/3;return c.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*f,m+=e.positionsCompressed.length/3})),g>p?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,n=e.edgeIndices,A=e.positionsCompressed;for(let e=0,s=t.length;e<s;e+=3){const s=A[3*t[e]]+"_"+A[3*t[e]+1]+"_"+A[3*t[e]+2]+"/"+A[3*t[e+1]]+"_"+A[3*t[e+1]+1]+"_"+A[3*t[e+1]+2]+"/"+A[3*t[e+2]]+"_"+A[3*t[e+2]+1]+"_"+A[3*t[e+2]+2];i[s]=!0}r+=e.edgeIndices.length/2;for(let e=0,t=n.length;e<t;e+=2){const t=A[3*n[e]]+"_"+A[3*n[e]+1]+"_"+A[3*n[e]+2]+"/"+A[3*n[e+1]]+"_"+A[3*n[e+1]+1]+"_"+A[3*n[e+1]+2]+"/";s[t]=!0}}));{const e=t.indices;t.edgeIndices;const s=t.positionsCompressed;for(let t=0,r=e.length;t<r;t+=3){const r=s[3*e[t]]+"_"+s[3*e[t]+1]+"_"+s[3*e[t]+2]+"/"+s[3*e[t+1]]+"_"+s[3*e[t+1]+1]+"_"+s[3*e[t+1]+2]+"/"+s[3*e[t+2]]+"_"+s[3*e[t+2]+1]+"_"+s[3*e[t+2]+2];if(!(r in i))throw console.log("Not found "+r),"Ohhhh!"}}}(c,e),c)}const En=new Float32Array([0,0,0]),Fn=new Uint16Array([0,0,0]);d.OBB3();class Un{constructor(e,t,i,s,r,n){this._isObject=t,this.scene=e.scene,this.model=e,this.isSceneModelEntity=!0,this.meshes=s,this._numPrimitives=0,this._capMaterial=null;for(let e=0,t=this.meshes.length;e<t;e++){const t=this.meshes[e];t.parent=this,t.entity=this,this._numPrimitives+=t.numPrimitives}this.id=i,this.originalSystemId=d.unglobalizeObjectId(e.id,i),this._flags=r,this._aabb=d.AABB3(),this._aabbDirty=!0,this._offset=d.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!n,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&e.scene._registerObject(this)}_transformDirty(){this._aabbDirty=!0,this.model._transformDirty()}_sceneModelDirty(){this._aabbDirty=!0;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._sceneModelDirty()}get aabb(){if(this._aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this.meshes.length;e<t;e++)d.expandAABB3(this._aabb,this.meshes[e].aabb);this._aabbDirty=!1}return this._aabb}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get numPrimitives(){return this._numPrimitives}get numTriangles(){return this._numPrimitives}get visible(){return this._getFlag(ks)}set visible(e){if(!!(this._flags&ks)!==e){this._flags=e?this._flags|ks:this._flags&~ks;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}get highlighted(){return this._getFlag(Hs)}set highlighted(e){if(!!(this._flags&Hs)!==e){this._flags=e?this._flags|Hs:this._flags&~Hs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}get xrayed(){return this._getFlag(Ls)}set xrayed(e){if(!!(this._flags&Ls)!==e){this._flags=e?this._flags|Ls:this._flags&~Ls;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}get selected(){return this._getFlag(Ns)}set selected(e){if(!!(this._flags&Ns)!==e){this._flags=e?this._flags|Ns:this._flags&~Ns;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}get edges(){return this._getFlag(Gs)}set edges(e){if(!!(this._flags&Gs)!==e){this._flags=e?this._flags|Gs:this._flags&~Gs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get culledVFC(){return!!this._culledVFC}set culledVFC(e){this._culledVFC=e,this._setCulled()}get culledLOD(){return!!this._culledLOD}set culledLOD(e){this._culledLOD=e,this._setCulled()}get culled(){return!!this._culled}set culled(e){this._culled=e,this._setCulled()}_setCulled(){let e=!!this._culled||!(!this._culledLOD||!this._lodCullable)||!!this._culledVFC;if(!!(this._flags&Qs)!==e){this._flags=e?this._flags|Qs:this._flags&~Qs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(Os)}set clippable(e){if(!!(this._flags&Os)!==e){this._flags=e?this._flags|Os:this._flags&~Os;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(Vs)}set collidable(e){if(!!(this._flags&Vs)!==e){this._flags=e?this._flags|Vs:this._flags&~Vs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(Rs)}set pickable(e){if(!!(this._flags&Rs)!==e){this._flags=e?this._flags|Rs:this._flags&~Rs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return En[0]=e[0]/255,En[1]=e[1]/255,En[2]=e[2]/255,En}set colorize(e){if(e){Fn[0]=Math.floor(255*e[0]),Fn[1]=Math.floor(255*e[1]),Fn[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(Fn)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t),this._colorizeUpdated=t}this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(s,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}get offset(){return this._offset}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._aabbDirty=!0,this.model._aabbDirty=!0,this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model.glRedraw()}get saoEnabled(){return this.model.saoEnabled}set capMaterial(e){this.scene.readableGeometryEnabled&&(this._capMaterial=e instanceof Vi?e:null,this.scene._capMaterialUpdated(this.id,this.model.id))}get capMaterial(){return this._capMaterial}getEachVertex(e){for(let t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachVertex(e)}getEachIndex(e){for(let t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachIndex(e)}getGeometryData(){let e=0;const t=[],i=[];for(let s=0,r=this.meshes.length;s<r;s++){const r=this.meshes[s];if(r.layer.readGeometryData){const s=r.layer.readGeometryData(r.portionId);for(let t=0,r=s.indices.length;t<r;t++)i.push(s.indices[t]+e);for(let e=0,i=s.positions.length;e<i;e++)t.push(s.positions[e]);e+=s.positions.length/3}}return{indices:i,positions:t}}get volume(){let e=0;for(let t=0,i=this.meshes.length;t<i;t++){const i=this.meshes[t].volume;if(i<0)return-1;e+=i}return e}get surfaceArea(){let e=0;for(let t=0,i=this.meshes.length;t<i;t++){const i=this.meshes[t].surfaceArea;i>=0&&(e+=i)}return e>0?e:-1}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_finalize2(){for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._deRegisterVisibleObject(this),this.xrayed&&e._deRegisterXRayedObject(this),this.selected&&e._deRegisterSelectedObject(this),this.highlighted&&e._deRegisterHighlightedObject(this),this._colorizeUpdated&&this.scene._deRegisterColorizedObject(this),this._opacityUpdated&&this.scene._deRegisterOpacityObject(this),!this._offset||0===this._offset[0]&&0===this._offset[1]&&0===this._offset[2]||this.scene._deRegisterOffsetObject(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const xn=d.vec4(4),In=d.vec4(),Tn=d.vec4(),Pn=d.vec3([1,0,0]),Sn=d.vec3([0,1,0]),Dn=d.vec3([0,0,1]);d.vec3(3),d.vec3(3);const kn=d.identityMat4();class Qn{constructor(e){this._model=e.model,this.id=e.id,this._parentTransform=e.parent,this._childTransforms=[],this._meshes=[],this._scale=new Float32Array([1,1,1]),this._quaternion=d.identityQuaternion(new Float32Array(4)),this._rotation=new Float32Array(3),this._position=new Float32Array(3),this._localMatrix=d.identityMat4(new Float32Array(16)),this._worldMatrix=d.identityMat4(new Float32Array(16)),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,e.matrix?this.matrix=e.matrix:(this.scale=e.scale,this.position=e.position,e.quaternion||(this.rotation=e.rotation)),e.parent&&e.parent._addChildTransform(this)}_addChildTransform(e){this._childTransforms.push(e),e._parentTransform=this,e._transformDirty(),e._setSubtreeAABBsDirty(this)}_addMesh(e){this._meshes.push(e),e.transform=this}get parentTransform(){return this._parentTransform}get meshes(){return this._meshes}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._model.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._model.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._model.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._model.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=d.identityMat4()),this._localMatrix.set(e||kn),d.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._transformDirty(),this._model.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=d.identityMat4()),d.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return xn[0]=e[0],xn[1]=e[1],xn[2]=e[2],xn[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(xn,In),d.mulQuaternions(this.quaternion,In,Tn),this.quaternion=Tn,this._setLocalMatrixDirty(),this._model.glRedraw(),this}rotateOnWorldAxis(e,t){return xn[0]=e[0],xn[1]=e[1],xn[2]=e[2],xn[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(xn,In),d.mulQuaternions(In,this.quaternion,In),this}rotateX(e){return this.rotate(Pn,e)}rotateY(e){return this.rotate(Sn,e)}rotateZ(e){return this.rotate(Dn,e)}translate(e){return this._position[0]+=e[0],this._position[1]+=e[1],this._position[2]+=e[2],this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateX(e){return this._position[0]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateY(e){return this._position[1]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateZ(e){return this._position[2]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._transformDirty()}_transformDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._childTransforms.length;e<t;e++){const t=this._childTransforms[e];if(t._transformDirty(),t._meshes&&t._meshes.length>0){const e=t._meshes;for(let t=0,i=e.length;t<i;t++)e[t]._transformDirty()}}if(this._meshes&&this._meshes.length>0){const e=this._meshes;for(let t=0,i=e.length;t<i;t++)e[t]._transformDirty()}}_buildWorldMatrix(){const e=this.matrix;if(this._parentTransform)d.mulMat4(this._parentTransform.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._childTransforms)for(let t=0,i=e._childTransforms.length;t<i;t++)this._setSubtreeAABBsDirty(e._childTransforms[t])}}const Rn=d.vec3(),On=d.OBB3(),Vn=d.vec4(),Ln=d.vec3([1,1,1]),Hn=d.vec3([0,0,0]);d.vec3([0,0,0]);const Nn=d.identityQuaternion(),Gn=d.identityMat4(),jn=new Uint8Array([255,255,255]);class Wn extends D{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!1,this._textureTranscoder=t.textureTranscoder||gn(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize??5e6,this._aabb=d.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboLayers={},this._dtxLayers={},this._meshList=[],this.layerList=[],this._layersToFinalize=[],this._entityList=[],this._entitiesToFinalize=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._transforms={},this._meshes={},this._unusedMeshes={},this._entities={},this.renderFlags=new Bi,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._layersFinalized=!1,this._edgeThreshold=t.edgeThreshold||10,this._origin=d.vec3(t.origin||[0,0,0]),this._position=d.vec3(t.position||[0,0,0]),this._rotation=d.vec3(t.rotation||[0,0,0]),this._quaternion=d.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=d.vec4(t.quaternion||[0,0,0,1]),t.rotation&&d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=d.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=d.mat4(),this._worldRotationMatrixConjugate=d.mat4(),this._matrix=d.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=d.mat4(),d.inverseMat4(this._matrix,this._worldNormalMatrix),d.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=d.mat4(),this._viewNormalMatrix=d.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()}));const i=(e,t)=>this._textures[e]=new nn({id:e,texture:new zi({gl:this.scene.canvas.gl,preloadColor:t})});this._textureSets.defaultTextureSet=new rn({id:"defaultTextureSet",colorTexture:i("defaultColorTexture",[1,1,1,1]),metallicRoughnessTexture:i("defaultMetalRoughTexture",[0,1,1,1]),normalsTexture:i("defaultNormalsTexture",[0,0,0,0]),emissiveTexture:i("defaultEmissiveTexture",[0,0,0,1]),occlusionTexture:i("defaultOcclusionTexture",[1,1,1,1])}),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||Gn),d.decomposeMat4(this._matrix,this._position,this._quaternion,this._scale),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._conjugateQuaternion,this._worldRotationMatrixConjugate),d.scaleMat4v(this._scale,this._worldRotationMatrix),d.scaleMat4v(this._scale,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._viewMatrixDirty=!0)}get rotationMatrixConjugate(){return this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._sceneModelDirty()}get worldMatrix(){return this.matrix}get worldNormalMatrix(){return this._worldNormalMatrix}_rebuildViewMatrices(){this._rebuildMatrices(),this._viewMatrixDirty&&(d.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),d.inverseMat4(this._viewMatrix,this._viewNormalMatrix),d.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1)}get viewMatrix(){return this._viewMatrix?(this._rebuildViewMatrices(),this._viewMatrix):this.scene.camera.viewMatrix}get viewNormalMatrix(){return this._viewNormalMatrix?(this._rebuildViewMatrices(),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}get backfaces(){return this._backfaces}set backfaces(e){e=!!e,this._backfaces=e,this.glRedraw()}get entityList(){return this._entityList}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return!1}get aabb(){if(this._aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._entityList.length;e<t;e++)d.expandAABB3(this._aabb,this._entityList[e].aabb);this._aabbDirty=!1}return this._aabb}get numTriangles(){return this._numTriangles}get numLines(){return this._numLines}get numPoints(){return this._numPoints}get visible(){return this.numVisibleLayerPortions>0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].visible=e;this.glRedraw()}get xrayed(){return this.numXRayedLayerPortions>0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].xrayed=e;this.glRedraw()}get highlighted(){return this.numHighlightedLayerPortions>0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].highlighted=e;this.glRedraw()}get selected(){return this.numSelectedLayerPortions>0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].selected=e;this.glRedraw()}get edges(){return this.numEdgesLayerPortions>0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].edges=e;this.glRedraw()}get culled(){return this._culled}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].culled=e;this.glRedraw()}get clippable(){return this._clippable}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].clippable=e;this.glRedraw()}get collidable(){return this._collidable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].collidable=e}get pickable(){return this.numPickableLayerPortions>0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].pickable=e}get colorize(){return this._colorize}set colorize(e){this._colorize=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].colorize=e}get opacity(){return this._opacity}set opacity(e){this._opacity=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].opacity=e}get castsShadow(){return this._castsShadow}set castsShadow(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}get receivesShadow(){return this._receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}get saoEnabled(){return this._saoEnabled}get pbrEnabled(){return this._pbrEnabled}get colorTextureEnabled(){return this._colorTextureEnabled}get isDrawable(){return!0}get isStateSortable(){return!1}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}createQuantizationRange(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:Sr(e.aabb,d.mat4())}:this.error("[createQuantizationRange] Config missing: id")}_createDefaultIndices(e){const t=[];for(let i=0;i<e;i++)t.push(i);return t}createGeometry(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.indices=this._createDefaultIndices((e.positions||e.positionsCompressed).length/3)),!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`[createGeometry] Param expected: indices (required for '${e.primitive}' primitive type)`),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Sr(e.positionsDecodeBoundary,d.mat4())),e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=Pr(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed),d.expandAABB3Points3(t,e.positionsCompressed),ge.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}else if(e.buckets){const t=d.collapseAABB3();this._dtxBuckets[e.id]=e.buckets;for(let i=0,s=e.buckets.length;i<s;i++){const s=e.buckets[i];s.positions?d.expandAABB3Points3(t,s.positions):s.positionsCompressed&&d.expandAABB3Points3(t,s.positionsCompressed)}e.positionsDecodeMatrix&&ge.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e<s;e++)i[e]=255*t[e];e.colorsCompressed=i}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=le(e.positions,e.indices,null,5):e.edgeIndices=le(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.uv){const t=ge.getUVBounds(e.uv),i=ge.compressUVs(e.uv,t.min,t.max);e.uvCompressed=i.quantized,e.uvDecodeMatrix=i.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error(`[createGeometry] Unsupported value for 'primitive': '${e.primitive}' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'.`);else this.error("[createGeometry] Config missing: id")}createTexture(e){const t=e.id;if(null==t)return void this.error("[createTexture] Config missing: id");if(this._textures[t])return void this.error("[createTexture] Texture already created: "+t);if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;let i=e.minFilter||1008;1006!==i&&1007!==i&&1008!==i&&1005!==i&&1004!==i&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),i=1008);let s=e.magFilter||1006;1006!==s&&1003!==s&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),s=1006);let r=e.wrapS||1e3;1001!==r&&1002!==r&&1e3!==r&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),r=1e3);let n=e.wrapT||1e3;1001!==n&&1002!==n&&1e3!==n&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),n=1e3);let A=e.wrapR||1e3;1001!==A&&1002!==A&&1e3!==A&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),A=1e3);let o=e.encoding||3e3;3e3!==o&&3001!==o&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),o=3e3);const a=new zi({gl:this.scene.canvas.gl,minFilter:i,magFilter:s,wrapS:r,wrapT:n,wrapR:A,encoding:o});if(e.preloadColor&&a.setPreloadColor(e.preloadColor),e.image){const t=e.image;if(t.crossOrigin="Anonymous",t.compressed){const e=t.data;a.setCompressedData({mipmaps:e,props:{format:e[0].format,minFilter:i,magFilter:s}})}else a.setImage(t,{minFilter:i,magFilter:s,wrapS:r,wrapT:n,wrapR:A,flipY:e.flipY,encoding:o})}else if(e.src){const t=e.src.split(".").pop();switch(t){case"jpeg":case"jpg":case"png":case"gif":const l=new Image;l.onload=()=>{a.setImage(l,{minFilter:i,magFilter:s,wrapS:r,wrapT:n,wrapR:A,flipY:e.flipY,encoding:o}),this.glRedraw()},l.src=e.src;break;default:this._textureTranscoder?w.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],a).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,a).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new nn({id:t,texture:a})}createTextureSet(e){const t=e.id;if(null==t)return this.error("[createTextureSet] Config missing: id"),!1;if(this._textureSets[t])return this.error(`[createTextureSet] Texture set already created: ${t}`),!1;const i=(e,t)=>{const i=e??t;if(i in this._textures)return this._textures[i];throw e};try{const s=new rn({id:t,model:this,alphaCutoff:e.alphaCutoff,colorTexture:i(e.colorTextureId,"defaultColorTexture"),metallicRoughnessTexture:i(e.metallicRoughnessTextureId,"defaultMetalRoughTexture"),normalsTexture:i(e.normalsTextureId,"defaultNormalsTexture"),emissiveTexture:i(e.emissiveTextureId,"defaultEmissiveTexture"),occlusionTexture:i(e.occlusionTextureId,"defaultOcclusionTexture")});return this._textureSets[t]=s,s}catch(e){return this.error(`[createTextureSet] Texture not found: ${e} - ensure that you create it first with createTexture()`),!1}}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new Qn({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;const t=e.geometryId,i=void 0!==t;if(i){if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)"),!1;if(e.geometry=this._geometries[t],!e.geometry)return this.error(`[createMesh] Geometry not found: ${t} - ensure that you create it first with createGeometry()`),!1}else e.primitive??="triangles";const s=i?e.geometry.primitive:e.primitive,r="triangles"===s||"solid"===s||"surface"===s,n=e.textureSetId,A=this._dtxEnabled&&r&&!n;if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,i){e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.aabb=d.AABB3(e.geometry.aabb);const t=e.transformId;if(t){if(e.transform=this._transforms[t],!e.transform)return this.error(`[createMesh] Transform not found: ${t} - ensure that you create it first with createTransform()`),!1}else if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Ln,i=e.position||Hn,s=e.rotation?d.eulerToQuaternion(e.rotation,"XYZ",Vn):e.quaternion||Nn;e.meshMatrix=d.composeMat4(i,s,t,d.mat4())}}else{if("points"!==s&&"lines"!==s&&"triangles"!==s&&"solid"!==s&&"surface"!==s)return this.error(`Unsupported value for 'primitive': '${s}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!e.buckets&&!e.indices)if(r)e.indices=this._createDefaultIndices((e.positions||e.positionsCompressed).length/3);else if("lines"===s)return this.error(`Param expected: indices (required for '${s}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Ln,i=e.position||Hn,s=e.rotation?d.eulerToQuaternion(e.rotation,"XYZ",Vn):e.quaternion||Nn;e.meshMatrix=d.composeMat4(i,s,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Sr(e.positionsDecodeBoundary,d.mat4())),e.positions){const t=[];$e(e.positions,t,Rn)&&(e.positions=t,e.origin=d.addVec3(e.origin,Rn,d.vec3()));const i=d.collapseAABB3();A?(e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(i,e.positions),e.positionsCompressed=Pr(e.positions,i,e.positionsDecodeMatrix)):(e.meshMatrix&&(d.transformPositions3(e.meshMatrix,e.positions,e.positions),e.meshMatrix=null),d.expandAABB3Points3(i,e.positions)),e.aabb=i}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),ge.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(A&&e.buckets){const t=d.collapseAABB3();e.buckets.forEach((e=>{const i=e.positions||e.positionsCompressed;i&&d.expandAABB3Points3(t,i)})),e.positionsDecodeMatrix&&ge.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}r&&!e.buckets&&(e.edgeIndices||=le(e.positions||e.positionsCompressed,e.indices,e.positions?null:e.positionsDecodeMatrix,2))}if(e.meshMatrix&&(d.AABB3ToOBB3(e.aabb,On),d.transformOBB3(e.meshMatrix,On,On),d.OBB3ToAABB3(On,e.aabb)),e.color=e.color?new Uint8Array(e.color.slice(0,3).map((e=>Math.floor(255*e)))):jn,e.opacity=Math.floor(255*(e.opacity??1)),A)e.type=2,i&&(e.buckets=this._dtxBuckets[t]),e.buckets||(e.buckets=function(e,t,i){let s,r,n,A;t||i?[s,r,n]=yn({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}):(s=e.positionsCompressed,r=e.indices,n=e.edgeIndices);if(i){A=Mn({positionsCompressed:s,indices:r,edgeIndices:n},s.length/3>65536?16:8)}else A=[{positionsCompressed:s,indices:r,edgeIndices:n}];return A}(i?e.geometry:e,this._enableVertexWelding,this._enableIndexBucketing),i&&(this._dtxBuckets[t]=e.buckets));else if(e.type=i?0:1,e.metallic=Math.floor(255*(e.metallic??0)),e.roughness=Math.floor(255*(e.roughness??1)),n&&(e.textureSet=this._textureSets[n],!i&&!e.textureSet))return this.error(`[createMesh] Texture set not found: ${n} - ensure that you create it first with createTextureSet()`),!1;e.numPrimitives=this._getNumPrimitives(e);const o=new Ds(this,e.id,e.color,e.opacity,e.transform,e.textureSet),a=this.scene._renderer.getPickID(o);return o.pickId=a,o.origin=d.vec3(e.origin),o.layer=2===e.type?this._getDTXLayer(e):this._getVBOLayer(0===e.type,e),o.aabb=e.aabb,e.pickColor=new Uint8Array([255&a,a>>8&255,a>>16&255,a>>24&255]),e.solid="solid"===e.primitive,e.meshMatrix=e.transform?e.transform.worldMatrix:e.meshMatrix,o.portionId=o.layer.createPortion(o,e),o.numPrimitives=e.numPrimitives,this._meshes[e.id]=o,this._unusedMeshes[e.id]=o,this._meshList.push(o),o}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].positionsCompressed.length;break;case 1:t+=e.positions?e.positions.length:e.positionsCompressed.length;break;case 0:const i=e.geometry;t+=i.positions?i.positions.length:i.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}_getDTXLayer(e){const t=e.origin,i=e.geometry?e.geometry.primitive:e.primitive,s=`.${i}.${Math.round(t[0])}.${Math.round(t[1])}.${Math.round(t[2])}`;let r=this._dtxLayers[s];if(r){if(r.canCreatePortion(e))return r;delete this._dtxLayers[s],r=null}switch(i){case"triangles":case"solid":case"surface":r=new Fr(this,i,t);break;default:return}return this._dtxLayers[s]=r,this.layerList.push(r),this._layersToFinalize.push(r),r}_getVBOLayer(e,t){const i=e&&t.geometry,s=e?i.primitive:t.primitive,r=t.origin,n=!e&&(t.positionsDecodeMatrix||t.positionsDecodeBoundary),A=n?(JSON.stringify(n).split("").reduce(((e,t)=>(e<<5)-e+t.charCodeAt(0)|0),0)>>>0).toString(16):"-",o=t.textureSetId||"-",a=e?t.geometryId:"-",l=(e?"instancing":"batching")+`.${Math.round(r[0])}.${Math.round(r[1])}.${Math.round(r[2])}.${s}.${A}.${o}.${a}`;if(!e&&l in this._vboLayers){const e=this._vboLayers[l],i=t.positionsCompressed?t.positionsCompressed.length:t.positions.length;e.canCreatePortion(i,"points"===s?0:t.indices.length)||(e.finalize(),delete this._vboLayers[l])}if(!(l in this._vboLayers)){const n=new en(this,s,r,{textureSet:t.textureSet,...e?{geometry:i}:{maxGeometryBatchSize:this._maxGeometryBatchSize,positionsDecodeMatrix:t.positionsDecodeMatrix,uvDecodeMatrix:t.uvDecodeMatrix}});this.layerList.push(n),this._layersToFinalize.push(n),this._vboLayers[l]=n}return this._vboLayers[l]}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return this.error("Config missing: meshIds"),null;const t=e=>!1!==e;let i=0;i|=this._visible&&t(e.visible)&&ks,i|=this._pickable&&t(e.pickable)&&Rs,i|=this._culled&&t(e.culled)&&Qs,i|=this._clippable&&t(e.clippable)&&Os,i|=this._collidable&&t(e.collidable)&&Vs,i|=this._xrayed&&t(e.xrayed)&&Ls,i|=this._highlighted&&t(e.highlighted)&&Hs,i|=this._selected&&t(e.selected)&&Ns,i|=this._edges&&t(e.edges)&&Gs,e.flags=i;let s=[];for(let t=0,i=e.meshIds.length;t<i;t++){const i=e.meshIds[t];let r=this._meshes[i];r?r.parent?this.error(`Mesh with ID "${i}" already belongs to object with ID "${r.parent.id}" - ignoring this mesh`):(s.push(r),delete this._unusedMeshes[i]):this.error(`Mesh with this ID not found: "${i}" - ignoring this mesh`)}const r=new Un(this,e.isObject,e.id,s,e.flags,!0);return this._entityList.push(r),this._entities[e.id]=r,this._entitiesToFinalize.push(r),this.numEntities++,r}preFinalize(){if(this.destroyed)return!1;if(0===this._layersToFinalize.length)return!1;this._createDummyEntityForUnusedMeshes();for(let e=0,t=this._layersToFinalize.length;e<t;e++){this._layersToFinalize[e].finalize()}this._vboLayers={},this._dtxLayers={},this._layersToFinalize=[];for(let e=0,t=this._entitiesToFinalize.length;e<t;e++){this._entitiesToFinalize[e]._finalize()}for(let e=0,t=this._entitiesToFinalize.length;e<t;e++){this._entitiesToFinalize[e]._finalize2()}this._entitiesToFinalize=[],this.scene._aabbDirty=!0,this._viewMatrixDirty=!0,this._matrixDirty=!0,this._aabbDirty=!0,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.position=this._position,this.layerList.sort(((e,t)=>e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0));for(let e=0,t=this.layerList.length;e<t;e++){this.layerList[e].layerIndex=e}this.glRedraw(),this._layersFinalized=!0}finalize(){this.destroyed||(this.preFinalize(),this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={})}stateSortCompare(e,t){}rebuildRenderFlags(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t<i;t++){const i=this.layerList[t];this._getActiveSectionPlanesForLayer(i)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}_createDummyEntityForUnusedMeshes(){const e=Object.keys(this._unusedMeshes);if(e.length>0){const t=`${this.id}-${d.createUUID()}`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e<s;e++){i[e].active?(t.sectionPlanesActivePerLayer[r+e]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[r+e]=!1}return!0}_updateRenderFlags(){if(0===this.numVisibleLayerPortions)return;if(this.numCulledLayerPortions===this.numPortions)return;const e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}_withEachVisibleLayer(e,t){if(e&&0===this.numVisibleLayerPortions)return;const i=this.renderFlags;for(let e=0,s=i.visibleLayers.length;e<s;e++){const s=i.visibleLayers[e];t(this.layerList[s])}}drawColorOpaque(e){this._withEachVisibleLayer(!1,(t=>t.drawColorOpaque(this.renderFlags,e)))}drawColorTransparent(e){this._withEachVisibleLayer(!1,(t=>t.drawColorTransparent(this.renderFlags,e)))}drawDepth(e){this._withEachVisibleLayer(!1,(t=>t.drawDepth(this.renderFlags,e)))}drawSilhouetteXRayed(e){this._withEachVisibleLayer(!1,(t=>t.drawSilhouetteXRayed(this.renderFlags,e)))}drawSilhouetteHighlighted(e){this._withEachVisibleLayer(!1,(t=>t.drawSilhouetteHighlighted(this.renderFlags,e)))}drawSilhouetteSelected(e){this._withEachVisibleLayer(!1,(t=>t.drawSilhouetteSelected(this.renderFlags,e)))}drawEdgesColorOpaque(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesColorOpaque(this.renderFlags,e)))}drawEdgesColorTransparent(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesColorTransparent(this.renderFlags,e)))}drawEdgesXRayed(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesXRayed(this.renderFlags,e)))}drawEdgesHighlighted(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesHighlighted(this.renderFlags,e)))}drawEdgesSelected(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesSelected(this.renderFlags,e)))}drawOcclusion(e){this._withEachVisibleLayer(!0,(t=>t.drawOcclusion(this.renderFlags,e)))}drawShadow(e){this._withEachVisibleLayer(!0,(t=>t.drawShadow(this.renderFlags,e)))}drawPickMesh(e){this._withEachVisibleLayer(!0,(t=>t.drawPickMesh(this.renderFlags,e)))}drawPickDepths(e){this._withEachVisibleLayer(!0,(t=>t.drawPickDepths(this.renderFlags,e)))}drawPickNormals(e){this._withEachVisibleLayer(!0,(t=>t.drawPickNormals(this.renderFlags,e)))}_drawSnap(e,t){this._withEachVisibleLayer(!0,(i=>i.drawSnap(this.renderFlags,e,t)))}drawSnapInit(e){this._drawSnap(e,!0)}drawSnap(e){this._drawSnap(e,!1)}destroy(){Object.values(this._vboLayers).forEach((e=>e.destroy())),this._vboLayers={},this.scene.camera.off(this._onCameraViewMatrix),this.scene.off(this._onTick);for(let e=0,t=this.layerList.length;e<t;e++)this.layerList[e].destroy();this.layerList=[];for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._destroy();this._layersToFinalize=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),super.destroy()}}class zn extends D{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e<t;e+=2)this._indices.push(e),this._indices.push(e+1)}this._color=t.color||[1,1,1],this._opacity=t.opacity||1,this._sceneModel=new Wn(this,{isModel:!1}),this._sceneModel.createMesh({id:"linesMesh",primitive:"lines",positions:this._positions,indices:this._indices,color:this._color,opacity:this._opacity}),this._sceneModel.createEntity({meshIds:["linesMesh"],visible:t.visible,clippable:t.clippable,collidable:t.collidable}),this._sceneModel.finalize(),this.scene._lineSetCreated(this)}set visible(e){this._sceneModel.visible=e}get visible(){return this._sceneModel.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}class Xn extends D{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Kn extends Xn{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:d.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Zn{constructor(e,t,i){this.gl=e,this.allocated=!1,this.buffer=null,this.bound=!1,this._colorFormats=t,this._hasDepthTexture=i}setSize(e){this.size=e}bind(){const e=this.size[0],t=this.size[1];if(!this.buffer||this.buffer.width===e&&this.buffer.height===t||(this.buffer.cleanup(),this.buffer=null),this.buffer||(this._allocateBuffer(e,t),this.bound=!1),!this.bound){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}_allocateBuffer(e,t){const i=this._colorFormats||[],s=this.gl,r=()=>{const e=s.createTexture();return s.bindTexture(s.TEXTURE_2D,e),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e},n=(i.length>0?i:[null]).map((i=>{const n=r();return i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),n})),A=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,A),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,e,t);const o=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,o);for(let e=0;e<n.length;e++)s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+e,s.TEXTURE_2D,n[e],0);i.length>0&&s.drawBuffers(n.map(((e,t)=>s.COLOR_ATTACHMENT0+t)));const a=this._hasDepthTexture&&r();if(a?(s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,e,t,0,s.DEPTH_COMPONENT,s.FLOAT,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,a,0)):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,A),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,o),!s.isFramebuffer(o))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={cleanup:()=>{n.forEach((e=>s.deleteTexture(e))),a&&s.deleteTexture(a),s.deleteFramebuffer(o),s.deleteRenderbuffer(A)},framebuf:o,width:e,height:t},this.colorTextures=n.map((e=>({bind:function(t){return s.activeTexture(s["TEXTURE"+t]),s.bindTexture(s.TEXTURE_2D,e),!0}}))),this.depthTexture=a&&{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,a),!0}}}read(e,t,i=null,s=null,r=Uint8Array,n=4,A=0){const o=new r(n),a=this.gl;return a.readBuffer(a.COLOR_ATTACHMENT0+A),a.readPixels(e,this.buffer.height-t-1,1,1,i||a.RGBA,s||a.UNSIGNED_BYTE,o,0),o}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}destroy(){this.allocated&&(this.buffer.cleanup(),this.allocated=!1,this.buffer=null,this.bound=!1),this.colorTextures=null,this.depthTexture=null}}class Jn extends Xn{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new oe({type:"dir",dir:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=d.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];d.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=d.identityMat4()),d.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new Zn(this.scene.canvas.gl),this._shadowRenderBuf.setSize([1024,1024])),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class Yn extends Xn{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,r=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new oe({type:"point",pos:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=d.identityMat4());const e=i._state.pos,t=s.look,r=s.up;d.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=d.identityMat4());const e=i.scene.canvas.canvas;d.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new Zn(i.scene.canvas.gl),i._shadowRenderBuf.setSize([1024,1024])),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function $n(e){if(!qn(e.width)||!qn(e.height)){const t=document.createElement("canvas");t.width=eA(e.width),t.height=eA(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function qn(e){return 0==(e&e-1)}function eA(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class tA extends D{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new oe({texture:new zi({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),m.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let n=0;n<e.length;n++){const A=new Image;A.onload=function(){let e=A;const o=n;return function(){if(!s&&(e=$n(e),t._images[o]=e,r++,6===r)){let e=t._state.texture;e||(e=new zi({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),A.onerror=function(){s=!0},A.src=e[n]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),m.memory.textures--,this._state.destroy()}}class iA extends tA{get type(){return"ReflectionMap"}constructor(e,t={}){super(e,t),this.scene._lightsState.addReflectionMap(this._state),this.scene._reflectionMapCreated(this)}destroy(){super.destroy(),this.scene._reflectionMapDestroyed(this)}}class sA extends tA{get type(){return"LightMap"}constructor(e,t={}){super(e,t),this.scene._lightMapCreated(this)}destroy(){super.destroy(),this.scene._lightMapDestroyed(this)}}const rA=d.vec4(),nA=d.vec4();class AA extends D{constructor(e,t){super(e,t),this._entity=null,this._visible=null,this._worldPos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._viewPos=d.vec3(),this._canvasPos=d.vec2(),this._occludable=!1,this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(d.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){rA.set(this._viewPos),rA[3]=1,d.transformPoint4(this.scene.camera.projMatrix,rA,nA);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+nA[0]/nA[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-nA[1]/nA[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){this._entity!==e&&(this._cleanupDestroyedHandlers(),this._entity=e,this._entity&&(this._entity.isSceneModelEntity?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0))}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),Ye(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._cleanupDestroyedHandlers(),this._renderer.removeMarker(this),super.destroy()}_cleanupDestroyedHandlers(){this._entity&&(null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null))}}class oA extends AA{constructor(e,t={}){super(e,{entity:t.entity,occludable:t.occludable,worldPos:t.worldPos}),this._occluded=!1,this._visible=!0,this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new $i(this,{src:t.src}),this._geometry=new be(this,{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),this._mesh=new Qi(this,{geometry:this._geometry,material:new Ni(this,{ambient:[.9,.3,.9],shininess:30,diffuseMap:this._texture,backfaces:!0}),scale:[1,1,1],position:t.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),this.visible=!0,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,this.size=t.size,t.image?this.image=t.image:this.src=t.src}_setVisible(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,super._setVisible(e)}set visible(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}get visible(){return this._visible}set image(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}class aA{constructor(e){this._eye=d.vec3(),this._look=d.vec3(),this._up=d.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const lA=d.vec3();class cA{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){this.numObjects=0,this._mask=i?w.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,n=!i||i.xrayed,A=!i||i.highlighted,o=!i||i.selected,a=!i||i.clippable,l=!i||i.pickable,c=!i||i.colorize,h=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e<t;e++){const t=d[u[e].id];if(t){if(s&&(this.objectsVisible[e]=t.visible),r&&(this.objectsEdges[e]=t.edges),n&&(this.objectsXrayed[e]=t.xrayed),A&&(this.objectsHighlighted[e]=t.highlighted),o&&(this.objectsSelected[e]=t.selected),a&&(this.objectsClippable[e]=t.clippable),l&&(this.objectsPickable[e]=t.pickable),c){const i=t.colorize;this.objectsColorize[3*e+0]=i[0],this.objectsColorize[3*e+1]=i[1],this.objectsColorize[3*e+2]=i[2]}h&&(this.objectsOpacity[e]=t.opacity),this.numObjects++}}}restoreObjects(e,t){const i=this._mask,s=!i||i.visible,r=!i||i.edges,n=!i||i.xrayed,A=!i||i.highlighted,o=!i||i.selected,a=!i||i.clippable,l=!i||i.pickable,c=!i||i.colorize,h=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e<t;e++){const t=d[u[e].id];t&&(s&&(t.visible=this.objectsVisible[e]),r&&(t.edges=this.objectsEdges[e]),n&&(t.xrayed=this.objectsXrayed[e]),A&&(t.highlighted=this.objectsHighlighted[e]),o&&(t.selected=this.objectsSelected[e]),a&&(t.clippable=this.objectsClippable[e]),l&&(t.pickable=this.objectsPickable[e]),c&&(lA[0]=this.objectsColorize[3*e+0],lA[1]=this.objectsColorize[3*e+1],lA[2]=this.objectsColorize[3*e+2],t.colorize=lA),h&&(t.opacity=this.objectsOpacity[e]))}}}const hA=d.vec3();class uA{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?w.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,n=!t||t.xrayed,A=!t||t.highlighted,o=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,c=!t||t.colorize,h=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),n&&(this.objectsXrayed[u]=t.xrayed),A&&(this.objectsHighlighted[u]=t.highlighted),o&&(this.objectsSelected[u]=t.selected),a&&(this.objectsClippable[u]=t.clippable),l&&(this.objectsPickable[u]=t.pickable),c){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}h&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,n=!t||t.highlighted,A=!t||t.selected,o=!t||t.clippable,a=!t||t.pickable,l=!t||t.colorize,c=!t||t.opacity;var h=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[h]),s&&(t.edges=this.objectsEdges[h]),r&&(t.xrayed=this.objectsXrayed[h]),n&&(t.highlighted=this.objectsHighlighted[h]),A&&(t.selected=this.objectsSelected[h]),o&&(t.clippable=this.objectsClippable[h]),a&&(t.pickable=this.objectsPickable[h]),l&&(this.objectsHasColorize[h]?(hA[0]=this.objectsColorize[3*h+0],hA[1]=this.objectsColorize[3*h+1],hA[2]=this.objectsColorize[3*h+2],t.colorize=hA):t.colorize=null),c&&(t.opacity=this.objectsOpacity[h]),h++}}}class dA extends K{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.v3=t.v3,this.t=t.t}set v0(e){this._v0=e||d.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||d.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||d.vec3([0,0,0])}get v2(){return this._v2}set v3(e){this.fire("v3",this._v3=e||d.vec3([0,0,0]))}get v3(){return this._v3}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=d.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=d.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class fA extends K{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i<s;i++)(t=this._curves[i]).off(this._dirtySubs[i]),t.off(this._destroyedSubs[i]);this._curves=[],this._dirtySubs=[],this._destroyedSubs=[];var r=this;function n(){r._dirty=!0}function A(){var e=this.id;for(i=0,s=r._curves.length;i<s;i++)if(r._curves[i].id===e)return r._curves=r._curves.slice(i,i+1),r._dirtySubs=r._dirtySubs.slice(i,i+1),r._destroyedSubs=r._destroyedSubs.slice(i,i+1),void(r._dirty=!0)}for(i=0,s=e.length;i<s;i++){if(t=e[i],w.isNumeric(t)||w.isString(t)){var o=t;if(!(t=this.scene.components[o])){this.error("Component not found: "+_inQuotes(o));continue}}var a=t.type;"xeokit.SplineCurve"===a||"xeokit.Path"===a||"xeokit.CubicBezierCurve"===a||"xeokit.QuadraticBezierCurve"===a?(this._curves.push(t),this._dirtySubs.push(t.on("dirty",n)),this._destroyedSubs.push(t.once("destroyed",A))):this.error("Component "+_inQuotes(t.id)+" is not a xeokit.SplineCurve, xeokit.Path or xeokit.QuadraticBezierCurve")}this._dirty=!0}get curves(){return this._curves}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r<s.length;){if(s[r]>=i){var n=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(n)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e<s;e++)i+=this._curves[e].length,t.push(i);return this._cachedLengths=t,this._dirty=!1,t}_getJSON(){for(var e=[],t=0,i=this._curves.length;t<i;t++)e.push(this._curves[t].id);return{curves:e,t:this._t}}destroy(){var e,t,i;for(super.destroy(),e=0,t=this._curves.length;e<t;e++)(i=this._curves[e]).off(this._dirtySubs[e]),i.off(this._destroyedSubs[e])}}class pA extends K{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.t=t.t}set v0(e){this._v0=e||d.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||d.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||d.vec3([0,0,0])}get v2(){return this._v2}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=d.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=d.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class gA extends Wn{constructor(e,t={}){super(e,t)}}const mA=d.vec3(),_A=d.vec3(),bA=d.vec4(),yA=d.vec3([0,0,-1]),wA=d.vec3([0,0,1]),vA=d.vec3([0,1,0]);class BA extends D{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new oe({active:!0,pos:d.vec3(),quaternion:d.vec4(),roll:0,dir:d.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active),this.scene.fire("sectionPlaneUpdated",this)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-d.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}get pos(){return this._state.pos}set quaternion(e){this._state.quaternion.set(e||[0,0,0,-1]),d.vec3ApplyQuaternion(this._state.quaternion,wA,this._state.dir);const t=d.vec3ApplyQuaternion(this._state.quaternion,vA,mA),i=d.vec3PairToQuaternion(wA,this._state.dir,bA),s=d.vec3ApplyQuaternion(i,vA,_A),r=Math.acos(Math.min(1,d.dotVec3(t,s))),n=Math.sign(d.dotVec3(this._state.dir,d.cross3Vec3(t,s,_A)));this._state.roll=n*r,this._onDirUpdated()}get quaternion(){return this._state.quaternion}set roll(e){this._state.roll=e||0,this._onDirRollUpdated()}get roll(){return this._state.roll}set dir(e){this._state.dir.set(e||yA),this._onDirRollUpdated()}_onDirRollUpdated(){d.vec3PairToQuaternion(wA,this._state.dir,this._state.quaternion),bA[0]=0,bA[1]=0,bA[2]=-1,bA[3]=this._state.roll,d.angleAxisToQuaternion(bA,bA),d.mulQuaternions(this._state.quaternion,bA,this._state.quaternion),this._onDirUpdated()}_onDirUpdated(){this._state.dist=-d.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){d.mulVec3Scalar(this._state.dir,-1,this._state.dir),this.dir=this._state.dir}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}class CA{transcode(e,t,i={}){}destroy(){}}class MA{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}const EA={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isIphoneOrIpadSafari(){const e=window.navigator.userAgent,t=/iPhone|iPad/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2,i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isTouchDevice:()=>"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.mxMaxTouchPoints>0};class FA{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){I.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const n=this._subIdMap.addItem();r[n]={callback:i,scope:s||this},this._subIdEvents[n]=t;const A=this._events[t];return void 0!==A&&i.call(s||this,A),n}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}class UA extends D{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const xA=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class IA extends D{constructor(e,t={}){super(e,t),this._backgroundColor=d.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new UA(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+d.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<xA.length;e++)try{this.gl=this.canvas.getContext(xA[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));{const e=this.gl;let t="__",i=e.activeTexture;e.activeTexture=function(e){t!==e&&(t=e,i.call(this,e))};let s={},r=e.bindTexture;e.bindTexture=function(e,i){s[t]!==i&&(s[t]=i,r.call(this,e,i))}}this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}getSnapshot(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}readPixels(e,t,i){return this.scene._renderer.snapshot.readPixels(e,t,i)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.gl=null,super.destroy()}}class TA{constructor(e){this._matPool=[],this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.viewParams={},this.viewParams.viewMatrix=null,this.viewParams.projMatrix=null,this.viewParams.near=.01,this.viewParams.far=5e3,this.pickInvisible=!1,this.lineWidth=1,this.snapPickLayerParams=[],this.snapPickCoordinateScale=d.vec3(),this.snapPickOrigin=d.vec3()}getRTCViewMatrix(e,t){let i=this._rtcViewMats[e];return i||(i=this._getNewMat(),Je(this.viewParams.viewMatrix,t,i),this._rtcViewMats[e]=i),i}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=d.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}const PA={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},SA=document.createElement("canvas");if(SA){const e=SA.getContext("webgl",{antialias:!0})||SA.getContext("experimental-webgl",{antialias:!0});PA.WEBGL=!!e,PA.WEBGL&&(PA.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?PA.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?PA.FS_MAX_FLOAT_PRECISION="mediump":PA.FS_MAX_FLOAT_PRECISION="lowp":PA.FS_MAX_FLOAT_PRECISION="mediump",PA.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),PA.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),PA.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),PA.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),PA.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),PA.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),PA.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),PA.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),PA.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),PA.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){PA.SUPPORTED_EXTENSIONS[e]=!0})))}class DA{constructor(e){this.aabb=d.AABB3(),this.origin=d.vec3(e),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(e,t){if(this.markerListDirty){for(var i in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(i)&&(this.markerList[this.numMarkers]=this.markers[i],this.markerIndices[i]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0}if(this.positionsDirty){let t=0;for(let e=0;e<this.numMarkers;e++)if(this.markerList[e]){const i=this.markerList[e].rtcPos;this.positions[t++]=i[0],this.positions[t++]=i[1],this.positions[t++]=i[2],this.indices[e]=e}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers,this.positionsDirty=!1;const i=this.aabb;d.collapseAABB3(i),d.expandAABB3Points3(i,this.positions);const s=this.origin;i[0]+=s[0],i[1]+=s[1],i[2]+=s[2],i[3]+=s[0],i[4]+=s[1],i[5]+=s[2],this.positionsBuf&&this.lenPositionsBuf!==this.positions.length&&(this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null);const r=new Float32Array(this.positions);this.positionsBuf?this.positionsBuf.setData(r):(this.positionsBuf=new ae(e,e.ARRAY_BUFFER,r,r.length,3,e.STATIC_DRAW),this.indicesBuf=new ae(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),this.indices.length,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length)}if(this.occlusionTestListDirty){let e=0;this.lenOcclusionTestList=0;for(let i=0;i<this.numMarkers;i++){const s=this.markerList[i];s.entity&&!s.entity.visible||!t(s)?s._setVisible(!1):s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[e++]=s.canvasPos[0],this.pixels[e++]=s.canvasPos[1]):s._setVisible(!0)}}}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const kA=d.vec3([255,0,0]);d.vec3();class QA{constructor(e){this._scene=e,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._drawable=null,this._markersToOcclusionLayersMap={};const t=e.camera,i=()=>{this._occlusionTestListDirty=!0};this._onCameraViewMatrix=t.on("viewMatrix",i),this._onCameraProjMatrix=t.on("projMatrix",i),this._onCanvasBoundary=e.canvas.on("boundary",i)}_addMarker(e,t){this._occlusionLayers[t]||(this._occlusionLayers[t]=new DA(e.origin),this._occlusionLayersListDirty=!0);const i=this._occlusionLayers[t];i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}_removeMarker(e,t){1===e.numMarkers?(e.destroy(),delete this._occlusionLayers[e.originHash],this._occlusionLayersListDirty=!0):e.removeMarker(t),delete this._markersToOcclusionLayersMap[t.id]}addMarker(e){const t=e.origin.join();this._addMarker(e,t),this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(t){const i=e.origin.join();i!==t.originHash?(this._removeMarker(t,e),this._addMarker(e,i)):t.markerWorldPosUpdated(e)}}removeMarker(e){const t=e.origin.join(),i=this._occlusionLayers[t];i&&this._removeMarker(i,e)}get needOcclusionTest(){return this._occlusionTestListDirty}drawMarkers(){const e=this._scene,t=e.canvas,i=t.gl,s=e._sectionPlanesState,r=[t.canvas.id,s.getHash()].join(";");if(!this._drawable||r!==this._drawable.shaderSourceHash){this._drawable&&this._drawable.destroy();const n=mi(),A=n.programVariables,o=A.createUniform("mat4","viewMatrix"),a=A.createUniform("mat4","projMatrix"),l=A.createAttribute("vec3","position"),c=A.createOutput("vec4","outColor"),h="clipPos",[u,f]=n.buildProgram(i,"OcclusionTester",{sectionPlanesState:s,getLogDepth:e.logarithmicDepthBufferEnabled&&(e=>e),clippableTest:()=>"true",getVertexData:()=>{const t=[];return t.push(`vec4 worldPosition = vec4(${l}, 1.0);`),t.push(`vec4 ${h} = ${a} * ${o} * worldPosition;`),!e.logarithmicDepthBufferEnabled&&e.markerZOffset<0&&t.push(`${h}.z += ${e.markerZOffset};`),t},worldPositionAttribute:"worldPosition",getPointSize:()=>"20.0",clipPos:h,appendFragmentOutputs:e=>e.push(`${c} = vec4(1.0, 0.0, 0.0, 1.0);`)});if(f)throw console.error(f.join("\n")),f.join("\n");this._occlusionTestListDirty=!0,this._drawable={shaderSourceHash:r,destroy:()=>u.destroy(),drawCall:()=>{const r=e.camera,n=r.project;u.bind(),a.setInputValue(n.matrix);const A=t.boundary,c=A[2],h=A[3],f=r.perspective.near,p=e=>{const t=e.viewPos,i=e.canvasPos,s=i[0],r=i[1];return t[2]<=-f&&s>=-10&&r>=-10&&s<=c+10&&r<=h+10};this._occlusionLayersList.forEach((e=>{e.update(i,p);const t=s.sectionPlanes.some(((t,i)=>{const s=t.active?d.planeAABB3Intersect(t.dir,t.dist,e.aabb):1,r=-1===s;return e.sectionPlanesActive[i]=0===s,r}));if(!t){const t=e.origin;o.setInputValue(Je(r.viewMatrix,t)),u.inputSetters.setUniforms(null,{view:{far:n.far},mesh:{origin:t,renderFlags:{sectionPlanesActivePerLayer:e.sectionPlanesActive}}}),l.setInputValue(e.positionsBuf);const s=e.indicesBuf;s.bind(),i.drawElements(i.POINTS,s.numItems,s.itemType,0)}}))}}}if(this._occlusionLayersListDirty){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e,this._occlusionLayersListDirty=!1}if(this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._drawable.drawCall()}doOcclusionTest(e){this._occlusionLayersList.forEach((t=>{for(let i=0;i<t.lenOcclusionTestList;i++){const s=2*i,r=e(t.pixels[s],t.pixels[s+1]);t.occlusionTestList[i]._setVisible(d.compareVec3(kA,r))}}))}destroy(){this.destroyed||(this._occlusionLayersList.forEach((e=>e.destroy())),this._drawable&&this._drawable.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0)}}const RA=d.vec3([0,0,0]),OA=d.vec4([1/4294967296,1/16777216,1/65536,1/256]),VA=e=>e[0]+(e[1]<<8)+(e[2]<<16)+(e[3]<<24),LA=e=>d.normalizeVec3(d.divVec3Scalar(e,d.MAX_INT,d.vec3())),HA=(e,t,i)=>d.vec3([e[0]*i[0]+t[0],e[1]*i[1]+t[1],e[2]*i[2]+t[2]]),NA=function(t,i){i=i||{};const s=new TA,r=t.canvas.canvas,n=t.canvas.gl,A=!!i.transparent,o=i.alphaDepthMask,a=new e({});let l={},c={},h=[],u=[],f=[],p=!0,g=!0,_=!0,b=!0,y=!0,w=!0,v=!0,B=!0;const C=function(){const e={},i={};return{getRenderBuffer:(s,r,A)=>{const o=1===t.canvas.resolutionScale?e:i;return o[s]||(o[s]=new Zn(n,r,A)),o[s]},destroy:()=>{Object.values(e).forEach((e=>e.destroy())),Object.values(i).forEach((e=>e.destroy()))}}}(),M=(e,t,i,s)=>{const r=i.programVariables,n=r.createUniform("vec2","uViewportInv"),A=r.createUniform("float","uCameraNear"),o=r.createUniform("float","uCameraFar"),a=r.createUniform("sampler2D","uDepthTexture"),l=r.createAttribute("vec2","uv"),c=r.createVarying("vec2","vUV",(()=>l)),h=r.createOutput("vec4","outColor"),u=r.createFragmentDefinition("getOutColor",((e,t)=>{const i="getDepth";t.push(`\n float getDepth(const in vec2 uv) {\n return texture(${a}, uv).r;\n }\n `),t.push(s(e,c,n,A,o,i))})),[d,f]=i.buildProgram(e,t,{clipPos:`vec4(2.0 * ${l} - 1.0, 0.0, 1.0)`,appendFragmentOutputs:e=>e.push(`${h} = ${u}();`)});if(f)throw console.error(f.join("\n")),f;{const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new ae(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),s=new Uint32Array([0,1,2,0,2,3]),r=new ae(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW);return{destroy:d.destroy,bind:(e,t,s)=>{d.bind(),n.setInputValue([1/e[0],1/e[1]]),A.setInputValue(t.near),o.setInputValue(t.far),a.setInputValue(s),l.setInputValue(i)},draw:()=>{r.bind(),e.drawElements(e.TRIANGLES,r.numItems,r.itemType,0)}}}},E=function(){let e=null,t=null;return{destroy:()=>e&&e.destroy(),render:(i,s,r,A)=>{const o=Math.floor(r.numSamples);if(t!==o){e&&e.destroy();const i=mi(),s=i.programVariables,r=s.createUniform("mat4","uProjectMatrix"),A=s.createUniform("mat4","uInvProjMatrix"),a=s.createUniform("bool","uPerspective"),l=s.createUniform("float","uScale"),c=s.createUniform("float","uIntensity"),h=s.createUniform("float","uBias"),u=s.createUniform("float","uKernelRadius"),d=s.createUniform("float","uMinResolution"),f=s.createUniform("float","uRandomSeed"),p=M(n,"SAOOcclusionRenderer",i,((e,t,i,s,n,p)=>`\n #define EPSILON 1e-6\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define NUM_SAMPLES ${o}\n #define NUM_RINGS 4\n\n const vec3 packFactors = vec3(256. * 256. * 256., 256. * 256., 256.);\n\n vec4 packFloatToRGBA(const in float v) {\n vec4 r = vec4(fract(v * packFactors), v);\n r.yzw -= r.xyz / 256.;\n return r * 256. / 255.;\n }\n\n highp float rand(const in vec2 uv) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n return fract(sin(mod(dot(uv, vec2(a, b)), PI)) * c);\n }\n\n vec3 getViewPos(const in vec2 screenPos, const in float depth) {\n float near = ${s};\n float far = ${n};\n float viewZ = (${a}\n ? ((near * far) / ((far - near) * depth - far))\n : (depth * (near - far) - near));\n float clipW = ${r}[2][3] * viewZ + ${r}[3][3];\n return (${A} * (clipW * vec4((vec3(screenPos, depth) - 0.5) * 2.0, 1.0))).xyz;\n }\n\n vec4 ${e}() {\n float centerDepth = ${p}(${t});\n if (centerDepth >= (1.0 - EPSILON)) {\n discard;\n }\n\n vec3 centerViewPosition = getViewPos(${t}, centerDepth);\n float scaleDividedByCameraFar = ${l} / ${n};\n float minResolutionMultipliedByCameraFar = ${d} * ${n};\n vec3 centerViewNormal = normalize(cross(dFdx(centerViewPosition), dFdy(centerViewPosition)));\n\n vec2 radiusStep = ${u} * ${i} / float(NUM_SAMPLES);\n vec2 radius = radiusStep;\n const float angleStep = PI2 * float(NUM_RINGS) / float(NUM_SAMPLES);\n float angle = PI2 * rand(${t} + ${f});\n\n float occlusionSum = 0.0;\n float weightSum = 0.0;\n\n for (int i = 0; i < NUM_SAMPLES; i++) {\n vec2 sampleUv = ${t} + vec2(cos(angle), sin(angle)) * radius;\n radius += radiusStep;\n angle += angleStep;\n\n float sampleDepth = ${p}(sampleUv);\n if (sampleDepth >= (1.0 - EPSILON)) {\n continue;\n }\n\n vec3 sampleViewPosition = getViewPos(sampleUv, sampleDepth);\n vec3 viewDelta = sampleViewPosition - centerViewPosition;\n float scaledScreenDistance = scaleDividedByCameraFar * length(viewDelta);\n occlusionSum += max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - ${h}) / (1.0 + scaledScreenDistance * scaledScreenDistance );\n weightSum += 1.0;\n }\n\n return packFloatToRGBA(1.0 - occlusionSum * ${c} / weightSum);\n }`));e={destroy:p.destroy,render:(e,t,i,s)=>{p.bind(e,t,s),r.setInputValue(t.matrix),A.setInputValue(t.inverseMatrix),a.setInputValue("Perspective"===t.type),l.setInputValue(i.scale*t.far/5),c.setInputValue(i.intensity),h.setInputValue(i.bias),u.setInputValue(i.kernelRadius),d.setInputValue(i.minResolution),f.setInputValue(Math.random()),p.draw()}},t=o}e.render(i,s,r,A)}}}(),F=function(){const e=e=>{const t=[];for(let i=0;i<=17;i++)t.push(e[0]*i),t.push(e[1]*i);return new Float32Array(t)},t=e([0,1]),i=e([1,0]),s=new Float32Array((e=>{const t=[];for(let i=0;i<e;++i)t.push(i);return t})(17).map((e=>((e,t)=>Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t))(e,4)))),r=mi(),A=r.programVariables,o=A.createUniform("float","uDepthCutoff"),a=A.createUniformArray("vec2","uSampleOffsets",17),l=A.createUniformArray("float","uSampleWeights",17),c=A.createUniform("sampler2D","uOcclusionTex"),h=M(n,"SAODepthLimitedBlurRenderer",r,((e,t,i,s,r,n)=>`\n #define EPSILON 1e-6\n\n const vec3 packFactors = vec3(256. * 256. * 256., 256. * 256., 256.);\n\n vec4 packFloatToRGBA(const in float v) {\n vec4 r = vec4(fract(v * packFactors), v);\n r.yzw -= r.xyz / 256.;\n return r * 256. / 255.;\n }\n\n float getOcclusion(const in vec2 uv) {\n vec4 v = texture(${c}, uv);\n return dot(floor(v * 255.0 + 0.5) / 255.0, 255. / 256. / vec4(packFactors, 1.)); // unpackRGBAToFloat\n }\n\n float getViewZ(const in float depth) {\n return (${s} * ${r}) / ((${r} - ${s}) * depth - ${r});\n }\n\n vec4 ${e}() {\n float centerDepth = ${n}(${t});\n if (centerDepth >= (1.0 - EPSILON)) {\n discard;\n }\n\n float centerViewZ = getViewZ(centerDepth);\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = ${l}[0];\n float occlusionSum = getOcclusion(${t}) * weightSum;\n\n for (int i = 1; i <= 16; i++) {\n float sampleWeight = ${l}[i];\n vec2 sampleUVOffset = ${a}[i] * ${i};\n\n if (! rBreak) {\n vec2 rSampleUV = ${t} + sampleUVOffset;\n if (abs(centerViewZ - getViewZ(${n}(rSampleUV))) > ${o}) {\n rBreak = true;\n } else {\n occlusionSum += getOcclusion(rSampleUV) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n if (! lBreak) {\n vec2 lSampleUV = ${t} - sampleUVOffset;\n if (abs(centerViewZ - getViewZ(${n}(lSampleUV))) > ${o}) {\n lBreak = true;\n } else {\n occlusionSum += getOcclusion(lSampleUV) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n }\n\n return packFloatToRGBA(occlusionSum / weightSum);\n }`));return{destroy:h.destroy,render:(e,r,n,A,u)=>{h.bind(e,r,A),o.setInputValue(.01),a.setInputValue(0===n?i:t),l.setInputValue(s),c.setInputValue(u),h.draw()}}}(),U=function(){let e=null;return function(){if(!e){const i=t.camera;e={get eye(){return i.eye},get far(){return i.project.far},get projMatrix(){return i.projMatrix},get viewMatrix(){return i.viewMatrix},get viewNormalMatrix(){return i.viewNormalMatrix}}}return e}}(),x=(e,t)=>"ortho"===e.projection?1:t/(2*Math.tan(.5*e.perspective.fov*Math.PI/180));function I(){if(p&&(Object.values(l).forEach((e=>{const t=e.drawableListPreCull;let i=0;Object.values(e.drawableMap).forEach((e=>{t[i++]=e})),t.length=i})),p=!1,g=!0),g){let e=0;Object.values(l).forEach((t=>{t.drawableListPreCull.forEach((t=>{h[e++]=t}))})),h.length=e,h.sort(((e,t)=>e.renderOrder-t.renderOrder)),g=!1,_=!0}if(_){let e=0,t=0;h.forEach((i=>{i.rebuildRenderFlags(),i.renderFlags.culled||(i.isUI?f[t++]=i:u[e++]=i)})),u.length=e,f.length=t}}this.scene=t,this._occlusionTester=null,this.capabilities={astcSupported:!!Gi(n,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!Gi(n,"WEBGL_compressed_texture_etc"),dxtSupported:!!Gi(n,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!Gi(n,"EXT_texture_compression_bptc"),pvrtcSupported:!(!Gi(n,"WEBGL_compressed_texture_pvrtc")&&!Gi(n,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){b=e,_=!0},this.setEdgesEnabled=function(e){y=e,_=!0},this.setSAOEnabled=function(e){w=e,_=!0},this.setPBREnabled=function(e){v=e,_=!0},this.setColorTextureEnabled=function(e){B=e,_=!0},this.needStateSort=function(){g=!0},this.shadowsDirty=function(){},this.imageDirty=function(){_=!0},this.addDrawable=function(e,t){const i=t.type;if(!i)return void console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring");let s=l[i];s||(s={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},l[i]=s),s.count++,s.drawableMap[e]=t,c[e]=t,p=!0},this.removeDrawable=function(e){const t=c[e];if(!t)return void console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring");const i=t.type,s=l[i];--s.count<=0?delete l[i]:delete s.drawableMap[e],delete c[e],p=!0},this.getPickID=function(e){return a.addItem(e)},this.putPickID=function(e){a.removeItem(e)},this.clear=function(e){if(n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),A)n.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;n.clearColor(e[0],e[1],e[2],1)}n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT)},this.needsRender=function(){return _||p||g},this.render=function(e,i){I(),_&&(!function(e,i){const r=t.sao,a=w&&r.possible&&r.numSamples>=1&&function(e){const i=t.sao,r=[n.drawingBufferWidth,n.drawingBufferHeight],A=C.getRenderBuffer("saoDepth",[],!0);A.setSize(r),A.bind(),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),s.reset(),s.pass=e,s.viewParams=U(),s.nearPlaneHeight=x(t.camera,n.drawingBufferHeight),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.enable(n.CULL_FACE),n.depthMask(!0),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),u.forEach((e=>{!e.culled&&e.visible&&e.drawDepth&&e.saoEnabled&&e.renderFlags.colorOpaque&&e.drawDepth(s)})),A.unbind();const o=A.depthTexture,a=C.getRenderBuffer("saoOcclusion");if(a.setSize(r),a.bind(),n.viewport(0,0,r[0],r[1]),n.clearColor(0,0,0,1),n.disable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT),E.render(r,t.camera.project,i,o),a.unbind(),i.blur){const e=C.getRenderBuffer("saoOcclusion2");e.setSize(r);const i=(e,i,s)=>{i.bind(),n.viewport(0,0,r[0],r[1]),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);const A=t.camera.project;F.render(r,A,s,o,e.colorTextures[0]),i.unbind()};i(a,e,0),i(e,a,1)}return a.colorTextures[0]}(e);t._lightsState.lights.forEach((e=>{if(e.castsShadow){const i=e.getShadowRenderBuf();i.bind(),s.reset(),s.backfaces=!0,s.frontface=!0,s.viewParams.viewMatrix=e.getShadowViewMatrix(),s.viewParams.projMatrix=e.getShadowProjMatrix(),s.nearPlaneHeight=x(t.camera,n.drawingBufferHeight),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),Object.values(l).forEach((e=>{e.drawableList.forEach((e=>{!1!==e.visible&&e.castsShadow&&e.drawShadow&&e.renderFlags.colorOpaque&&e.drawShadow(s)}))})),i.unbind()}})),function(e,i,r){const a=[],l=[],c=[],h=[],p=[],g=[],_=[],w=[],C=[],M=[],E=[],F=[],I=[],T=[],P=[],S=[],D=t._lightsState.getAmbientColorAndIntensity();if(s.reset(),s.pass=e,s.withSAO=!1,s.pbrEnabled=v&&!!t.pbrEnabled,s.colorTextureEnabled=B&&!!t.colorTextureEnabled,s.viewParams=U(),s.nearPlaneHeight=x(t.camera,n.drawingBufferHeight),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),A)n.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?D:t.canvas.backgroundColor;n.clearColor(e[0],e[1],e[2],1)}let k,Q;n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.enable(n.CULL_FACE),n.depthMask(!0),n.lineWidth(1),s.lineWidth=1,t.sao,s.saoParams=[n.drawingBufferWidth,n.drawingBufferHeight,t.sao.blendCutoff,t.sao.blendFactor],s.occlusionTexture=r;const R=Date.now();i&&n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);const O=function(e){let i=0,u=0,f=0,m=0,v=0,B=0,U=0,x=0,D=0,R=0,O=0,V=0,L=0,H=0,N=0,G=0;for(let t=0,n=e.length;t<n;t++){if(Q=e[t],!0===Q.culled||!1===Q.visible)continue;const n=Q.renderFlags;n.colorOpaque&&(Q.saoEnabled&&r?a[i++]=Q:Q.drawColorOpaque(s)),b&&n.colorTransparent&&(c[f++]=Q),n.xrayedSilhouetteTransparent&&(_[U++]=Q),n.xrayedSilhouetteOpaque&&(p[v++]=Q),n.highlightedSilhouetteTransparent&&(E[O++]=Q),n.highlightedSilhouetteOpaque&&(C[D++]=Q),n.selectedSilhouetteTransparent&&(P[N++]=Q),n.selectedSilhouetteOpaque&&(I[L++]=Q),Q.edges&&y&&(n.edgesOpaque&&(l[u++]=Q),n.edgesTransparent&&(h[m++]=Q),n.selectedEdgesTransparent&&(S[G++]=Q),n.selectedEdgesOpaque&&(T[H++]=Q),n.xrayedEdgesTransparent&&(w[x++]=Q),n.xrayedEdgesOpaque&&(g[B++]=Q),n.highlightedEdgesTransparent&&(F[V++]=Q),n.highlightedEdgesOpaque&&(M[R++]=Q))}if(i>0)for(s.withSAO=!0,k=0;k<i;k++)a[k].drawColorOpaque(s);if(u>0)for(k=0;k<u;k++)l[k].drawEdgesColorOpaque(s);if(v>0)for(k=0;k<v;k++)p[k].drawSilhouetteXRayed(s);if(B>0)for(k=0;k<B;k++)g[k].drawEdgesXRayed(s);if(U>0||x>0||f>0||m>0){if(n.enable(n.CULL_FACE),n.enable(n.BLEND),A?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):(n.blendEquation(n.FUNC_ADD),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,o||n.depthMask(!1),(f>0||m>0)&&n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),m>0)for(k=0;k<m;k++)Q=h[k],Q.drawEdgesColorTransparent(s);if(f>0){const e=s.viewParams.eye,t=c.map((t=>({drawable:t,distSq:d.distVec3(t.origin||RA,e)})));for(t.sort(((e,t)=>t.distSq-e.distSq)),k=0;k<f;k++)t[k].drawable.drawColorTransparent(s)}if(x>0)for(k=0;k<x;k++)w[k].drawEdgesXRayed(s);if(U>0)for(k=0;k<U;k++)_[k].drawSilhouetteXRayed(s);n.disable(n.BLEND),o||n.depthMask(!0)}if(D>0||R>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),R>0)for(k=0;k<R;k++)M[k].drawEdgesHighlighted(s);if(D>0)for(k=0;k<D;k++)C[k].drawSilhouetteHighlighted(s)}if(O>0||V>0||D>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),n.enable(n.BLEND),A?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),n.enable(n.CULL_FACE),V>0)for(k=0;k<V;k++)F[k].drawEdgesHighlighted(s);if(O>0)for(k=0;k<O;k++)E[k].drawSilhouetteHighlighted(s);n.disable(n.BLEND)}if(L>0||H>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),H>0)for(k=0;k<H;k++)T[k].drawEdgesSelected(s);if(L>0)for(k=0;k<L;k++)I[k].drawSilhouetteSelected(s)}if(N>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),n.enable(n.CULL_FACE),n.enable(n.BLEND),A?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),G>0)for(k=0;k<G;k++)S[k].drawEdgesSelected(s);if(N>0)for(k=0;k<N;k++)P[k].drawSilhouetteSelected(s);n.disable(n.BLEND)}};O(u),f.length>0&&(n.clear(n.DEPTH_BUFFER_BIT),O(f));const V=Date.now(),L=m.frame;L.renderTime=(V-R)/1e3,L.drawElements=s.drawElements,L.drawArrays=s.drawArrays,L.useProgram=s.useProgram,L.bindTexture=s.bindTexture,L.bindArray=s.bindArray;const H=PA.MAX_TEXTURE_IMAGE_UNITS;for(let e=0;e<H;e++)n.activeTexture(n.TEXTURE0+e);n.bindTexture(n.TEXTURE_CUBE_MAP,null),n.bindTexture(n.TEXTURE_2D,null);const N=PA.MAX_VERTEX_ATTRIBS;for(let e=0;e<N;e++)n.disableVertexAttribArray(e)}(e,i,a)}(e,i),m.frame.frameCount++,_=!1)};const T=(e,i,s,r,A,o,a)=>{a.reset(),a.backfaces=!0,a.frontface=!0,a.viewParams.eye=r,a.viewParams.projMatrix=A,a.viewParams.viewMatrix=o,a.nearPlaneHeight=x(s,n.drawingBufferHeight);const l=t.canvas.resolutionScale;a.pickClipPos=[e?2*e[0]*l/n.drawingBufferWidth-1:0,e?1-2*e[1]*l/n.drawingBufferHeight:0],a.pickClipPosInv=[n.drawingBufferWidth/i,n.drawingBufferHeight/i]};this.pick=function(){const e=d.vec3(),i=d.vec3(),A=d.vec4(),o=d.vec4(),l=d.vec4(),c=d.vec4(),h=d.vec4(),p=d.mat4(),g=d.mat4(),m=d.mat4(),_=d.mat4(),b=d.vec3([0,1,0]),y=new MA,w=d.vec2(),v=d.vec3(),B=d.vec3(),C=d.vec3();d.vec3(),d.vec3();const M=new Zn(n);M.setSize([1,1]);const E=new Zn(n,[n.RGBA32I]);return E.setSize([3,3]),function(F,U=y){U.reset(),I();let x=null,P=null,S=null;const D=t.camera;if(U.pickSurface=F.pickSurface,F.canvasPos)v[0]=F.canvasPos[0],v[1]=F.canvasPos[1],x=D.viewMatrix,P=D.projMatrix,S=D.projection,w[0]=D.project.near,w[1]=D.project.far,U.canvasPos=F.canvasPos;else{if(F.matrix)x=F.matrix,P=D.projMatrix,S=D.projection,w[0]=D.project.near,w[1]=D.project.far;else{B.set(F.origin||[0,0,0]),C.set(F.direction||[0,0,1]);const t=d.addVec3(B,C,e),s=i;Math.abs(d.dotVec3(C,b))>.999999?(s[0]=0,s[1]=0,s[2]=Math.sign(C[1])):(d.cross3Vec3(C,b,s),d.cross3Vec3(s,C,s),d.normalizeVec3(s,s)),x=d.lookAtMat4v(B,t,s,g),P=D.ortho.matrix,S="ortho",w[0]=D.ortho.near,w[1]=D.ortho.far,U.origin=B,U.direction=C}v[0]=.5*r.clientWidth,v[1]=.5*r.clientHeight}M.bind();const k=e=>T(v,e,D,U.origin||D.eye,P||D.projMatrix,x||D.viewMatrix,s);k(1),s.pickInvisible=!!F.pickInvisible,n.viewport(0,0,1,1),n.depthMask(!0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);const Q=F.includeEntityIds,R=F.excludeEntityIds,O=function(e){e.forEach((e=>{e.culled||!e.visible||!e.pickable||!e.drawPickMesh||Q&&!Q[e.id]||R&&R[e.id]||e.drawPickMesh(s)}))};O(u),f.length>0&&(n.clear(n.DEPTH_BUFFER_BIT),O(f));const V=VA(M.read(0,0)),L=V>=0&&a.items[V];if(!L)return M.unbind(),null;const H=L.delegatePickedEntity?L.delegatePickedEntity():L;if(!H)return M.unbind(),null;if(F.pickSurface)if(L.canPickTriangle&&L.canPickTriangle())L.drawPickTriangles&&(k(1),n.viewport(0,0,1,1),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),L.drawPickTriangles(s),U.primIndex=3*VA(M.read(0,0))),L.pickTriangleSurface(x,P,S,U),U.pickSurfacePrecision=!1;else if(L.canPickWorldPos&&L.canPickWorldPos()){k(1),s.viewParams.near=w[0],s.viewParams.far=w[1],n.viewport(0,0,1,1),n.clearColor(0,0,0,0),n.depthMask(!0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),L.drawPickDepths(s);const e=d.dotVec4(M.read(0,0),OA),t=(v[0]-r.clientWidth/2)/(r.clientWidth/2),i=-(v[1]-r.clientHeight/2)/(r.clientHeight/2),a=L.origin,u=d.inverseMat4(d.mulMat4(P,a?Je(x,a,p):x,m),_),f=(e,s)=>(s[0]=t,s[1]=i,s[2]=e,s[3]=1,d.transformVec4(u,s,s),d.mulVec4Scalar(s,1/s[3])),g=f(-1,A),b=f(1,o),y=d.subVec3(b,g,l),B=d.addVec3(g,d.mulVec4Scalar(y,e,c),h);if(a&&d.addVec3(B,a),U.worldPos=B,!1!==F.pickSurfaceNormal){k(3),E.bind(),n.viewport(0,0,E.size[0],E.size[1]),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.DEPTH_BUFFER_BIT),n.clearBufferiv(n.COLOR,0,new Int32Array([0,0,0,0])),L.drawPickNormals(s);const e=E.read(1,1,n.RGBA_INTEGER,n.INT,Int32Array,4);E.unbind(),U.worldNormal=LA(e)}U.pickSurfacePrecision=!1}return M.unbind(),U.entity=H,U}}(),this.snapPick=function(){const e=new MA,i=function(){const e={};return t=>{if(!(t in e)){const i=new Zn(n,[n.RGBA32I,n.RGBA32I,n.RGBA8UI],!0);i.setSize([2*t+1,2*t+1]),e[t]=i}return e[t]}}();return function(r,A=e){const{canvasPos:o,origin:l,direction:c,snapRadius:h,snapToVertex:f,snapToEdge:p}=r;if(!f&&!p)return this.pick({canvasPos:o,pickSurface:!0});const g=t.camera,m=h||30,_=o?g.viewMatrix:d.lookAtMat4v(l,d.addVec3(l,c,d.vec3()),d.vec3([0,1,0]),d.mat4());T(o,2*m,g,g.eye,g.projMatrix,_,s);const b=i(m);b.bind(),n.viewport(0,0,b.size[0],b.size[1]),n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.disable(n.CULL_FACE),n.depthMask(!0),n.disable(n.BLEND),n.depthFunc(n.LEQUAL),n.clear(n.DEPTH_BUFFER_BIT),n.clearBufferiv(n.COLOR,0,new Int32Array([0,0,0,0])),n.clearBufferiv(n.COLOR,1,new Int32Array([0,0,0,0])),n.clearBufferuiv(n.COLOR,2,new Uint32Array([0,0,0,0])),n.drawBuffers([n.COLOR_ATTACHMENT0,n.COLOR_ATTACHMENT1,n.COLOR_ATTACHMENT2]),s.snapPickLayerParams=[],s.snapPickLayerParams.push(null),u.forEach((e=>{!e.culled&&e.visible&&e.pickable&&e.drawSnapInit&&e.drawSnapInit(s)}));const y=s.snapPickLayerParams;s.snapPickLayerParams=[],n.depthMask(!1),n.drawBuffers([n.COLOR_ATTACHMENT0]);const w=e=>{s.snapMode=e,s.snapPickLayerParams.push(null),u.forEach((e=>{!e.culled&&e.visible&&e.pickable&&e.drawSnap&&e.drawSnap(s)}))};p&&w("edge"),f&&w("vertex"),n.depthMask(!0);const v=s.snapPickLayerParams,B=(e,t,i)=>{const s=b.buffer.width,r=b.buffer.height,A=new t(4*s*r);return n.readBuffer(e),n.readPixels(0,0,s,r,n.RGBA_INTEGER,i,A,0),A},C=B(n.COLOR_ATTACHMENT0,Int32Array,n.INT),M=B(n.COLOR_ATTACHMENT1,Int32Array,n.INT),E=B(n.COLOR_ATTACHMENT2,Uint32Array,n.UNSIGNED_INT);b.unbind();let F=null,U=null,x=null;const I=4*m+m*b.size[0]*4,P=C.slice(I,I+4),S=M.slice(I,I+4),D=E.slice(I,I+4);if(0!==P[3]){const e=y[Math.abs(P[3])%y.length];F=HA(P,e.origin,e.coordinateScale),U=LA(S),x=a.items[VA(D)]}const k=[];for(let e=0;e<C.length;e+=4){const t=C[e+3];if(t>0){const i=Math.floor(e/4),s=b.size[0],r=i%s-Math.floor(s/2),n=Math.floor(i/s)-Math.floor(s/2);k.push({dist:d.lenVec2([r,n]),isVertex:f&&p?t>v.length/2:f,result:C.subarray(e,e+4),normal:M.subarray(e,e+4),id:E.subarray(e,e+4)})}}const Q=e=>e&&e.delegatePickedEntity?e.delegatePickedEntity():e;if(k.length>0){const e=k.reduce(((e,t)=>(e.isVertex-t.isVertex||t.dist-e.dist)>0?e:t)),t=e.result,i=v[t[3]],s=HA(t,i.origin,i.coordinateScale),r=g.projectWorldPos(s);return A.reset(),A.snappedToEdge=!e.isVertex,A.snappedToVertex=e.isVertex,A.worldPos=s,A.worldNormal=LA(e.normal),A.entity=Q(a.items[VA(e.id)]),A.canvasPos=o||F&&g.projectWorldPos(F)||r,A.snappedCanvasPos=r,A}return F?(A.reset(),A.snappedToEdge=!1,A.snappedToVertex=!1,A.worldPos=F,A.worldNormal=U,A.entity=Q(x),A.canvasPos=o||g.projectWorldPos(F),A.snappedCanvasPos=o,A):null}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new QA(t),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){I();const e=C.getRenderBuffer("occlusionReadPix");if(e&&(e.setSize([n.drawingBufferWidth,n.drawingBufferHeight]),e.bind()),s.reset(),s.backfaces=!0,s.frontface=!0,s.viewParams=U(),s.nearPlaneHeight=x(t.camera,n.drawingBufferHeight),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),u.forEach((e=>{!e.culled&&e.visible&&e.pickable&&e.drawOcclusion&&e.drawOcclusion(s)})),this._occlusionTester.drawMarkers(),e){const i=t.canvas.resolutionScale;this._occlusionTester.doOcclusionTest(((t,s)=>e.read(Math.round(i*t),Math.round(i*s)))),e.unbind()}}},this.snapshot=(()=>{let e=!1;const t=new Zn(n);let i=null;return{readPixels:(e,i,s)=>{t.bind(),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),_=!0,this.render();for(let r=0;r<s;r++){const s=2*r,n=4*r,A=t.read(e[s],e[s+1]);i[n]=A[0],i[n+1]=A[1],i[n+2]=A[2],i[n+3]=A[3]}t.unbind(),_=!0},beginSnapshot:()=>{t.setSize([n.drawingBufferWidth,n.drawingBufferHeight]),t.bind(),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),e=!0},renderSnapshotToCanvas:()=>{const s=t.buffer.width,r=t.buffer.height;return i&&i.width===s&&i.height===r||(i=function(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=s,e.height=r;const i=new Uint8Array(s*r*4),A=t.createImageData(s,r);return{width:s,height:r,getUpdatedCanvas:()=>{n.readPixels(0,0,s,r,n.RGBA,n.UNSIGNED_BYTE,i);const o=Math.floor(r/2),a=4*s,l=new Uint8Array(a);for(let e=0;e<o;++e){const t=e*a,s=(r-e-1)*a;l.set(i.subarray(t,t+a)),i.copyWithin(t,s,s+a),i.set(l,s)}return A.data.set(i),t.resetTransform(),t.putImageData(A,0,0),e}}}()),e&&(n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),_=!0,this.render(),_=!0),i.getUpdatedCanvas()},endSnapshot:()=>{e&&(t.unbind(),e=!1),_=!0,this.render()}}})(),this.destroy=function(){l={},c={},C.destroy(),E.destroy(),F.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class GA extends D{constructor(e,t={}){super(e,t),this.KEY_BACKSPACE=8,this.KEY_TAB=9,this.KEY_ENTER=13,this.KEY_SHIFT=16,this.KEY_CTRL=17,this.KEY_ALT=18,this.KEY_PAUSE_BREAK=19,this.KEY_CAPS_LOCK=20,this.KEY_ESCAPE=27,this.KEY_PAGE_UP=33,this.KEY_PAGE_DOWN=34,this.KEY_END=35,this.KEY_HOME=36,this.KEY_LEFT_ARROW=37,this.KEY_UP_ARROW=38,this.KEY_RIGHT_ARROW=39,this.KEY_DOWN_ARROW=40,this.KEY_INSERT=45,this.KEY_DELETE=46,this.KEY_NUM_0=48,this.KEY_NUM_1=49,this.KEY_NUM_2=50,this.KEY_NUM_3=51,this.KEY_NUM_4=52,this.KEY_NUM_5=53,this.KEY_NUM_6=54,this.KEY_NUM_7=55,this.KEY_NUM_8=56,this.KEY_NUM_9=57,this.KEY_A=65,this.KEY_B=66,this.KEY_C=67,this.KEY_D=68,this.KEY_E=69,this.KEY_F=70,this.KEY_G=71,this.KEY_H=72,this.KEY_I=73,this.KEY_J=74,this.KEY_K=75,this.KEY_L=76,this.KEY_M=77,this.KEY_N=78,this.KEY_O=79,this.KEY_P=80,this.KEY_Q=81,this.KEY_R=82,this.KEY_S=83,this.KEY_T=84,this.KEY_U=85,this.KEY_V=86,this.KEY_W=87,this.KEY_X=88,this.KEY_Y=89,this.KEY_Z=90,this.KEY_LEFT_WINDOW=91,this.KEY_RIGHT_WINDOW=92,this.KEY_SELECT_KEY=93,this.KEY_NUMPAD_0=96,this.KEY_NUMPAD_1=97,this.KEY_NUMPAD_2=98,this.KEY_NUMPAD_3=99,this.KEY_NUMPAD_4=100,this.KEY_NUMPAD_5=101,this.KEY_NUMPAD_6=102,this.KEY_NUMPAD_7=103,this.KEY_NUMPAD_8=104,this.KEY_NUMPAD_9=105,this.KEY_MULTIPLY=106,this.KEY_ADD=107,this.KEY_SUBTRACT=109,this.KEY_DECIMAL_POINT=110,this.KEY_DIVIDE=111,this.KEY_F1=112,this.KEY_F2=113,this.KEY_F3=114,this.KEY_F4=115,this.KEY_F5=116,this.KEY_F6=117,this.KEY_F7=118,this.KEY_F8=119,this.KEY_F9=120,this.KEY_F10=121,this.KEY_F11=122,this.KEY_F12=123,this.KEY_NUM_LOCK=144,this.KEY_SCROLL_LOCK=145,this.KEY_SEMI_COLON=186,this.KEY_EQUAL_SIGN=187,this.KEY_COMMA=188,this.KEY_DASH=189,this.KEY_PERIOD=190,this.KEY_FORWARD_SLASH=191,this.KEY_GRAVE_ACCENT=192,this.KEY_OPEN_BRACKET=219,this.KEY_BACK_SLASH=220,this.KEY_CLOSE_BRACKET=221,this.KEY_SINGLE_QUOTE=222,this.KEY_SPACE=32,this.MOUSE_LEFT_BUTTON=260,this.MOUSE_MIDDLE_BUTTON=261,this.MOUSE_RIGHT_BUTTON=262,this.element=t.element,this.altDown=!1,this.ctrlDown=!1,this.mouseDownLeft=!1,this.mouseDownMiddle=!1,this.mouseDownRight=!1,this.keyDown=[],this.enabled=!0,this.keyboardEnabled=!0,this.mouseover=!1,this.mouseCanvasPos=d.vec2(),this._keyboardEventsElement=t.keyboardEventsElement||document,this._bindEvents()}_bindEvents(){if(this._eventsBound)return;this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){const t=e.target.getBoundingClientRect();this.mouseCanvasPos[0]=e.clientX-t.left,this.mouseCanvasPos[1]=e.clientY-t.top}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}class jA extends D{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new oe({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class WA extends D{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new oe({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),d.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const n=this.scene.canvas.canvas,A=n.offsetWidth/2,o=n.offsetHeight/2;return i[0]=(e[0]-A)/A,i[1]=(e[1]-o)/o,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class zA extends D{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new oe({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],n=s/r;let A,o,a,l;s>r?(A=-t,o=t,a=t/n,l=-t/n):(A=-t*n,o=t*n,a=t,l=-t),d.orthoMat4c(A,o,l,a,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const n=this.scene.canvas.canvas,A=n.offsetWidth/2,o=n.offsetHeight/2;return i[0]=(e[0]-A)/A,i[1]=(e[1]-o)/o,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class XA extends D{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new oe({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){d.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const n=this.scene.canvas.canvas,A=n.offsetWidth/2,o=n.offsetHeight/2;return i[0]=(e[0]-A)/A,i[1]=(e[1]-o)/o,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class KA extends D{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new oe({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const n=this.scene.canvas.canvas,A=n.offsetWidth/2,o=n.offsetHeight/2;return i[0]=(e[0]-A)/A,i[1]=(e[1]-o)/o,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const ZA=d.vec3(),JA=d.vec3(),YA=d.vec3(),$A=d.vec3(),qA=d.vec3(),eo=d.vec3(),to=d.vec4(),io=d.vec4(),so=d.vec4(),ro=d.mat4(),no=d.mat4(),Ao=d.vec3(),oo=d.vec3(),ao=d.vec3(),lo=d.vec3();class co extends D{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new oe({offsetEyeFromLook:!0,deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new WA(this),this._ortho=new zA(this),this._frustum=new XA(this),this._customProjection=new KA(this),this._project=this._perspective,this._eye=d.vec3([0,0,10]),this._look=d.vec3([0,0,0]),this._up=d.vec3([0,1,0]),this._worldUp=d.vec3([0,1,0]),this._worldRight=d.vec3([1,0,0]),this._worldForward=d.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection&&this._state.offsetEyeFromLook?(d.subVec3(this._eye,this._look,Ao),d.normalizeVec3(Ao,oo),d.mulVec3Scalar(oo,1e3,ao),d.addVec3(this._look,ao,lo),t=lo):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,no),d.mulMat4(e.deviceMatrix,no,e.matrix)):d.lookAtMat4v(t,this._look,this._up,e.matrix),d.inverseMat4(this._state.matrix,this._state.inverseMatrix),d.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=d.subVec3(this._eye,this._look,ZA);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,ro),t=d.transformPoint3(ro,t,JA),this.eye=d.addVec3(this._look,t,YA),this.up=d.transformPoint3(ro,this._up,$A)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,ZA);const i=d.cross3Vec3(d.normalizeVec3(t,JA),d.normalizeVec3(this._up,YA));d.rotationMat4v(.0174532925*e,i,ro),t=d.transformPoint3(ro,t,$A),this.up=d.transformPoint3(ro,this._up,qA),this.eye=d.addVec3(t,this._look,eo)}yaw(e){let t=d.subVec3(this._look,this._eye,ZA);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,ro),t=d.transformPoint3(ro,t,JA),this.look=d.addVec3(t,this._eye,YA),this._gimbalLock&&(this.up=d.transformPoint3(ro,this._up,$A))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,ZA);const i=d.cross3Vec3(d.normalizeVec3(t,JA),d.normalizeVec3(this._up,YA));d.rotationMat4v(.0174532925*e,i,ro),this.up=d.transformPoint3(ro,this._up,eo),t=d.transformPoint3(ro,t,$A),this.look=d.addVec3(t,this._eye,qA)}pan(e){const t=d.subVec3(this._eye,this._look,ZA),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,JA));s=d.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=d.mulVec3Scalar(d.normalizeVec3(this._up,YA),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,$A),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,qA),this.look=d.addVec3(this._look,i,eo)}zoom(e){const t=d.subVec3(this._eye,this._look,ZA),i=Math.abs(d.lenVec3(t,JA)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,YA);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),$A)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=d.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return d.lenVec3(d.subVec3(this._look,this._eye,ZA))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}get offsetEyeFromLook(){return this._state.offsetEyeFromLook}set offsetEyeFromLook(e){this._state.offsetEyeFromLook=e,this._needUpdate(0)}projectWorldPos(e){const t=to,i=io,s=so;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,d.mulMat4v4(this.viewMatrix,t,i),d.mulMat4v4(this.projMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,n=r.offsetWidth/2,A=r.offsetHeight/2;return[s[0]*n+n,s[1]*A+A]}destroy(){super.destroy(),this._state.destroy()}}const ho={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class uo extends D{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=d.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return ho}set units(e){e||(e="meters");ho[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=d.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=d.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class fo extends D{constructor(e,t={}){super(e,t),this._supported=PA.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class po extends D{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const go={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class mo extends Vi{get type(){return"PointsMaterial"}get presets(){return go}constructor(e,t={}){super(e,t),this._state=new oe({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=go[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(go).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const _o={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class bo extends Vi{get type(){return"LinesMaterial"}get presets(){return _o}constructor(e,t={}){super(e,t),this._state=new oe({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=_o[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(_o).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function yo(e,t,i=2){const s=t&&t.length,r=s?t[0]*i:e.length;let n=wo(e,0,r,i,!0);const A=[];if(!n||n.next===n.prev)return A;let o,a,l;if(s&&(n=function(e,t,i,s){const r=[];for(let i=0,n=t.length;i<n;i++){const A=wo(e,t[i]*s,i<n-1?t[i+1]*s:e.length,s,!1);A===A.next&&(A.steiner=!0),r.push(Po(A))}r.sort(Uo);for(let e=0;e<r.length;e++)i=xo(r[e],i);return i}(e,t,n,i)),e.length>80*i){o=1/0,a=1/0;let t=-1/0,s=-1/0;for(let n=i;n<r;n+=i){const i=e[n],r=e[n+1];i<o&&(o=i),r<a&&(a=r),i>t&&(t=i),r>s&&(s=r)}l=Math.max(t-o,s-a),l=0!==l?32767/l:0}return Bo(n,A,i,o,a,l,0),A}function wo(e,t,i,s,r){let n;if(r===function(e,t,i,s){let r=0;for(let n=t,A=i-s;n<i;n+=s)r+=(e[A]-e[n])*(e[n+1]+e[A+1]),A=n;return r}(e,t,i,s)>0)for(let r=t;r<i;r+=s)n=Go(r/s|0,e[r],e[r+1],n);else for(let r=i-s;r>=t;r-=s)n=Go(r/s|0,e[r],e[r+1],n);return n&&Ro(n,n.next)&&(jo(n),n=n.next),n}function vo(e,t){if(!e)return e;t||(t=e);let i,s=e;do{if(i=!1,s.steiner||!Ro(s,s.next)&&0!==Qo(s.prev,s,s.next))s=s.next;else{if(jo(s),s=t=s.prev,s===s.next)break;i=!0}}while(i||s!==t);return t}function Bo(e,t,i,s,r,n,A){if(!e)return;!A&&n&&function(e,t,i,s){let r=e;do{0===r.z&&(r.z=To(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,i=1;do{let s,r=e;e=null;let n=null;for(t=0;r;){t++;let A=r,o=0;for(let e=0;e<i&&(o++,A=A.nextZ,A);e++);let a=i;for(;o>0||a>0&&A;)0!==o&&(0===a||!A||r.z<=A.z)?(s=r,r=r.nextZ,o--):(s=A,A=A.nextZ,a--),n?n.nextZ=s:e=s,s.prevZ=n,n=s;r=A}n.nextZ=null,i*=2}while(t>1)}(r)}(e,s,r,n);let o=e;for(;e.prev!==e.next;){const a=e.prev,l=e.next;if(n?Mo(e,s,r,n):Co(e))t.push(a.i,e.i,l.i),jo(e),e=l.next,o=l.next;else if((e=l)===o){A?1===A?Bo(e=Eo(vo(e),t),t,i,s,r,n,2):2===A&&Fo(e,t,i,s,r,n):Bo(vo(e),t,i,s,r,n,1);break}}}function Co(e){const t=e.prev,i=e,s=e.next;if(Qo(t,i,s)>=0)return!1;const r=t.x,n=i.x,A=s.x,o=t.y,a=i.y,l=s.y,c=Math.min(r,n,A),h=Math.min(o,a,l),u=Math.max(r,n,A),d=Math.max(o,a,l);let f=s.next;for(;f!==t;){if(f.x>=c&&f.x<=u&&f.y>=h&&f.y<=d&&Do(r,o,n,a,A,l,f.x,f.y)&&Qo(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function Mo(e,t,i,s){const r=e.prev,n=e,A=e.next;if(Qo(r,n,A)>=0)return!1;const o=r.x,a=n.x,l=A.x,c=r.y,h=n.y,u=A.y,d=Math.min(o,a,l),f=Math.min(c,h,u),p=Math.max(o,a,l),g=Math.max(c,h,u),m=To(d,f,t,i,s),_=To(p,g,t,i,s);let b=e.prevZ,y=e.nextZ;for(;b&&b.z>=m&&y&&y.z<=_;){if(b.x>=d&&b.x<=p&&b.y>=f&&b.y<=g&&b!==r&&b!==A&&Do(o,c,a,h,l,u,b.x,b.y)&&Qo(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,y.x>=d&&y.x<=p&&y.y>=f&&y.y<=g&&y!==r&&y!==A&&Do(o,c,a,h,l,u,y.x,y.y)&&Qo(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;b&&b.z>=m;){if(b.x>=d&&b.x<=p&&b.y>=f&&b.y<=g&&b!==r&&b!==A&&Do(o,c,a,h,l,u,b.x,b.y)&&Qo(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;y&&y.z<=_;){if(y.x>=d&&y.x<=p&&y.y>=f&&y.y<=g&&y!==r&&y!==A&&Do(o,c,a,h,l,u,y.x,y.y)&&Qo(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function Eo(e,t){let i=e;do{const s=i.prev,r=i.next.next;!Ro(s,r)&&Oo(s,i,i.next,r)&&Ho(s,r)&&Ho(r,s)&&(t.push(s.i,i.i,r.i),jo(i),jo(i.next),i=e=r),i=i.next}while(i!==e);return vo(i)}function Fo(e,t,i,s,r,n){let A=e;do{let e=A.next.next;for(;e!==A.prev;){if(A.i!==e.i&&ko(A,e)){let o=No(A,e);return A=vo(A,A.next),o=vo(o,o.next),Bo(A,t,i,s,r,n,0),void Bo(o,t,i,s,r,n,0)}e=e.next}A=A.next}while(A!==e)}function Uo(e,t){let i=e.x-t.x;if(0===i&&(i=e.y-t.y,0===i)){i=(e.next.y-e.y)/(e.next.x-e.x)-(t.next.y-t.y)/(t.next.x-t.x)}return i}function xo(e,t){const i=function(e,t){let i=t;const s=e.x,r=e.y;let n,A=-1/0;if(Ro(e,i))return i;do{if(Ro(e,i.next))return i.next;if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){const e=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=s&&e>A&&(A=e,n=i.x<i.next.x?i:i.next,e===s))return n}i=i.next}while(i!==t);if(!n)return null;const o=n,a=n.x,l=n.y;let c=1/0;i=n;do{if(s>=i.x&&i.x>=a&&s!==i.x&&So(r<l?s:A,r,a,l,r<l?A:s,r,i.x,i.y)){const t=Math.abs(r-i.y)/(s-i.x);Ho(i,e)&&(t<c||t===c&&(i.x>n.x||i.x===n.x&&Io(n,i)))&&(n=i,c=t)}i=i.next}while(i!==o);return n}(e,t);if(!i)return t;const s=No(i,e);return vo(s,s.next),vo(i,i.next)}function Io(e,t){return Qo(e.prev,e,t.prev)<0&&Qo(t.next,e,e.next)<0}function To(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-s)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Po(e){let t=e,i=e;do{(t.x<i.x||t.x===i.x&&t.y<i.y)&&(i=t),t=t.next}while(t!==e);return i}function So(e,t,i,s,r,n,A,o){return(r-A)*(t-o)>=(e-A)*(n-o)&&(e-A)*(s-o)>=(i-A)*(t-o)&&(i-A)*(n-o)>=(r-A)*(s-o)}function Do(e,t,i,s,r,n,A,o){return!(e===A&&t===o)&&So(e,t,i,s,r,n,A,o)}function ko(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&Oo(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Ho(e,t)&&Ho(t,e)&&function(e,t){let i=e,s=!1;const r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(Qo(e.prev,e,t.prev)||Qo(e,t.prev,t))||Ro(e,t)&&Qo(e.prev,e,e.next)>0&&Qo(t.prev,t,t.next)>0)}function Qo(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Ro(e,t){return e.x===t.x&&e.y===t.y}function Oo(e,t,i,s){const r=Lo(Qo(e,t,i)),n=Lo(Qo(e,t,s)),A=Lo(Qo(i,s,e)),o=Lo(Qo(i,s,t));return r!==n&&A!==o||(!(0!==r||!Vo(e,i,t))||(!(0!==n||!Vo(e,s,t))||(!(0!==A||!Vo(i,e,s))||!(0!==o||!Vo(i,t,s)))))}function Vo(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function Lo(e){return e>0?1:e<0?-1:0}function Ho(e,t){return Qo(e.prev,e,e.next)<0?Qo(e,t,e.next)>=0&&Qo(e,e.prev,t)>=0:Qo(e,t,e.prev)<0||Qo(e,e.next,t)<0}function No(e,t){const i=Wo(e.i,e.x,e.y),s=Wo(t.i,t.x,t.y),r=e.next,n=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function Go(e,t,i,s){const r=Wo(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function jo(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function Wo(e,t,i){return{i:e,x:t,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}const zo=[0,1,0],Xo=[1,0,0],Ko=d.vec3(),Zo=d.vec3(),Jo=d.vec3(),Yo=d.vec3(),$o=d.vec3();function qo(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6&&Math.abs(e[2]-t[2])<1e-6}class ea{constructor(e){this.scene=e,this._resourcesAllocated=!1}_onCapMaterialUpdated(e,t){if(!this._resourcesAllocated){this._resourcesAllocated=!0,this._sectionPlanes=[],this._sceneModelsData={},this._dirtyMap={},this._prevIntersectionModelsMap={},this._sectionPlaneTimeout=null,this._updateTimeout=null;const e=e=>{const t=()=>{this._setAllDirty(!0),this._update()};this._sectionPlanes.push(e),e.on("pos",t),e.on("dir",t),e.on("active",t),e.once("destroyed",(()=>{const t=e.id;t&&(this._sectionPlanes=this._sectionPlanes.filter((e=>e.id!==t)),this._update())}).bind(this))};for(const t in this.scene.sectionPlanes)e(this.scene.sectionPlanes[t]);this._onSectionPlaneCreated=this.scene.on("sectionPlaneCreated",e),this._onTick=this.scene.on("tick",(()=>{let e=!1;for(const t in this._sceneModelsData)this.scene.models[t]?this._sceneModelsData[t].visible!==!!this.scene.models[t].visible&&(this._sceneModelsData[t].visible=!!this.scene.models[t].visible,e=!0):(delete this._sceneModelsData[t],e=!0);e&&this._update()}))}this._dirtyMap[t]||(this._dirtyMap[t]=new Map),this._dirtyMap[t].set(e,!0),this._update()}_update(){clearTimeout(this._updateTimeout),this._deletePreviousModels(),this._updateTimeout=setTimeout((()=>{clearTimeout(this._updateTimeout);const e=Object.values(this.scene.models).filter((e=>e.visible));this._addHatches(e,this._sectionPlanes.filter((e=>e.active))),this._setAllDirty(!1)}),100)}_setAllDirty(e){for(const t in this._dirty)this._dirtyMap[t].forEach(((i,s)=>this._dirtyMap[t].set(s,e)))}_addHatches(e,t){t.forEach((t=>{e.forEach((e=>{if(!this._doesPlaneIntersectBoundingBox(e.aabb,t))return;if(!this._dirtyMap[e.id])return;const i=new Map,s=e.objects,r=[d.vec3(),d.vec3(),d.vec3()];this._dirtyMap[e.id].forEach(((n,A)=>{if(!n)return;const o=s[A];if(!this._doesPlaneIntersectBoundingBox(o.aabb,t))return;if(!this._sceneModelsData[e.id]){const t=e.aabb;this._sceneModelsData[e.id]={verticesMap:new Map,indicesMap:new Map,modelOrigin:d.vec3([(t[0]+t[3])/2,(t[1]+t[4])/2,(t[2]+t[5])/2])}}const a=this._sceneModelsData[e.id],l=a.modelOrigin;if(!a.verticesMap.has(A)){const e=o.meshes[0].isSolid(),t=[],i=[];e&&o.capMaterial&&(o.getEachVertex((e=>t.push(e[0]-l[0],e[1]-l[1],e[2]-l[2]))),o.getEachIndex((e=>i.push(e)))),a.verticesMap.set(A,t),a.indicesMap.set(A,i)}const c=a.verticesMap.get(A),h=a.indicesMap.get(A),u=-d.dotVec3(d.subVec3(t.pos,l,Ko),t.dir),f=[],p=h.length;for(let e=0;e<p;e+=3){for(let t=0;t<3;t++){const i=3*h[e+t];r[t][0]=c[i],r[t][1]=c[i+1],r[t][2]=c[i+2]}if(!r[0][0]&&!r[0][1]&&!r[0][2])continue;const i=[];for(let e=0;e<3;e++){const s=r[e],n=r[(e+1)%3],A=u+d.dotVec3(t.dir,s),o=u+d.dotVec3(t.dir,n);if(A*o>0)continue;const a=-A/(o-A);i.push(d.lerpVec3(a,0,1,s,n,d.vec3()))}2===i.length&&f.push(i)}f.length>0&&i.set(A,f)}));const n=new Map;i.forEach(((e,t)=>{n.set(t,[[e[0]]]),e.splice(0,1);let s=0;for(;e.length>0;){const r=n.get(t)[s][n.get(t)[s].length-1][1];let A=!1;for(let i=0;i<e.length;i++){const[o,a]=e[i];if(qo(r,o)){n.get(t)[s].push(e[i]),e.splice(i,1),A=!0;break}if(qo(r,a)){n.get(t)[s].push([a,o]),e.splice(i,1),A=!0;break}}if(!A&&qo(r,n.get(t)[s][0][0])&&e.length>1)n.get(t).push([i.get(t)[0]]),e.splice(0,1),s++;else if(!A)break}}));const A=new Map;n.forEach(((e,i)=>{const s=[];for(let i=0;i<e.length;i++)s.push([]),e[i].forEach((e=>{s[i].push([this._projectTo2D(e[0],t.dir),this._projectTo2D(e[1],t.dir)])}));A.set(i,s)}));const o=new Map;let a;A.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin;a=[];const n=i,A=[],l=new Set;for(let e=0;e<n.length;e++){if(l.has(e))continue;const t=[n[e]];l.add(e);for(let i=e+1;i<n.length;i++)l.has(i)||(this._isLoopInside(n[e],n[i])||this._isLoopInside(n[i],n[e]))&&(t.push(n[i]),l.add(i));A.push(t)}A.forEach((e=>{const i=[],s=[];let n=0;const A=e.map((e=>{let t=0;for(let i=0;i<e.length;i++){const s=(i+1)%e.length;t+=e[i][0][0]*e[s][0][1],t-=e[s][0][0]*e[i][0][1]}return Math.abs(t)/2})),o=A.indexOf(Math.max(...A));e[o].forEach((e=>{i.push(e[0][0],e[0][1]),n+=2}));for(let t=0;t<e.length;t++)t!==o&&(s.push(n/2),e[t].forEach((e=>{i.push(e[0][0],e[0][1]),n+=2})));const l=yo(i,s),c=[];for(let e=0;e<l.length;e+=3){const s=[];for(let n=0;n<3;n++){const A=2*l[e+n],o=[i[A],i[A+1]],a=this._convertTo3D(o,t,r);s.push(a)}c.push(s)}a.push(c)})),o.set(s,a)}));const l=new Map;o.forEach(((e,t)=>{a=[],e.forEach((e=>{const t=new Map,i=[],s=[];let r=0;e.forEach((e=>{const n=[];e.forEach((e=>{const s=`${e[0].toFixed(6)},${e[1].toFixed(6)},${e[2].toFixed(6)}`;t.has(s)?n.push(t.get(s)):(i.push(e[0],e[1],e[2]),t.set(s,r),n.push(r),r++)})),s.push(...n)})),a.push({positions:i,indices:s})})),l.set(t,a)})),this._prevIntersectionModelsMap[e.id]||(this._prevIntersectionModelsMap[e.id]=new Map),d.mulVec3Scalar(t.dir,.001,$o),l.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin,n=new Array(i.size);let A=0;i.forEach(((i,o)=>{const a=i.positions,l=i.indices;a.length;const c=d.buildNormals(a,l),h=this._createUVs(a,t,r);n[A++]=new Qi(this.scene,{id:`${t.id}-${s}-${o}`,geometry:new be(this.scene,{primitive:"triangles",positions:a,indices:l,normals:c,uv:h}),origin:d.addVec3(r,$o,Ko),position:[0,0,0],rotation:[0,0,0],material:e.objects[s].capMaterial})})),this._prevIntersectionModelsMap[e.id].has(s)?this._prevIntersectionModelsMap[e.id].get(s).push(...n):this._prevIntersectionModelsMap[e.id].set(s,n)}))}))}))}_doesPlaneIntersectBoundingBox(e,t){const i=[e[0],e[1],e[2]],s=[e[3],e[4],e[5]],r=[[i[0],i[1],i[2]],[s[0],i[1],i[2]],[i[0],s[1],i[2]],[s[0],s[1],i[2]],[i[0],i[1],s[2]],[s[0],i[1],s[2]],[i[0],s[1],s[2]],[s[0],s[1],s[2]]];let n=!1,A=!1;for(const e of r){const i=t.dist+d.dotVec3(t.dir,e);if(i>0&&(n=!0),i<0&&(A=!0),n&&A)return!0}return!1}_buildLines(e){for(const t in e)for(let i=0;i<e[t].length;i++){const s=e[t][i];s.length<=0||s.forEach(((e,t)=>{new Qi(this.scene,{clippable:!1,geometry:new be(this.scene,Oe({startPoint:e[0],endPoint:e[1]})),material:new Ni(this.scene,{emissive:[1,0,0]})})}))}}_projectTo2D(e,t){let i;i=Math.abs(t[0])>Math.abs(t[1])?[-t[2],0,t[0]]:[0,t[2],-t[1]],i=d.normalizeVec3(i);const s=d.vec3(t),r=d.cross3Vec3(s,i),n=d.normalizeVec3(r);return[d.dotVec3(e,i),d.dotVec3(e,n)]}_isLoopInside(e,t){const i=e[0][0];let s=!1;for(let e=0,r=t.length-1;e<t.length;r=e++){const n=t[e][0][0],A=t[e][0][1],o=t[r][0][0],a=t[r][0][1];A>i[1]!=a>i[1]&&i[0]<(o-n)*(i[1]-A)/(a-A)+n&&(s=!s)}return s}_convertTo3D(e,t,i){let s,r=t.dir,n=t.pos;s=Math.abs(r[0])>Math.abs(r[1])?[-r[2],0,r[0]]:[0,r[2],-r[1]],s=d.normalizeVec3(s);const A=d.vec3(r),o=d.cross3Vec3(A,s),a=d.normalizeVec3(o),l=e[0],c=e[1],h=[s[0]*l+a[0]*c,s[1]*l+a[1]*c,s[2]*l+a[2]*c],u=d.dotVec3(r,[n[0]-h[0]-i[0],n[1]-h[1]-i[1],n[2]-h[2]-i[2]]);return[h[0]+r[0]*u,h[1]+r[1]*u,h[2]+r[2]*u]}_deletePreviousModels(){for(const e in this._prevIntersectionModelsMap){this._prevIntersectionModelsMap[e].forEach(((t,i)=>{this._dirtyMap[e].get(i)&&(t.forEach((e=>{e.destroy()})),this._prevIntersectionModelsMap[e].delete(i))})),this._prevIntersectionModelsMap[e].size<=0&&delete this._prevIntersectionModelsMap[e]}}_createUVs(e,t,i){const s=t.pos,r=Ko;r.set(t.dir),d.normalizeVec3(r);const n=Zo,A=[];for(let t=0;t<e.length;t+=3){n[0]=e[t]+i[0],n[1]=e[t+1]+i[1],n[2]=e[t+2]+i[2];const o=d.subVec3(n,s,Jo),a=d.dotVec3(o,r);d.subVec3(n,d.mulVec3Scalar(r,a,Jo),n);const l=Math.abs(d.dotVec3(r,zo))<.999?d.cross3Vec3(r,zo,Jo):Xo,c=d.cross3Vec3(r,l,Jo);d.normalizeVec3(c,c);const h=d.subVec3(n,s,n);A.push(d.dotVec3(h,d.normalizeVec3(d.cross3Vec3(c,r,Yo))),d.dotVec3(h,c))}return A}destroy(){this._deletePreviousModels(),this._resourcesAllocated&&(this.scene.off(this._onModelLoaded),this.scene.off(this._onModelUnloaded),this.scene.off(this._onSectionPlaneCreated),this.scene.off(this._onTick))}}function ta(e,t){const i={};let s,r;for(let n=0,A=t.length;n<A;n++)s=t[n],r=e.components[s],r?r.isEntity?i[s]=!0:e.warn("pick(): Component is not an Entity: "+s):e.warn("pick(): Component not found: "+s);return i}class ia extends D{get type(){return"Scene"}constructor(e,t={}){super(null,t);const i=t.canvasElement||document.querySelector(`#${t.canvasId}`);if(!(i instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";this._tickifiedFunctions={};const s=!!t.transparent,r=!!t.alphaDepthMask;this._aabbDirty=!0,this._readableGeometry=!!t.readableGeometryEnabled,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.bitmaps={},this.lineSets={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new IA(this,{dontClear:!0,canvas:i,spinnerElementId:t.spinnerElementId,transparent:s,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha});const n=e=>this.viewer.destroy();i.addEventListener("webglcontextlost",n,!1),this._removeWebglcontextlostListener=()=>i.removeEventListener("webglcontextlost",n,!1),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new NA(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;e<s;e++)i.push("cp");return i.push(";"),e=i.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let i=0,s=this.sectionPlanes.length;i<s;i++)if(this.sectionPlanes[i].id===t.id)return this.sectionPlanes.splice(i,1),void(e=null)},this.setNumCachedSectionPlanes=function(t){this._numCachedSectionPlanes=t,e=null},this.getNumCachedSectionPlanes=function(){return this._numCachedSectionPlanes},this.getNumAllocatedSectionPlanes=function(){const e=this.sectionPlanes.length;return e>this._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=d.vec4([0,0,0,0]),t=d.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i<r;i++)s=t[i],e.push("/"),e.push(s.type),e.push("world"===s.space?"w":"v"),s.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t<r;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),s&&s.id===e.id&&(s=null),void(i=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),i=null},this.removeReflectionMap=function(e){for(let t=0,s=this.reflectionMaps.length;t<s;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(i=null)},this.addLightMap=function(e){this.lightMaps.push(e),i=null},this.removeLightMap=function(e){for(let t=0,s=this.lightMaps.length;t<s;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(i=null)},this.getAmbientColorAndIntensity=function(){if(!s)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){s=t;break}}if(s){const e=s.color,i=s.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=i,t}return e}},this.input=new GA(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new uo(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new fo(this,{enabled:t.saoEnabled}),this.crossSections=new po(this,{}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._dtxEnabled=!1!==t.dtxEnabled,this._pbrEnabled=!!t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._dtxEnabled=!!t.dtxEnabled,this._markerZOffset=t.markerZOffset,I._addScene(this),this._initDefaults(),this._viewport=new jA(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new co(this,{id:"default.camera",dontClear:!0}),this._sectionCaps=new ea(this),new Kn(this,{color:[1,1,1],intensity:.7}),new Jn(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new Jn(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+w.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=d.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],w.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_capMaterialUpdated(e,t){this._sectionCaps._onCapMaterialUpdated(e,t)}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get readableGeometryEnabled(){return this._readableGeometry}get pickSurfacePrecisionEnabled(){return this._readableGeometry}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&I.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),e||this._renderer.needsRender()){t.sceneId=this.id;for(let i=0;i<this._passes;i++)t.pass=i,this.fire("rendering",t,!0),e&&this._renderer.imageDirty(),this._renderer.render(i,this._clearEachPass||0===i),this.fire("rendered",t,!0);this._saveAmbientColor()}}compile(){this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1)}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=d.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!w.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!w.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!w.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||Ee(be)}get material(){return this.components["default.material"]||new Ni(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new us(this,{id:"default.xrayMaterial",fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new us(this,{id:"default.highlightMaterial",fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new us(this,{id:"default.selectedMaterial",fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new fs(this,{id:"default.edgeMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new mo(this,{id:"default.pointsMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new bo(this,{id:"default.linesMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){const e=this.aabb;this._center||(this._center=d.vec3()),this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=d.AABB3());let e,t=d.MAX_DOUBLE,i=d.MAX_DOUBLE,s=d.MAX_DOUBLE,r=d.MIN_DOUBLE,n=d.MIN_DOUBLE,A=d.MIN_DOUBLE;const o=this._collidables;let a,l=!1;for(const c in o)if(o.hasOwnProperty(c)){if(a=o[c],!1===a.collidable)continue;e=a.aabb,e[0]<t&&(t=e[0]),e[1]<i&&(i=e[1]),e[2]<s&&(s=e[2]),e[3]>r&&(r=e[3]),e[4]>n&&(n=e[4]),e[5]>A&&(A=e[5]),l=!0}l||(t=-100,i=-100,s=-100,r=100,n=100,A=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=n,this._aabb[5]=A,this._aabbDirty=!1,this._center=null}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(!this.canvas)return this.error("Picking not allowed on a destroyed Scene"),null;if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=ta(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=ta(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return this.canvas?(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos?this._renderer.snapPick(e):void this.error("Scene.snapPick() canvasPos parameter expected")):(this.error("Picking not allowed on a destroyed Scene"),null)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t<i;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,i=e.length;t<i;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,i=e.length;t<i;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,i=e.length;t<i;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(w.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,i=d.MAX_DOUBLE,s=d.MAX_DOUBLE,r=d.MAX_DOUBLE,n=d.MIN_DOUBLE,A=d.MIN_DOUBLE,o=d.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const a=e.aabb;a[0]<i&&(i=a[0]),a[1]<s&&(s=a[1]),a[2]<r&&(r=a[2]),a[3]>n&&(n=a[3]),a[4]>A&&(A=a[4]),a[5]>o&&(o=a[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=n,e[4]=A,e[5]=o,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){w.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s<r;s++){const r=e[s];let n=this.objects[r];if(n)i=t(n)||i;else{const e=this.modelIds;for(let s=0,A=e.length;s<A;s++){const A=e[s],o=d.globalizeObjectId(A,r);n=this.objects[o],n&&(i=t(n)||i)}}}return i}tickify(e){const t=e.toString();if(t in this._tickifiedFunctions)return this._tickifiedFunctions[t].wrapperFunc;let i,s=0,r=0;const n=function(...e){i=e,r++},A=this.on("tick",(()=>{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:A,wrapperFunc:n},n}destroy(){super.destroy(),this._removeWebglcontextlostListener();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this._sectionCaps.destroy(),this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._sectionCaps=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const sa=d.vec4(),ra=d.vec4(),na=d.vec3(),Aa=d.vec3(),oa=d.vec3(),aa=d.vec4(),la=d.vec4(),ca=d.vec4();class ha{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=d.subVec3(e,r.eye,na);s=d.lenVec3(t)<i}if("perspective"===r.projection){r.ortho.scale=r.ortho.scale-i;const s=this._unproject(t,aa),n=d.subVec3(s,r.eye,ca),A=d.mulVec3Scalar(d.normalizeVec3(n),-i,[]);if(r.eye=[r.eye[0]-A[0],r.eye[1]-A[1],r.eye[2]-A[2]],r.look=[r.look[0]-A[0],r.look[1]-A[1],r.look[2]-A[2]],e){const t=d.subVec3(e,r.eye,na),i=d.lenVec3(t),s=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(r.look,r.eye,Aa)),i);r.look=[r.eye[0]+s[0],r.eye[1]+s[1],r.eye[2]+s[2]]}}else if("ortho"===r.projection){const e=this._unproject(t,aa);r.ortho.scale=r.ortho.scale-i,r.ortho._update();const s=this._unproject(t,la),n=d.subVec3(s,e,ca),A=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(r.look,r.eye,na)),-i,Aa),o=d.addVec3(n,A,oa);r.eye=[r.eye[0]-o[0],r.eye[1]-o[1],r.eye[2]-o[2]],r.look=[r.look[0]-o[0],r.look[1]-o[1],r.look[2]-o[2]]}return s}_unproject(e,t){const i=this._scene.camera,s=i.project.transposedMatrix,r=s.subarray(8,12),n=s.subarray(12),A=[0,0,-1,1],o=d.dotVec4(A,r)/d.dotVec4(A,n);return i.project.unproject(e,o,sa,ra,t),t}destroy(){}}const ua=d.vec3(),da=d.vec3(),fa=d.vec3(),pa=d.vec4(),ga=d.vec4(),ma=d.vec4(),_a=Math.PI-.001;class ba{constructor(e,t){this._scene=e,this._configs=t,this._pivotWorldPos=d.vec3(),this._cameraOffset=d.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotSphereEnabled=!1,this._pivotSphere=null,this._pivotSphereSize=1,this._pivotSphereGeometry=null,this._pivotSphereMaterial=null,this._rtcCenter=d.vec3(),this._rtcPos=d.vec3(),this._pivotViewPos=d.vec4(),this._pivotProjPos=d.vec4(),this._pivotCanvasPos=d.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(()=>{this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const i=d.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),Ye(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new ve(this._scene,Pe({radius:s})),this._pivotSphere=new Qi(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let n=t._lastBoundingClientRect;if(!n||t._canvasSizeChanged){const e=t.canvas;n=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(n.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(n.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(Ye(this.getPivotPos(),this._rtcCenter,this._rtcPos),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Ni(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.up);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,i),t=d.inverseMat4(t);const s=d.transformVec3(t,this._cameraOffset),r=d.vec3();if(d.subVec3(e.eye,i,r),d.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=d.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,ua)),i=d.cross3Vec3(t,e.worldUp,da);return d.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(d.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),n=s.subarray(12),A=[0,0,-1,1],o=d.dotVec4(A,r)/d.dotVec4(A,n),a=pa;t.project.unproject(e,o,ga,ma,a);const l=d.normalizeVec3(d.subVec3(a,t.eye,ua)),c=d.addVec3(t.eye,d.mulVec3Scalar(l,i,da),fa);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s;const n=r<0,A=r>0,o=Math.abs(this._polar-.001)<.005,a=Math.abs(this._polar-_a)<.005;let l=this._polar+.01*r;l=o&&n?.001:a&&A?_a:d.clamp(l,.001,_a),this._polar=l;const c=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=c[1];c[1]=c[2],c[2]=e}const h=d.lenVec3(d.subVec3(i.look,i.eye,d.vec3())),u=this.getPivotPos();d.addVec3(c,u);let f=d.lookAtMat4v(c,u,i.worldUp);f=d.inverseMat4(f);const p=d.transformVec3(f,this._cameraOffset);f[12]-=p[0],f[13]-=p[1],f[14]-=p[2];const g=[f[8],f[9],f[10]];i.eye=[f[12],f[13],f[14]],d.subVec3(i.eye,d.mulVec3Scalar(g,h),i.look),i.up=[f[4],f[5],f[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class ya{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new MA;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const wa=d.vec2();class va{constructor(e,t,i,s,r){this._scene=e;const n=t.pickController,A=t.cameraControl;let o,a,l,c=0,h=0,u=0,f=0,p=!1;const g=d.vec3();let m=!0;const _=this._scene.canvas.canvas,b=[];function y(e=!0){c=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],f=s.pointerCanvasPos[1],e&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.picked&&n.pickedSurface&&n.pickResult&&n.pickResult.worldPos?(p=!0,g.set(n.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;b[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;b[s]=!1}),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{b.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{b.splice(0)}),_.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:b[e.input.KEY_SHIFT]||i.planView?(o=!0,b[e.input.MOUSE_LEFT_BUTTON]=!0,y()):(o=!0,b[e.input.MOUSE_LEFT_BUTTON]=!0,y(!1));break;case 2:a=!0,b[e.input.MOUSE_MIDDLE_BUTTON]=!0,y();break;case 3:l=!0,b[e.input.MOUSE_RIGHT_BUTTON]=!0,i.panRightClick&&y()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!o&&!a&&!l)return;const n=e.canvas.boundary,u=n[2],f=n[3],m=s.pointerCanvasPos[0],_=s.pointerCanvasPos[1],y=i.planView||A._isKeyDownForAction(A.MOUSE_PAN,b),w=A._isKeyDownForAction(A.MOUSE_ROTATE,b),v=document.pointerLockElement?t.movementX:m-c,B=document.pointerLockElement?t.movementY:_-h;if(y){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?d.lenVec3(d.subVec3(g,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*v*i/f,r.panDeltaY+=1.5*B*i/f}else r.panDeltaX+=.5*t.ortho.scale*(v/f),r.panDeltaY+=.5*t.ortho.scale*(B/f)}else w&&(i.planView||(i.firstPerson?(r.rotateDeltaY-=v/u*i.dragRotationRate/2,r.rotateDeltaX+=B/f*(i.dragRotationRate/4)):(r.rotateDeltaY-=v/u*(1.5*i.dragRotationRate),r.rotateDeltaX+=B/f*(1.5*i.dragRotationRate))));c=m,h=_}),_.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(m=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:case 2:case 3:o=!1,a=!1,l=!1,b[e.input.MOUSE_LEFT_BUTTON]=!1,b[e.input.MOUSE_MIDDLE_BUTTON]=!1,b[e.input.MOUSE_RIGHT_BUTTON]=!1}}),_.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,n=0,A=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,n+=i.scrollLeft,A+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+n-s,t[1]=e.pageY+A-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,wa);const i=wa[0],s=wa[1];Math.abs(i-u)<3&&Math.abs(s-f)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:wa,event:e},!0)}_.style.removeProperty("cursor")}}),_.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const w=1/60;let v=null;_.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel&&A._isKeyDownForAction(A.MOUSE_DOLLY,b)))return;const t=performance.now()/1e3;var n=null!==v?t-v:0;v=t,n>.05&&(n=.05),n<w&&(n=w);const o=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===o)return;const a=o/Math.abs(o);r.dollyDelta+=-a*n*i.mouseWheelDollyRate,m&&(s.followPointerDirty=!0,m=!1)},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const Ba=d.vec3(),Ca=d.vec3(),Ma=d.vec3(),Ea=d.vec3(),Fa=d.vec3(),Ua={eye:d.vec3(),look:d.vec3(),up:d.vec3()};class xa{constructor(e,t,i,s){this._scene=e;const r=t.cameraControl,n=e.camera;this._onSceneKeyDown=e.input.on("keydown",(()=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),o=r._isKeyDownForAction(r.AXIS_VIEW_BACK),a=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),l=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),h=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(A||o||a||l||c||h))return;const u=e.aabb,f=d.getAABB3Diag(u);d.getAABB3Center(u,Ba);const p=Math.abs(f/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),g=1.1*f;Ua.orthoScale=g,A?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldRight,p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(n.worldUp)):o?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldForward,p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(n.worldUp)):a?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldRight,-p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(n.worldUp)):l?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldForward,-p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(n.worldUp)):c?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldUp,p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(d.normalizeVec3(d.mulVec3Scalar(n.worldForward,1,Ma),Ea))):h&&(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldUp,-p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(d.normalizeVec3(d.mulVec3Scalar(n.worldForward,-1,Ma)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Ba),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Ua,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Ua),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Ia{constructor(e,t,i,s,r){this._scene=e;const n=t.pickController,A=t.pivotController,o=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null,this._lastClickedWorldPos=null;let a=!1,l=!1;const c=this._scene.canvas.canvas,h=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},u=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(a||l)return;if(o.hasSubs("rayMove")){const t=d.vec3(),i=d.vec3();d.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,e.camera.projection,s.pointerCanvasPos,t,i),o.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=o.hasSubs("hover"),A=o.hasSubs("hoverEnter"),c=o.hasSubs("hoverOut"),h=o.hasSubs("hoverOff"),u=o.hasSubs("hoverSurface"),f=o.hasSubs("hoverSnapOrSurface");if(r||A||c||h||u||f)if(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickEntity=!0,n.schedulePickSurface=u,n.scheduleSnapOrPick=f,n.update(),n.pickResult){if(n.pickResult.entity){const t=n.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&o.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),o.fire("hoverEnter",n.pickResult,!0),this._lastPickedEntityId=t)}o.fire("hover",n.pickResult,!0),(n.pickResult.worldPos||n.pickResult.snappedWorldPos)&&o.fire("hoverSurface",n.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(o.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),o.fire("hoverOff",{canvasPos:n.pickCursorPos},!0)});c.addEventListener("mousemove",u),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(a=!0),3===t.which&&(l=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),1===t.which))){const t=n.pickResult;t&&t.worldPos?(A.setPivotPos(t.worldPos),A.startPivot(),this._lastClickedWorldPos=t.worldPos.slice()):(i.smartPivot?A.setCanvasPivotPos(s.pointerCanvasPos):this._lastClickedWorldPos?A.setPivotPos(this._lastClickedWorldPos):A.setPivotPos(e.camera.look),A.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(a=!1),3===e.which&&(l=!1),A.getPivoting()&&A.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(A.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const a=o.hasSubs("picked"),l=o.hasSubs("pickedNothing"),c=o.hasSubs("pickedSurface"),u=o.hasSubs("doublePicked"),f=o.hasSubs("doublePickedSurface"),p=o.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||f||p))return(a||l||c)&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickEntity=!0,n.schedulePickSurface=c,n.update(),n.pickResult?(o.fire("picked",n.pickResult,!0),n.pickedSurface&&o.fire("pickedSurface",n.pickResult,!0)):o.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){n.pickCursorPos=s.pointerCanvasPos,n.schedulePickEntity=i.doublePickFlyTo,n.schedulePickSurface=c,n.update();const e=n.pickResult,r=n.pickedSurface;this._timeout=setTimeout((()=>{e?(o.fire("picked",e,!0),r&&(o.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):o.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),n.pickCursorPos=s.pointerCanvasPos,n.schedulePickEntity=i.doublePickFlyTo||u||f,n.schedulePickSurface=n.schedulePickEntity&&f,n.update(),n.pickResult){if(o.fire("doublePicked",n.pickResult,!0),n.pickedSurface&&o.fire("doublePickedSurface",n.pickResult,!0),i.doublePickFlyTo&&(h(n.pickResult),!i.firstPerson&&i.followPointer)){const e=n.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(o.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(h(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=d.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Ta{constructor(e,t,i,s,r){this._scene=e;const n=e.input,A=[];e.canvas.canvas;let o=!0;this._onSceneMouseMove=n.on("mousemove",(()=>{o=!0})),this._onSceneKeyDown=n.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(A[t]=!0))})),this._onSceneKeyUp=n.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(A[s]=!1,t.pivotController.getPivoting()&&t.pivotController.endPivot())})),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{A.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{A.splice(0)}),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const l=t.cameraControl,c=a.deltaTime/1e3;if(!i.planView){const e=l._isKeyDownForAction(l.ROTATE_Y_POS,A),s=l._isKeyDownForAction(l.ROTATE_Y_NEG,A),n=l._isKeyDownForAction(l.ROTATE_X_POS,A),o=l._isKeyDownForAction(l.ROTATE_X_NEG,A),a=c*i.keyboardRotationRate;(e||s||n||o)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=a:s&&(r.rotateDeltaY-=a),n?r.rotateDeltaX+=a:o&&(r.rotateDeltaX-=a),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!A[n.KEY_CTRL]&&!A[n.KEY_ALT]){const e=l._isKeyDownForAction(l.DOLLY_BACKWARDS,A),n=l._isKeyDownForAction(l.DOLLY_FORWARDS,A);if(e||n){const A=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),n?r.dollyDelta-=A:e&&(r.dollyDelta+=A),o&&(s.followPointerDirty=!0,o=!1)}}const h=l._isKeyDownForAction(l.PAN_FORWARDS,A),u=l._isKeyDownForAction(l.PAN_BACKWARDS,A),d=l._isKeyDownForAction(l.PAN_LEFT,A),f=l._isKeyDownForAction(l.PAN_RIGHT,A),p=l._isKeyDownForAction(l.PAN_UP,A),g=l._isKeyDownForAction(l.PAN_DOWN,A),m=(A[n.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(h||u||d||f||p||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:p&&(r.panDeltaY+=-m),f?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:h&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),this._scene.input.off(this._onSceneKeyUp)}}const Pa=d.vec3();class Sa{constructor(e,t,i,s,r){this._scene=e;const n=e.camera,A=t.pickController,o=t.pivotController,a=t.panController,l=t.cameraControl;let c=1,h=1,u=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--c<=0&&(c=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(A.pickCursorPos=s.pointerCanvasPos,A.schedulePickSurface=!0,A.update(),A.pickResult&&A.pickResult.worldPos?u=A.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(d.lenVec3(d.subVec3(u,e.camera.eye,Pa)));h=t/i.dollyProximityThreshold}h<i.dollyMinSpeed&&(h=i.dollyMinSpeed)}}else h=1,u=null;const f=r.dollyDelta*h;if(0===r.rotateDeltaY&&0===r.rotateDeltaX||(!i.firstPerson&&i.followPointer&&o.getPivoting()?(o.continuePivot(r.rotateDeltaY,r.rotateDeltaX),o.showPivot()):(0!==r.rotateDeltaX&&(i.firstPerson?n.pitch(-r.rotateDeltaX):n.orbitPitch(r.rotateDeltaX)),0!==r.rotateDeltaY&&(i.firstPerson?n.yaw(r.rotateDeltaY):n.orbitYaw(r.rotateDeltaY))),r.rotateDeltaX*=i.rotationInertia,r.rotateDeltaY*=i.rotationInertia,t=l._cursors.rotate),Math.abs(r.panDeltaX)<.001&&(r.panDeltaX=0),Math.abs(r.panDeltaY)<.001&&(r.panDeltaY=0),Math.abs(r.panDeltaZ)<.001&&(r.panDeltaZ=0),0!==r.panDeltaX||0!==r.panDeltaY||0!==r.panDeltaZ){const e=d.vec3();let s,A;if(e[0]=r.panDeltaX,e[1]=r.panDeltaY,e[2]=r.panDeltaZ,i.constrainVertical){n.xUp?(s=n.eye[0],A=n.look[0]):n.yUp?(s=n.eye[1],A=n.look[1]):n.zUp&&(s=n.eye[2],A=n.look[2]),n.pan(e);const t=n.eye,i=n.look;n.xUp?(t[0]=s,i[0]=A):n.yUp?(t[1]=s,i[1]=A):n.zUp&&(t[2]=s,i[2]=A),n.eye=t,n.look=i}else n.pan(e);t=l._cursors.pan}if(r.panDeltaX*=i.panInertia,r.panDeltaY*=i.panInertia,r.panDeltaZ*=i.panInertia,0!==f){if(t=f<0?l._cursors.dollyForward:l._cursors.dollyBackward,i.firstPerson){let e,t;if(i.constrainVertical&&(n.xUp?(e=n.eye[0],t=n.look[0]):n.yUp?(e=n.eye[1],t=n.look[1]):n.zUp&&(e=n.eye[2],t=n.look[2])),i.followPointer){a.dollyToCanvasPos(u,s.pointerCanvasPos,-f)&&(s.followPointerDirty=!0)}else n.pan([0,0,f]),n.ortho.scale=n.ortho.scale-f;if(i.constrainVertical){const i=n.eye,s=n.look;n.xUp?(i[0]=e,s[0]=t):n.yUp?(i[1]=e,s[1]=t):n.zUp&&(i[2]=e,s[2]=t),n.eye=i,n.look=s}}else if(i.planView)if(i.followPointer){a.dollyToCanvasPos(u,s.pointerCanvasPos,-f)&&(s.followPointerDirty=!0)}else n.ortho.scale=n.ortho.scale+f,n.zoom(f);else if(i.followPointer){a.dollyToCanvasPos(u,s.pointerCanvasPos,-f)&&(s.followPointerDirty=!0)}else n.ortho.scale=n.ortho.scale+f,n.zoom(f);r.dollyDelta*=i.dollyInertia}A.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class Da{constructor(e,t,i,s,r){this._scene=e;const n=this._scene.canvas.canvas;n.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.mouseover=!0}),n.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,n.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{ka(e,n,s.pointerCanvasPos)}),n.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(ka(e,n,s.pointerCanvasPos),s.mouseover=!0)}),n.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function ka(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const Qa=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Ra{constructor(e,t,i,s,r){this._scene=e;const n=t.pickController,A=t.pivotController,o=d.vec2(),a=d.vec2(),l=d.vec2(),c=d.vec2(),h=[],u=this._scene.canvas.canvas;let f=0,p=!1;this._onTick=e.on("tick",(()=>{p=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,a=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===a.length&&(Qa(r[0],o),i.followPointer&&(n.pickCursorPos=o,n.schedulePickSurface=!0,n.update(),i.planView||(n.picked&&n.pickedSurface&&n.pickResult&&n.pickResult.worldPos?(A.setPivotPos(n.pickResult.worldPos),!i.firstPerson&&A.startPivot()&&A.showPivot()):(i.smartPivot?A.setCanvasPivotPos(s.pointerCanvasPos):A.setPivotPos(e.camera.look),!i.firstPerson&&A.startPivot()&&A.showPivot()))));h.length<r.length;)h.push(d.vec2());for(let e=0,t=r.length;e<t;++e)Qa(r[e],h[e]);f=r.length}),u.addEventListener("touchend",this._canvasTouchEndHandler=()=>{A.getPivoting()&&(A.endPivot(),A.hidePivot())}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),p)return;p=!0;const A=e.canvas.boundary,o=A[2],u=A[3],g=t.touches;if(t.touches.length===f){if(1===f){Qa(g[0],a),d.subVec2(a,h[0],c);const t=c[0],n=c[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(n)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const A=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*A/u*i.touchPanRate,r.panDeltaY+=n*A/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(n/u)*i.touchPanRate}else r.rotateDeltaY-=t/o*(1*i.dragRotationRate),r.rotateDeltaX+=n/u*(1.5*i.dragRotationRate)}else if(2===f){const t=g[0],A=g[1];Qa(t,a),Qa(A,l);const o=d.geometricMeanVec2(h[0],h[1]),c=d.geometricMeanVec2(a,l),f=d.vec2();d.subVec2(o,c,f);const p=f[0],m=f[1],_=e.camera,b=d.distVec2([t.pageX,t.pageY],[A.pageX,A.pageY]),y=(d.distVec2(h[0],h[1])-b)*i.touchDollyRate;if(r.dollyDelta=y,Math.abs(y)<1)if("perspective"===_.projection){const t=n.pickResult?n.pickResult.worldPos:e.center,s=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=p*s/u*i.touchPanRate,r.panDeltaY-=m*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(p/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/u)*i.touchPanRate;s.pointerCanvasPos=c}for(let e=0;e<f;++e)Qa(g[e],h[e])}})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}const Oa=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Va{constructor(e,t,i,s,r){this._scene=e;const n=t.pickController,A=t.cameraControl;let o;const a=[],l=new Float32Array(2);let c=-1,h=-1;const u=this._scene.canvas.canvas,f=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,n=e.changedTouches;if(o=Date.now(),1===r.length&&1===n.length){c=o,Oa(r[0],l);const n=l[0],A=l[1],a=r[0].pageX,h=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{i.active&&i.pointerEnabled&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(a),Math.round(h)],canvasPos:[Math.round(n),Math.round(A)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else c=-1;for(;a.length<r.length;)a.push(new Float32Array(2));for(let e=0,t=r.length;e<t;++e)Oa(r[e],a[e]);a.length=r.length},{passive:!0}),u.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,o=e.changedTouches,u=A.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===o.length&&c>-1&&t-c<150&&(h>-1&&c-h<325?(Oa(o[0],n.pickCursorPos),n.schedulePickEntity=!0,n.schedulePickSurface=u,n.update(),n.pickResult?(n.pickResult.touchInput=!0,A.fire("doublePicked",n.pickResult),n.pickedSurface&&A.fire("doublePickedSurface",n.pickResult),i.doublePickFlyTo&&f(n.pickResult)):(A.fire("doublePickedNothing"),i.doublePickFlyTo&&f()),h=-1):d.distVec2(a[0],l)<4&&(Oa(o[0],n.pickCursorPos),n.schedulePickEntity=!0,n.schedulePickSurface=u,n.update(),n.pickResult?(n.pickResult.touchInput=!0,A.fire("picked",n.pickResult),n.pickedSurface&&A.fire("pickedSurface",n.pickResult)):A.fire("pickedNothing"),h=t),c=-1),a.length=r.length;for(let e=0,t=r.length;e<t;++e)a[e][0]=r[e].pageX,a[e][1]=r[e].pageY},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}class La extends D{constructor(e,t={}){super(e,t),this.PAN_LEFT=0,this.PAN_RIGHT=1,this.PAN_UP=2,this.PAN_DOWN=3,this.PAN_FORWARDS=4,this.PAN_BACKWARDS=5,this.ROTATE_X_POS=6,this.ROTATE_X_NEG=7,this.ROTATE_Y_POS=8,this.ROTATE_Y_NEG=9,this.DOLLY_FORWARDS=10,this.DOLLY_BACKWARDS=11,this.AXIS_VIEW_RIGHT=12,this.AXIS_VIEW_BACK=13,this.AXIS_VIEW_LEFT=14,this.AXIS_VIEW_FRONT=15,this.AXIS_VIEW_TOP=16,this.AXIS_VIEW_BOTTOM=17,this.MOUSE_PAN=18,this.MOUSE_ROTATE=19,this.MOUSE_DOLLY=20,this._keyMap={},this.scene.canvas.canvas.oncontextmenu=e=>{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new ya(this,this._configs),pivotController:new ba(i,this._configs),panController:new ha(i),cameraFlight:new se(this,{duration:.5})},this._handlers=[new Da(this.scene,this._controllers,this._configs,this._states,this._updates),new Ra(this.scene,this._controllers,this._configs,this._states,this._updates),new va(this.scene,this._controllers,this._configs,this._states,this._updates),new xa(this.scene,this._controllers,this._configs,this._states,this._updates),new Ia(this.scene,this._controllers,this._configs,this._states,this._updates),new Va(this.scene,this._controllers,this._configs,this._states,this._updates),new Ta(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cursors={dollyForward:"zoom-in",dollyBackward:"zoom-out",rotate:"grabbing",pan:"move"},this._cameraUpdater=new Sa(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",w.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_areAllKeysDown(e,t){if(!t||t.length<=0)return!0;if(!e)return!1;for(let i=0,s=t.length;i<s;i++){if(!e[t[i]])return!1}return!0}_isAnyOtherKeyDown(e,t){for(let i=0,s=e.length;i<s;i++)if(e[i])if(Array.isArray(t)){if(t.indexOf(i)<0)return!0}else if(i!==t)return!0;return!1}_isMouseAction(e){switch(e){case this.MOUSE_ROTATE:case this.MOUSE_DOLLY:case this.MOUSE_PAN:return!0;default:return!1}}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;if(0===i.length&&this._isMouseAction(e))return!0;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e<s;e++){const s=i[e];if(Array.isArray(s)){if(this._areAllKeysDown(t,s)&&!this._isAnyOtherKeyDown(t,s))return!0}else if(t[s]&&!this._isAnyOtherKeyDown(t,s))return!0}return!1}set pivotElement(e){this._controllers.pivotController.setPivotElement(e)}set active(e){e=!1!==e,this._configs.active=e,this._handlers[1]._active=e,this._handlers[5]._active=e}get active(){return this._configs.active}set snapToVertex(e){this._configs.snapToVertex=!!e}get snapToVertex(){return this._configs.snapToVertex}set snapToEdge(e){this._configs.snapToEdge=!!e}get snapToEdge(){return this._configs.snapToEdge}set snapRadius(e){e=e||30,this._configs.snapRadius=e}get snapRadius(){return this._configs.snapRadius}set keyboardEnabledOnlyIfMouseover(e){this._configs.keyboardEnabledOnlyIfMouseover=!!e}get keyboardEnabledOnlyIfMouseover(){return this._configs.keyboardEnabledOnlyIfMouseover}set navMode(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}get navMode(){return this._configs.navMode}set pointerEnabled(e){this._reset(),this._configs.pointerEnabled=!!e}setCursorStyle(e,t){Object.prototype.hasOwnProperty.call(this._cursors,e)?this._cursors={...this._cursors,[e]:t}:console.warn(`Action '${e}' is not valid for cursor styles.`)}getCursorStyle(e){return this._cursors[e]||null}_reset(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.reset&&t.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}get pointerEnabled(){return this._configs.pointerEnabled}set followPointer(e){this._configs.followPointer=!1!==e}get followPointer(){return this._configs.followPointer}set pivotPos(e){this._controllers.pivotController.setPivotPos(e)}get pivotPos(){return this._controllers.pivotController.getPivotPos()}set dollyToPointer(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}get dollyToPointer(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer}set panToPointer(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}get panToPointer(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1}set planView(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}get planView(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView}set firstPerson(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}get firstPerson(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson}set constrainVertical(e){this._configs.constrainVertical=!!e}get constrainVertical(){return this._configs.constrainVertical}set doublePickFlyTo(e){this._configs.doublePickFlyTo=!1!==e}get doublePickFlyTo(){return this._configs.doublePickFlyTo}set panRightClick(e){this._configs.panRightClick=!1!==e;const t=this._keyMap[this.MOUSE_PAN];if(t&&t.length>0){const e=this.scene.input;for(let i=0,s=t.length;i<s;i++)this._configs.panRightClick&&t[i]===e.MOUSE_MIDDLE_BUTTON?this._keyMap[this.MOUSE_PAN][i]=e.MOUSE_RIGHT_BUTTON:this._configs.panRightClick||t[i]!==e.MOUSE_RIGHT_BUTTON||(this._keyMap[this.MOUSE_PAN][i]=e.MOUSE_MIDDLE_BUTTON)}}get panRightClick(){return this._configs.panRightClick}set rotationInertia(e){this._configs.rotationInertia=null!=e?e:0}get rotationInertia(){return this._configs.rotationInertia}set keyboardPanRate(e){this._configs.keyboardPanRate=null!=e?e:5}set touchPanRate(e){this._configs.touchPanRate=null!=e?e:1}get touchPanRate(){return this._configs.touchPanRate}get keyboardPanRate(){return this._configs.keyboardPanRate}set keyboardRotationRate(e){this._configs.keyboardRotationRate=null!=e?e:90}get keyboardRotationRate(){return this._configs.keyboardRotationRate}set dragRotationRate(e){this._configs.dragRotationRate=null!=e?e:360}get dragRotationRate(){return this._configs.dragRotationRate}set keyboardDollyRate(e){this._configs.keyboardDollyRate=null!=e?e:15}get keyboardDollyRate(){return this._configs.keyboardDollyRate}set touchDollyRate(e){this._configs.touchDollyRate=null!=e?e:.2}get touchDollyRate(){return this._configs.touchDollyRate}set mouseWheelDollyRate(e){this._configs.mouseWheelDollyRate=null!=e?e:100}get mouseWheelDollyRate(){return this._configs.mouseWheelDollyRate}set dollyInertia(e){this._configs.dollyInertia=null!=e?e:0}get dollyInertia(){return this._configs.dollyInertia}set dollyProximityThreshold(e){this._configs.dollyProximityThreshold=null!=e?e:35}get dollyProximityThreshold(){return this._configs.dollyProximityThreshold}set dollyMinSpeed(e){this._configs.dollyMinSpeed=null!=e?e:.04}get dollyMinSpeed(){return this._configs.dollyMinSpeed}set panInertia(e){this._configs.panInertia=null!=e?e:.5}get panInertia(){return this._configs.panInertia}set keyboardLayout(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}get keyboardLayout(){return this._configs.keyboardLayout}enablePivotSphere(e={}){this._controllers.pivotController.enablePivotSphere(e)}disablePivotSphere(){this._controllers.pivotController.disablePivotSphere()}set smartPivot(e){this._configs.smartPivot=!1!==e}get smartPivot(){return this._configs.smartPivot}set doubleClickTimeFrame(e){this._configs.doubleClickTimeFrame=null!=e?e:250}get doubleClickTimeFrame(){return this._configs.doubleClickTimeFrame}set zoomOnMouseWheel(e){this._configs.zoomOnMouseWheel=!!e}get zoomOnMouseWheel(){return this._configs.zoomOnMouseWheel}destroy(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),super.destroy()}_destroyHandlers(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.destroy&&t.destroy()}}_destroyControllers(){for(let e=0,t=this._controllers.length;e<t;e++){const t=this._controllers[e];t.destroy&&t.destroy()}}}class Ha{constructor(e,t,i,s,r){this.name=e,this.type=i,this.value=t,this.valueType=s,this.description=r}}class Na{constructor(e){if(this.id=e.id,this.originalSystemId=e.originalSystemId,this.metaModels=[],this.name=e.name,this.type=e.type,this.properties=[],e.properties){const t=e.properties;for(let e=0,i=t.length;e<i;e++){const i=t[e];Number.isInteger(i)?this.properties.push(i):this.properties.push(new Ha(i.name,i.value,i.type,i.valueType,i.description))}}}}class Ga{constructor(e){this.metaModels=[],this.id=e.id,this.parentId=e.parentId,this.parent=null,this.originalSystemId=e.originalSystemId,this.name=e.name,this.type=e.type,this.propertySetIds=e.propertySetIds,this.propertySets=[],this.attributes=e.attributes||{},void 0!==e.external&&null!==e.external&&(this.external=e.external)}get metaModel(){return 1==this.metaModels.length?this.metaModels[0]:null}getObjectIDsInSubtree(){const e=[];return function t(i){if(!i)return;e.push(i.id);const s=i.children;if(s)for(var r=0,n=s.length;r<n;r++)t(s[r])}(this),e}withMetaObjectsInSubtree(e){!function t(i){if(!i)return;e(i);const s=i.children;if(s)for(var r=0,n=s.length;r<n;r++)t(s[r])}(this)}getObjectIDsInSubtreeByType(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=e[i];const r=[];return function e(i){if(!i)return;t[i.type]&&r.push(i.id);const s=i.children;if(s)for(var n=0,A=s.length;n<A;n++)e(s[n])}(this),r}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class ja{constructor(e){this.id=e.id,this.projectId=e.projectId,this.revisionId=e.revisionId,this.author=e.author,this.createdAt=e.createdAt,this.creatingApplication=e.creatingApplication,this.schema=e.schema,this.metaScene=e.metaScene,this.propertySets=[],this.rootMetaObjects=[],this.metaObjects={},this.graph=e.graph||{},this.metaScene.metaModels[this.id]=this,this._propertyLookup=[],this.finalized=!1}get rootMetaObject(){return 1===this.rootMetaObjects.length?this.rootMetaObjects[0]:null}loadData(e,t={}){if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);const i=this.metaScene,s=e.properties;if(s)for(let e=0,t=s.length;e<t;e++)this._propertyLookup.push(s[e]);if(e.propertySets)for(let t=0,s=e.propertySets.length;t<s;t++){const s=e.propertySets[t];s.properties||(s.properties=[]);let r=i.propertySets[s.id];r||(r=new Na({id:s.id,originalSystemId:s.originalSystemId||s.id,type:s.type,name:s.name,properties:s.properties}),i.propertySets[r.id]=r),r.metaModels.push(this),this.propertySets.push(r)}if(e.metaObjects)for(let t=0,s=e.metaObjects.length;t<s;t++){const s=e.metaObjects[t],r=s.id;let n=i.metaObjects[r];if(!n){const e=s.type,t=s.originalSystemId,i=s.propertySets||s.propertySetIds;n=new Ga({id:r,originalSystemId:t,parentId:s.parent,type:e,name:s.name,attributes:s.attributes,propertySetIds:i,external:s.external}),this.metaScene.metaObjects[r]=n,n.metaModels=[]}this.metaObjects[r]=n,s.parent||(this.rootMetaObjects.push(n),i.rootMetaObjects[r]=n),n.metaModels.push(this)}}_decompressProperties(e,t){const i=[];for(let s=0,r=t.length;s<r;s++){const r=t[s];if(Number.isInteger(r)){const n=e[r];n?t[s]=n:i.push(r)}}i.length>0&&console.error(`[MetaModel._decompressProperties] Properties not found: ${i}`)}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(let t=0,s=i.propertySetIds.length;t<s;t++){const s=i.propertySetIds[t],r=e.propertySets[s];i.propertySets.push(r)}}for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.parentId){const t=e.metaObjects[i.parentId];t&&(i.parent=t,(t.children||(t.children=[])).push(i))}}for(let t in e.metaObjects){e.metaObjects[t].metaModels=[]}for(let t in e.metaModels){const i=e.metaModels[t];for(let e in i.metaObjects){i.metaObjects[e].metaModels.push(i)}}e.metaObjectsByType={};for(let t in e.metaObjects){const i=e.metaObjects[t],s=i.type;(e.metaObjectsByType[s]||(e.metaObjectsByType[s]={}))[t]=i}if(this.propertySets)for(let e=0,t=this.propertySets.length;e<t;e++){const t=this.propertySets[e];this._decompressProperties(this._propertyLookup,t.properties)}this._propertyLookup=[],this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}getJSON(){const e={id:this.id,projectId:this.projectId,author:this.author,createdAt:this.createdAt,schema:this.schema,creatingApplication:this.creatingApplication,metaObjects:[],propertySets:[]},t=Object.values(this.metaObjects);for(let i=0,s=t.length;i<s;i++){const s=t[i],r={id:s.id,originalSystemId:s.originalSystemId,extId:s.extId,type:s.type,name:s.name};s.parent&&(r.parent=s.parent.id),s.attributes&&(r.attributes=s.attributes),s.propertySetIds&&(r.propertySetIds=s.propertySetIds),e.metaObjects.push(r)}for(let t=0,i=this.propertySets.length;t<i;t++){const i=this.propertySets[t],s={id:i.id,originalSystemId:i.originalSystemId,extId:i.extId,type:i.type,name:i.name,propertyies:[]};for(let e=0,t=i.properties.length;e<t;e++){const t=i.properties[e],r={id:t.id,description:t.description,type:t.type,name:t.name,value:t.value,valueType:t.valueType};s.properties.push(r)}e.propertySets.push(s)}return e}_globalizeIDs(e,t){const i=!!t.globalizeObjectIds;if(e.metaObjects)for(let t=0,s=e.metaObjects.length;t<s;t++){const s=e.metaObjects[t];if(s.originalSystemId=s.id,s.parent&&(s.originalParentSystemId=s.parent),i&&(s.id=d.globalizeObjectId(this.id,s.id),s.parent&&(s.parent=d.globalizeObjectId(this.id,s.parent))),i){const e=s.propertySetIds;if(e){const t=[];for(let i=0,s=e.length;i<s;i++)t.push(d.globalizeObjectId(this.id,e[i]));s.propertySetIds=t,s.originalSystemPropertySetIds=e}}else s.originalSystemPropertySetIds=s.propertySetIds}if(e.propertySets)for(let t=0,s=e.propertySets.length;t<s;t++){const s=e.propertySets[t];s.originalSystemId=s.id,i&&(s.id=d.globalizeObjectId(this.id,s.id))}}}class Wa{constructor(e,t){this.viewer=e,this.scene=t,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}off(e){}createMetaModel(e,t,i={}){const s=new ja({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return s.loadData(t),s.finalize(),s}destroyMetaModel(e){const t=this.metaModels[e];if(t){if(t.propertySets)for(let i=0,s=t.propertySets.length;i<s;i++){const s=t.propertySets[i];if(1===s.metaModels.length&&s.metaModels[0].id===e)delete this.propertySets[s.id];else{const t=[];for(let i=0,r=s.metaModels.length;i<r;i++)s.metaModels[i].id!==e&&t.push(s.metaModels[i]);s.metaModels=t}}if(t.metaObjects)for(let i in t.metaObjects){const s=t.metaObjects[i];1===s.metaModels.length&&s.metaModels[0].id===e?(delete this.metaObjects[i],s.parent||delete this.rootMetaObjects[i]):s.metaModels=s.metaModels.filter((t=>t.id!==e))}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.children&&(t.children=[]),t.propertySets&&(t.propertySets=[]),t.propertySetIds)for(let e=0,i=t.propertySetIds.length;e<i;e++){const i=t.propertySetIds[e],s=this.propertySets[i];t.propertySets.push(s)}}this.metaObjectsByType={};for(let e in this.metaObjects){const t=this.metaObjects[e],i=t.type;t.children&&(t.children=null),(this.metaObjectsByType[i]||(this.metaObjectsByType[i]={}))[e]=t}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.parentId){const e=this.metaObjects[t.parentId];e&&(t.parent=e,(e.children||(e.children=[])).push(t))}}delete this.metaModels[e];for(let e in this.metaObjects){this.metaObjects[e].metaModels=[]}for(let e in this.metaModels){const t=this.metaModels[e];for(let e in t.metaObjects){t.metaObjects[e].metaModels.push(t)}}this.fire("metaModelDestroyed",e)}}getObjectIDsByType(e){const t=this.metaObjectsByType[e];return t?Object.keys(t):[]}getObjectIDsInSubtree(e,t,i){const s=[],r=this.metaObjects[e],n=t&&t.length>0?za(t):null,A=i&&i.length>0?za(i):null,o=e=>{if(!e)return;var t=!0;(A&&A[e.type]||n&&!n[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,a=i.length;r<a;r++)o(i[r])};return o(r),s}withMetaObjectsInSubtree(e,t){const i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}function za(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=!0;return t}
|
|
23
|
+
**/let wn=null;function vn(e,t){const i=3*e,s=3*t;let r,n,A,o,a,l;const c=Math.min(r=wn[i],n=wn[i+1],A=wn[i+2]),h=Math.min(o=wn[s],a=wn[s+1],l=wn[s+2]);if(c!==h)return c-h;const u=Math.max(r,n,A),d=Math.max(o,a,l);return u!==d?u-d:0}let Bn=null;function Cn(e,t){let i=Bn[2*e]-Bn[2*t];return 0!==i?i:Bn[2*e+1]-Bn[2*t+1]}function Mn(e,t,i=!1){const s=e.positionsCompressed||[],r=function(e,t){const i=new Int32Array(e.length/3);for(let e=0,t=i.length;e<t;e++)i[e]=e;wn=new Int32Array(e.length);for(let i=0,s=e.length;i<s;i++)wn[i]=e[i]>>t;i.sort(vn);const s=new Int32Array(e.length);for(let t=0,r=i.length;t<r;t++)s[3*t+0]=e[3*i[t]+0],s[3*t+1]=e[3*i[t]+1],s[3*t+2]=e[3*i[t]+2];return s}(e.indices||[],t),n=function(e){if(0===(e||[]).length)return[];let t=new Int32Array(e.length/2);for(let e=0,i=t.length;e<i;e++)t[e]=e;for(let t=0,i=e.length;t<i;t+=2)if(e[t]>e[t+1]){let i=e[t];e[t]=e[t+1],e[t+1]=i}Bn=new Int32Array(e),t.sort(Cn);const i=new Int32Array(e.length);for(let s=0,r=t.length;s<r;s++)i[2*s+0]=e[2*t[s]+0],i[2*s+1]=e[2*t[s]+1];return i}(e.edgeIndices||[]);function A(e,t){if(e>t){let i=e;e=t,t=i}function i(i,s){return i!==e?e-i:s!==t?t-s:0}let s=0,r=(n.length>>1)-1;for(;s<=r;){const e=r+s>>1,t=i(n[2*e],n[2*e+1]);if(t>0)s=e+1;else{if(!(t<0))return e;r=e-1}}return-s-1}const o=new Int32Array(n.length/2);o.fill(0);const a=s.length/3;if(a>8*(1<<t))return[e];const l=new Int32Array(a);l.fill(-1);const c=[];function h(){l.fill(-1);const e={positionsCompressed:[],indices:[],edgeIndices:[],maxNumPositions:(1<<t)-t,numPositions:0,bucketNumber:c.length};return c.push(e),e}let u=h();for(let t=0,i=r.length;t<i;t+=3){let i=0;const a=r[t],c=r[t+1],d=r[t+2];if(-1===l[a]&&i++,-1===l[c]&&i++,-1===l[d]&&i++,i+u.numPositions>u.maxNumPositions&&(u=h()),u.bucketNumber>8)return[e];let f;-1===l[a]&&(l[a]=u.numPositions++,u.positionsCompressed.push(s[3*a]),u.positionsCompressed.push(s[3*a+1]),u.positionsCompressed.push(s[3*a+2])),-1===l[c]&&(l[c]=u.numPositions++,u.positionsCompressed.push(s[3*c]),u.positionsCompressed.push(s[3*c+1]),u.positionsCompressed.push(s[3*c+2])),-1===l[d]&&(l[d]=u.numPositions++,u.positionsCompressed.push(s[3*d]),u.positionsCompressed.push(s[3*d+1]),u.positionsCompressed.push(s[3*d+2])),u.indices.push(l[a]),u.indices.push(l[c]),u.indices.push(l[d]),(f=A(a,c))>=0&&0===o[f]&&(o[f]=1,u.edgeIndices.push(l[n[2*f]]),u.edgeIndices.push(l[n[2*f+1]])),(f=A(a,d))>=0&&0===o[f]&&(o[f]=1,u.edgeIndices.push(l[n[2*f]]),u.edgeIndices.push(l[n[2*f+1]])),(f=A(c,d))>=0&&0===o[f]&&(o[f]=1,u.edgeIndices.push(l[n[2*f]]),u.edgeIndices.push(l[n[2*f+1]]))}const d=t/8*2,f=t/8,p=2*s.length+(r.length+n.length)*d;let g=0,m=-s.length/3;return c.forEach((e=>{g+=2*e.positionsCompressed.length+(e.indices.length+e.edgeIndices.length)*f,m+=e.positionsCompressed.length/3})),g>p?[e]:(i&&function(e,t){const i={},s={};let r=0;e.forEach((e=>{const t=e.indices,n=e.edgeIndices,A=e.positionsCompressed;for(let e=0,s=t.length;e<s;e+=3){const s=A[3*t[e]]+"_"+A[3*t[e]+1]+"_"+A[3*t[e]+2]+"/"+A[3*t[e+1]]+"_"+A[3*t[e+1]+1]+"_"+A[3*t[e+1]+2]+"/"+A[3*t[e+2]]+"_"+A[3*t[e+2]+1]+"_"+A[3*t[e+2]+2];i[s]=!0}r+=e.edgeIndices.length/2;for(let e=0,t=n.length;e<t;e+=2){const t=A[3*n[e]]+"_"+A[3*n[e]+1]+"_"+A[3*n[e]+2]+"/"+A[3*n[e+1]]+"_"+A[3*n[e+1]+1]+"_"+A[3*n[e+1]+2]+"/";s[t]=!0}}));{const e=t.indices;t.edgeIndices;const s=t.positionsCompressed;for(let t=0,r=e.length;t<r;t+=3){const r=s[3*e[t]]+"_"+s[3*e[t]+1]+"_"+s[3*e[t]+2]+"/"+s[3*e[t+1]]+"_"+s[3*e[t+1]+1]+"_"+s[3*e[t+1]+2]+"/"+s[3*e[t+2]]+"_"+s[3*e[t+2]+1]+"_"+s[3*e[t+2]+2];if(!(r in i))throw console.log("Not found "+r),"Ohhhh!"}}}(c,e),c)}const En=new Float32Array([0,0,0]),Fn=new Uint16Array([0,0,0]);d.OBB3();class Un{constructor(e,t,i,s,r,n){this._isObject=t,this.scene=e.scene,this.model=e,this.isSceneModelEntity=!0,this.meshes=s,this._numPrimitives=0,this._capMaterial=null;for(let e=0,t=this.meshes.length;e<t;e++){const t=this.meshes[e];t.parent=this,t.entity=this,this._numPrimitives+=t.numPrimitives}this.id=i,this.originalSystemId=d.unglobalizeObjectId(e.id,i),this._flags=r,this._aabb=d.AABB3(),this._aabbDirty=!0,this._offset=d.vec3(),this._colorizeUpdated=!1,this._opacityUpdated=!1,this._lodCullable=!!n,this._culled=!1,this._culledVFC=!1,this._culledLOD=!1,this._isObject&&e.scene._registerObject(this)}_transformDirty(){this._aabbDirty=!0,this.model._transformDirty()}_sceneModelDirty(){this._aabbDirty=!0;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._sceneModelDirty()}get aabb(){if(this._aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this.meshes.length;e<t;e++)d.expandAABB3(this._aabb,this.meshes[e].aabb);this._aabbDirty=!1}return this._aabb}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get numPrimitives(){return this._numPrimitives}get numTriangles(){return this._numPrimitives}get visible(){return this._getFlag(ks)}set visible(e){if(!!(this._flags&ks)!==e){this._flags=e?this._flags|ks:this._flags&~ks;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}get highlighted(){return this._getFlag(Hs)}set highlighted(e){if(!!(this._flags&Hs)!==e){this._flags=e?this._flags|Hs:this._flags&~Hs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}get xrayed(){return this._getFlag(Ls)}set xrayed(e){if(!!(this._flags&Ls)!==e){this._flags=e?this._flags|Ls:this._flags&~Ls;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}get selected(){return this._getFlag(Ns)}set selected(e){if(!!(this._flags&Ns)!==e){this._flags=e?this._flags|Ns:this._flags&~Ns;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}get edges(){return this._getFlag(Gs)}set edges(e){if(!!(this._flags&Gs)!==e){this._flags=e?this._flags|Gs:this._flags&~Gs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get culledVFC(){return!!this._culledVFC}set culledVFC(e){this._culledVFC=e,this._setCulled()}get culledLOD(){return!!this._culledLOD}set culledLOD(e){this._culledLOD=e,this._setCulled()}get culled(){return!!this._culled}set culled(e){this._culled=e,this._setCulled()}_setCulled(){let e=!!this._culled||!(!this._culledLOD||!this._lodCullable)||!!this._culledVFC;if(!!(this._flags&Qs)!==e){this._flags=e?this._flags|Qs:this._flags&~Qs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(Os)}set clippable(e){if(!!(this._flags&Os)!==e){this._flags=e?this._flags|Os:this._flags&~Os;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get collidable(){return this._getFlag(Vs)}set collidable(e){if(!!(this._flags&Vs)!==e){this._flags=e?this._flags|Vs:this._flags&~Vs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}get pickable(){return this._getFlag(Rs)}set pickable(e){if(!!(this._flags&Rs)!==e){this._flags=e?this._flags|Rs:this._flags&~Rs;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setPickable(this._flags)}}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return En[0]=e[0]/255,En[1]=e[1]/255,En[2]=e[2]/255,En}set colorize(e){if(e){Fn[0]=Math.floor(255*e[0]),Fn[1]=Math.floor(255*e[1]),Fn[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(Fn)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t),this._colorizeUpdated=t}this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(s,this._flags);this._isObject&&(this.scene._objectOpacityUpdated(this,t),this._opacityUpdated=t),this.model.glRedraw()}get offset(){return this._offset}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._aabbDirty=!0,this.model._aabbDirty=!0,this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model.glRedraw()}get saoEnabled(){return this.model.saoEnabled}set capMaterial(e){this.scene.readableGeometryEnabled&&(this._capMaterial=e instanceof Vi?e:null,this.scene._capMaterialUpdated(this.id,this.model.id))}get capMaterial(){return this._capMaterial}getEachVertex(e){for(let t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachVertex(e)}getEachIndex(e){for(let t=0,i=this.meshes.length;t<i;t++)this.meshes[t].getEachIndex(e)}getGeometryData(){let e=0;const t=[],i=[];for(let s=0,r=this.meshes.length;s<r;s++){const r=this.meshes[s];if(r.layer.readGeometryData){const s=r.layer.readGeometryData(r.portionId);for(let t=0,r=s.indices.length;t<r;t++)i.push(s.indices[t]+e);for(let e=0,i=s.positions.length;e<i;e++)t.push(s.positions[e]);e+=s.positions.length/3}}return{indices:i,positions:t}}get volume(){let e=0;for(let t=0,i=this.meshes.length;t<i;t++){const i=this.meshes[t].volume;if(i<0)return-1;e+=i}return e}get surfaceArea(){let e=0;for(let t=0,i=this.meshes.length;t<i;t++){const i=this.meshes[t].surfaceArea;i>=0&&(e+=i)}return e>0?e:-1}_getFlag(e){return!!(this._flags&e)}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_finalize2(){for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize2()}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._deRegisterVisibleObject(this),this.xrayed&&e._deRegisterXRayedObject(this),this.selected&&e._deRegisterSelectedObject(this),this.highlighted&&e._deRegisterHighlightedObject(this),this._colorizeUpdated&&this.scene._deRegisterColorizedObject(this),this._opacityUpdated&&this.scene._deRegisterOpacityObject(this),!this._offset||0===this._offset[0]&&0===this._offset[1]&&0===this._offset[2]||this.scene._deRegisterOffsetObject(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const xn=d.vec4(4),In=d.vec4(),Tn=d.vec4(),Pn=d.vec3([1,0,0]),Sn=d.vec3([0,1,0]),Dn=d.vec3([0,0,1]);d.vec3(3),d.vec3(3);const kn=d.identityMat4();class Qn{constructor(e){this._model=e.model,this.id=e.id,this._parentTransform=e.parent,this._childTransforms=[],this._meshes=[],this._scale=new Float32Array([1,1,1]),this._quaternion=d.identityQuaternion(new Float32Array(4)),this._rotation=new Float32Array(3),this._position=new Float32Array(3),this._localMatrix=d.identityMat4(new Float32Array(16)),this._worldMatrix=d.identityMat4(new Float32Array(16)),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,e.matrix?this.matrix=e.matrix:(this.scale=e.scale,this.position=e.position,e.quaternion||(this.rotation=e.rotation)),e.parent&&e.parent._addChildTransform(this)}_addChildTransform(e){this._childTransforms.push(e),e._parentTransform=this,e._transformDirty(),e._setSubtreeAABBsDirty(this)}_addMesh(e){this._meshes.push(e),e.transform=this}get parentTransform(){return this._parentTransform}get meshes(){return this._meshes}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._model.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._model.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._model.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._model.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=d.identityMat4()),this._localMatrix.set(e||kn),d.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._transformDirty(),this._model.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=d.identityMat4()),d.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return xn[0]=e[0],xn[1]=e[1],xn[2]=e[2],xn[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(xn,In),d.mulQuaternions(this.quaternion,In,Tn),this.quaternion=Tn,this._setLocalMatrixDirty(),this._model.glRedraw(),this}rotateOnWorldAxis(e,t){return xn[0]=e[0],xn[1]=e[1],xn[2]=e[2],xn[3]=t*d.DEGTORAD,d.angleAxisToQuaternion(xn,In),d.mulQuaternions(In,this.quaternion,In),this}rotateX(e){return this.rotate(Pn,e)}rotateY(e){return this.rotate(Sn,e)}rotateZ(e){return this.rotate(Dn,e)}translate(e){return this._position[0]+=e[0],this._position[1]+=e[1],this._position[2]+=e[2],this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateX(e){return this._position[0]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateY(e){return this._position[1]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}translateZ(e){return this._position[2]+=e,this._setLocalMatrixDirty(),this._model.glRedraw(),this}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._transformDirty()}_transformDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._childTransforms.length;e<t;e++){const t=this._childTransforms[e];if(t._transformDirty(),t._meshes&&t._meshes.length>0){const e=t._meshes;for(let t=0,i=e.length;t<i;t++)e[t]._transformDirty()}}if(this._meshes&&this._meshes.length>0){const e=this._meshes;for(let t=0,i=e.length;t<i;t++)e[t]._transformDirty()}}_buildWorldMatrix(){const e=this.matrix;if(this._parentTransform)d.mulMat4(this._parentTransform.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._childTransforms)for(let t=0,i=e._childTransforms.length;t<i;t++)this._setSubtreeAABBsDirty(e._childTransforms[t])}}const Rn=d.vec3(),On=d.OBB3(),Vn=d.vec4(),Ln=d.vec3([1,1,1]),Hn=d.vec3([0,0,0]);d.vec3([0,0,0]);const Nn=d.identityQuaternion(),Gn=d.identityMat4(),jn=new Uint8Array([255,255,255]);class Wn extends D{constructor(e,t={}){super(e,t),this.renderOrder=t.renderOrder||0,this._dtxEnabled=this.scene.dtxEnabled&&!1!==t.dtxEnabled,this._enableVertexWelding=!1,this._enableIndexBucketing=!1,this._textureTranscoder=t.textureTranscoder||gn(this.scene.viewer),this._maxGeometryBatchSize=t.maxGeometryBatchSize??5e6,this._aabb=d.collapseAABB3(),this._aabbDirty=!0,this._quantizationRanges={},this._vboLayers={},this._dtxLayers={},this._meshList=[],this.layerList=[],this._layersToFinalize=[],this._entityList=[],this._entitiesToFinalize=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._transforms={},this._meshes={},this._unusedMeshes={},this._entities={},this.renderFlags=new Bi,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._layersFinalized=!1,this._edgeThreshold=t.edgeThreshold||10,this._origin=d.vec3(t.origin||[0,0,0]),this._position=d.vec3(t.position||[0,0,0]),this._rotation=d.vec3(t.rotation||[0,0,0]),this._quaternion=d.vec4(t.quaternion||[0,0,0,1]),this._conjugateQuaternion=d.vec4(t.quaternion||[0,0,0,1]),t.rotation&&d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=d.vec3(t.scale||[1,1,1]),this._worldRotationMatrix=d.mat4(),this._worldRotationMatrixConjugate=d.mat4(),this._matrix=d.mat4(),this._matrixDirty=!0,this._rebuildMatrices(),this._worldNormalMatrix=d.mat4(),d.inverseMat4(this._matrix,this._worldNormalMatrix),d.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=d.mat4(),this._viewNormalMatrix=d.mat4(),this._viewMatrixDirty=!0,this._matrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!1!==t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0})),this._meshesWithDirtyMatrices=[],this._numMeshesWithDirtyMatrices=0,this._onTick=this.scene.on("tick",(()=>{for(;this._numMeshesWithDirtyMatrices>0;)this._meshesWithDirtyMatrices[--this._numMeshesWithDirtyMatrices]._updateMatrix()}));const i=(e,t)=>this._textures[e]=new nn({id:e,texture:new zi({gl:this.scene.canvas.gl,preloadColor:t})});this._textureSets.defaultTextureSet=new rn({id:"defaultTextureSet",colorTexture:i("defaultColorTexture",[1,1,1,1]),metallicRoughnessTexture:i("defaultMetalRoughTexture",[0,1,1,1]),normalsTexture:i("defaultNormalsTexture",[0,0,0,0]),emissiveTexture:i("defaultEmissiveTexture",[0,0,0,1]),occlusionTexture:i("defaultOcclusionTexture",[1,1,1,1])}),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces}_meshMatrixDirty(e){this._meshesWithDirtyMatrices[this._numMeshesWithDirtyMatrices++]=e}get isPerformanceModel(){return!0}get transforms(){return this._transforms}get textures(){return this._textures}get textureSets(){return this._textureSets}get meshes(){return this._meshes}get objects(){return this._entities}get origin(){return this._origin}set position(e){this._position.set(e||[0,0,0]),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),d.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){}get scale(){return this._scale}set matrix(e){this._matrix.set(e||Gn),d.decomposeMat4(this._matrix,this._position,this._quaternion,this._scale),d.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._matrixDirty=!1,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.glRedraw()}get matrix(){return this._rebuildMatrices(),this._matrix}get rotationMatrix(){return this._rebuildMatrices(),this._worldRotationMatrix}_rebuildMatrices(){this._matrixDirty&&(d.quaternionToRotationMat4(this._quaternion,this._worldRotationMatrix),d.conjugateQuaternion(this._quaternion,this._conjugateQuaternion),d.quaternionToRotationMat4(this._conjugateQuaternion,this._worldRotationMatrixConjugate),d.scaleMat4v(this._scale,this._worldRotationMatrix),d.scaleMat4v(this._scale,this._worldRotationMatrixConjugate),this._matrix.set(this._worldRotationMatrix),d.translateMat4v(this._position,this._matrix),this._matrixDirty=!1,this._viewMatrixDirty=!0)}get rotationMatrixConjugate(){return this._rebuildMatrices(),this._worldRotationMatrixConjugate}_setWorldMatrixDirty(){this._matrixDirty=!0,this._aabbDirty=!0}_transformDirty(){this._matrixDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0}_sceneModelDirty(){this.scene._aabbDirty=!0,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._matrixDirty=!0;for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._sceneModelDirty()}get worldMatrix(){return this.matrix}get worldNormalMatrix(){return this._worldNormalMatrix}_rebuildViewMatrices(){this._rebuildMatrices(),this._viewMatrixDirty&&(d.mulMat4(this.scene.camera.viewMatrix,this._matrix,this._viewMatrix),d.inverseMat4(this._viewMatrix,this._viewNormalMatrix),d.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1)}get viewMatrix(){return this._viewMatrix?(this._rebuildViewMatrices(),this._viewMatrix):this.scene.camera.viewMatrix}get viewNormalMatrix(){return this._viewNormalMatrix?(this._rebuildViewMatrices(),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}get backfaces(){return this._backfaces}set backfaces(e){e=!!e,this._backfaces=e,this.glRedraw()}get entityList(){return this._entityList}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return!1}get aabb(){if(this._aabbDirty){d.collapseAABB3(this._aabb);for(let e=0,t=this._entityList.length;e<t;e++)d.expandAABB3(this._aabb,this._entityList[e].aabb);this._aabbDirty=!1}return this._aabb}get numTriangles(){return this._numTriangles}get numLines(){return this._numLines}get numPoints(){return this._numPoints}get visible(){return this.numVisibleLayerPortions>0}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].visible=e;this.glRedraw()}get xrayed(){return this.numXRayedLayerPortions>0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].xrayed=e;this.glRedraw()}get highlighted(){return this.numHighlightedLayerPortions>0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].highlighted=e;this.glRedraw()}get selected(){return this.numSelectedLayerPortions>0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].selected=e;this.glRedraw()}get edges(){return this.numEdgesLayerPortions>0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].edges=e;this.glRedraw()}get culled(){return this._culled}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].culled=e;this.glRedraw()}get clippable(){return this._clippable}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].clippable=e;this.glRedraw()}get collidable(){return this._collidable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].collidable=e}get pickable(){return this.numPickableLayerPortions>0}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].pickable=e}get colorize(){return this._colorize}set colorize(e){this._colorize=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].colorize=e}get opacity(){return this._opacity}set opacity(e){this._opacity=e;for(let t=0,i=this._entityList.length;t<i;t++)this._entityList[t].opacity=e}get castsShadow(){return this._castsShadow}set castsShadow(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}get receivesShadow(){return this._receivesShadow}set receivesShadow(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}get saoEnabled(){return this._saoEnabled}get pbrEnabled(){return this._pbrEnabled}get colorTextureEnabled(){return this._colorTextureEnabled}get isDrawable(){return!0}get isStateSortable(){return!1}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}createQuantizationRange(e){void 0!==e.id&&null!==e.id?e.aabb?this.error("[createQuantizationRange] Config missing: aabb"):this._quantizationRanges[e.id]?this.error("[createQuantizationRange] QuantizationRange already created: "+e.id):this._quantizationRanges[e.id]={id:e.id,aabb:e.aabb,matrix:Sr(e.aabb,d.mat4())}:this.error("[createQuantizationRange] Config missing: id")}_createDefaultIndices(e){const t=[];for(let i=0;i<e;i++)t.push(i);return t}createGeometry(e){if(void 0!==e.id&&null!==e.id)if(this._geometries[e.id])this.error("[createGeometry] Geometry already created: "+e.id);else if(void 0!==e.primitive&&null!==e.primitive||(e.primitive="triangles"),"points"===e.primitive||"lines"===e.primitive||"triangles"===e.primitive||"solid"===e.primitive||"surface"===e.primitive){if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("[createGeometry] Param expected: `positions`, `positionsCompressed' or 'buckets"),null;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("[createGeometry] Param expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.positionsDecodeMatrix&&e.positionsDecodeBoundary)return this.error("[createGeometry] Only one of these params expected: `positionsDecodeMatrix` or 'positionsDecodeBoundary' (required for `positionsCompressed')"),null;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("[createGeometry] Param expected: `uvDecodeMatrix` (required for `uvCompressed')"),null;if(e.buckets||e.indices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.indices=this._createDefaultIndices((e.positions||e.positionsCompressed).length/3)),!e.buckets&&!e.indices&&"points"!==e.primitive)return this.error(`[createGeometry] Param expected: indices (required for '${e.primitive}' primitive type)`),null;if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Sr(e.positionsDecodeBoundary,d.mat4())),e.positions){const t=d.collapseAABB3();e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(t,e.positions),e.positionsCompressed=Pr(e.positions,t,e.positionsDecodeMatrix),e.aabb=t}else if(e.positionsCompressed){const t=d.collapseAABB3();e.positionsDecodeMatrix=new Float64Array(e.positionsDecodeMatrix),e.positionsCompressed=new Uint16Array(e.positionsCompressed),d.expandAABB3Points3(t,e.positionsCompressed),ge.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}else if(e.buckets){const t=d.collapseAABB3();this._dtxBuckets[e.id]=e.buckets;for(let i=0,s=e.buckets.length;i<s;i++){const s=e.buckets[i];s.positions?d.expandAABB3Points3(t,s.positions):s.positionsCompressed&&d.expandAABB3Points3(t,s.positionsCompressed)}e.positionsDecodeMatrix&&ge.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(e.colorsCompressed&&e.colorsCompressed.length>0)e.colorsCompressed=new Uint8Array(e.colorsCompressed);else if(e.colors&&e.colors.length>0){const t=e.colors,i=new Uint8Array(t.length);for(let e=0,s=t.length;e<s;e++)i[e]=255*t[e];e.colorsCompressed=i}if(e.buckets||e.edgeIndices||"triangles"!==e.primitive&&"solid"!==e.primitive&&"surface"!==e.primitive||(e.positions?e.edgeIndices=le(e.positions,e.indices,null,5):e.edgeIndices=le(e.positionsCompressed,e.indices,e.positionsDecodeMatrix,2)),e.uv){const t=ge.getUVBounds(e.uv),i=ge.compressUVs(e.uv,t.min,t.max);e.uvCompressed=i.quantized,e.uvDecodeMatrix=i.decodeMatrix}else e.uvCompressed&&(e.uvCompressed=new Uint16Array(e.uvCompressed),e.uvDecodeMatrix=new Float64Array(e.uvDecodeMatrix));e.normals&&(e.normals=null),this._geometries[e.id]=e,this._numTriangles+=e.indices?Math.round(e.indices.length/3):0,this.numGeometries++}else this.error(`[createGeometry] Unsupported value for 'primitive': '${e.primitive}' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'.`);else this.error("[createGeometry] Config missing: id")}createTexture(e){const t=e.id;if(null==t)return void this.error("[createTexture] Config missing: id");if(this._textures[t])return void this.error("[createTexture] Texture already created: "+t);if(!e.src&&!e.image&&!e.buffers)return this.error("[createTexture] Param expected: `src`, `image' or 'buffers'"),null;let i=e.minFilter||1008;1006!==i&&1007!==i&&1008!==i&&1005!==i&&1004!==i&&(this.error("[createTexture] Unsupported value for 'minFilter' - \n supported values are LinearFilter, LinearMipMapNearestFilter, NearestMipMapNearestFilter, \n NearestMipMapLinearFilter and LinearMipmapLinearFilter. Defaulting to LinearMipmapLinearFilter."),i=1008);let s=e.magFilter||1006;1006!==s&&1003!==s&&(this.error("[createTexture] Unsupported value for 'magFilter' - supported values are LinearFilter and NearestFilter. Defaulting to LinearFilter."),s=1006);let r=e.wrapS||1e3;1001!==r&&1002!==r&&1e3!==r&&(this.error("[createTexture] Unsupported value for 'wrapS' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),r=1e3);let n=e.wrapT||1e3;1001!==n&&1002!==n&&1e3!==n&&(this.error("[createTexture] Unsupported value for 'wrapT' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),n=1e3);let A=e.wrapR||1e3;1001!==A&&1002!==A&&1e3!==A&&(this.error("[createTexture] Unsupported value for 'wrapR' - supported values are ClampToEdgeWrapping, MirroredRepeatWrapping and RepeatWrapping. Defaulting to RepeatWrapping."),A=1e3);let o=e.encoding||3e3;3e3!==o&&3001!==o&&(this.error("[createTexture] Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),o=3e3);const a=new zi({gl:this.scene.canvas.gl,minFilter:i,magFilter:s,wrapS:r,wrapT:n,wrapR:A,encoding:o});if(e.preloadColor&&a.setPreloadColor(e.preloadColor),e.image){const t=e.image;if(t.crossOrigin="Anonymous",t.compressed){const e=t.data;a.setCompressedData({mipmaps:e,props:{format:e[0].format,minFilter:i,magFilter:s}})}else a.setImage(t,{minFilter:i,magFilter:s,wrapS:r,wrapT:n,wrapR:A,flipY:e.flipY,encoding:o})}else if(e.src){const t=e.src.split(".").pop();switch(t){case"jpeg":case"jpg":case"png":case"gif":const l=new Image;l.onload=()=>{a.setImage(l,{minFilter:i,magFilter:s,wrapS:r,wrapT:n,wrapR:A,flipY:e.flipY,encoding:o}),this.glRedraw()},l.src=e.src;break;default:this._textureTranscoder?w.loadArraybuffer(e.src,(e=>{e.byteLength?this._textureTranscoder.transcode([e],a).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'src': file data is zero length")}),(function(e){this.error(`[createTexture] Can't create texture from 'src': ${e}`)})):this.error(`[createTexture] Can't create texture from 'src' - SceneModel needs to be configured with a TextureTranscoder for this file type ('${t}')`)}}else e.buffers&&(this._textureTranscoder?this._textureTranscoder.transcode(e.buffers,a).then((()=>{this.glRedraw()})):this.error("[createTexture] Can't create texture from 'buffers' - SceneModel needs to be configured with a TextureTranscoder for this option"));this._textures[t]=new nn({id:t,texture:a})}createTextureSet(e){const t=e.id;if(null==t)return this.error("[createTextureSet] Config missing: id"),!1;if(this._textureSets[t])return this.error(`[createTextureSet] Texture set already created: ${t}`),!1;const i=(e,t)=>{const i=e??t;if(i in this._textures)return this._textures[i];throw e};try{const s=new rn({id:t,model:this,alphaCutoff:e.alphaCutoff,colorTexture:i(e.colorTextureId,"defaultColorTexture"),metallicRoughnessTexture:i(e.metallicRoughnessTextureId,"defaultMetalRoughTexture"),normalsTexture:i(e.normalsTextureId,"defaultNormalsTexture"),emissiveTexture:i(e.emissiveTextureId,"defaultEmissiveTexture"),occlusionTexture:i(e.occlusionTextureId,"defaultOcclusionTexture")});return this._textureSets[t]=s,s}catch(e){return this.error(`[createTextureSet] Texture not found: ${e} - ensure that you create it first with createTexture()`),!1}}createTransform(e){if(void 0===e.id||null===e.id)return void this.error("[createTransform] SceneModel.createTransform() config missing: id");if(this._transforms[e.id])return void this.error(`[createTransform] SceneModel already has a transform with this ID: ${e.id}`);let t;if(e.parentTransformId&&(t=this._transforms[e.parentTransformId],!t))return void this.error("[createTransform] SceneModel.createTransform() config missing: id");const i=new Qn({id:e.id,model:this,parent:t,matrix:e.matrix,position:e.position,scale:e.scale,rotation:e.rotation,quaternion:e.quaternion});return this._transforms[i.id]=i,i}createMesh(e){if(void 0===e.id||null===e.id)return this.error("[createMesh] SceneModel.createMesh() config missing: id"),!1;if(this._meshes[e.id])return this.error(`[createMesh] SceneModel already has a mesh with this ID: ${e.id}`),!1;const t=e.geometryId,i=void 0!==t;if(i){if(e.positions||e.positionsCompressed||e.indices||e.edgeIndices||e.normals||e.normalsCompressed||e.uv||e.uvCompressed||e.positionsDecodeMatrix)return this.error("Mesh geometry parameters not expected when instancing a geometry (not expected: positions, positionsCompressed, indices, edgeIndices, normals, normalsCompressed, uv, uvCompressed, positionsDecodeMatrix)"),!1;if(e.geometry=this._geometries[t],!e.geometry)return this.error(`[createMesh] Geometry not found: ${t} - ensure that you create it first with createGeometry()`),!1}else e.primitive??="triangles";const s=i?e.geometry.primitive:e.primitive,r="triangles"===s||"solid"===s||"surface"===s,n=e.textureSetId,A=this._dtxEnabled&&r&&!n;if(e.origin=e.origin?d.addVec3(this._origin,e.origin,d.vec3()):this._origin,i){e.positionsDecodeMatrix=e.geometry.positionsDecodeMatrix,e.aabb=d.AABB3(e.geometry.aabb);const t=e.transformId;if(t){if(e.transform=this._transforms[t],!e.transform)return this.error(`[createMesh] Transform not found: ${t} - ensure that you create it first with createTransform()`),!1}else if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Ln,i=e.position||Hn,s=e.rotation?d.eulerToQuaternion(e.rotation,"XYZ",Vn):e.quaternion||Nn;e.meshMatrix=d.composeMat4(i,s,t,d.mat4())}}else{if("points"!==s&&"lines"!==s&&"triangles"!==s&&"solid"!==s&&"surface"!==s)return this.error(`Unsupported value for 'primitive': '${s}' ('geometryId' is absent) - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'.`),!1;if(!e.positions&&!e.positionsCompressed&&!e.buckets)return this.error("Param expected: 'positions', 'positionsCompressed' or `buckets` ('geometryId' is absent)"),!1;if(e.positions&&(e.positionsDecodeMatrix||e.positionsDecodeBoundary))return this.error("Illegal params: 'positions' not expected with 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.positionsCompressed&&!e.positionsDecodeMatrix&&!e.positionsDecodeBoundary)return this.error("Param expected: 'positionsCompressed' should be accompanied by 'positionsDecodeMatrix'/'positionsDecodeBoundary' ('geometryId' is absent)"),!1;if(e.uvCompressed&&!e.uvDecodeMatrix)return this.error("Param expected: 'uvCompressed' should be accompanied by `uvDecodeMatrix` ('geometryId' is absent)"),!1;if(!e.buckets&&!e.indices)if(r)e.indices=this._createDefaultIndices((e.positions||e.positionsCompressed).length/3);else if("lines"===s)return this.error(`Param expected: indices (required for '${s}' primitive type)`),!1;if((e.matrix||e.position||e.rotation||e.scale)&&(e.positionsCompressed||e.positionsDecodeBoundary))return this.error("Unexpected params: 'matrix', 'rotation', 'scale', 'position' not allowed with 'positionsCompressed'"),!1;if(e.matrix)e.meshMatrix=e.matrix;else if(e.scale||e.rotation||e.position||e.quaternion){const t=e.scale||Ln,i=e.position||Hn,s=e.rotation?d.eulerToQuaternion(e.rotation,"XYZ",Vn):e.quaternion||Nn;e.meshMatrix=d.composeMat4(i,s,t,d.mat4())}if(e.positionsDecodeBoundary&&(e.positionsDecodeMatrix=Sr(e.positionsDecodeBoundary,d.mat4())),e.positions){const t=[];$e(e.positions,t,Rn)&&(e.positions=t,e.origin=d.addVec3(e.origin,Rn,d.vec3()));const i=d.collapseAABB3();A?(e.positionsDecodeMatrix=d.mat4(),d.expandAABB3Points3(i,e.positions),e.positionsCompressed=Pr(e.positions,i,e.positionsDecodeMatrix)):(e.meshMatrix&&(d.transformPositions3(e.meshMatrix,e.positions,e.positions),e.meshMatrix=null),d.expandAABB3Points3(i,e.positions)),e.aabb=i}else if(e.positionsCompressed){const t=d.collapseAABB3();d.expandAABB3Points3(t,e.positionsCompressed),ge.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}if(A&&e.buckets){const t=d.collapseAABB3();e.buckets.forEach((e=>{const i=e.positions||e.positionsCompressed;i&&d.expandAABB3Points3(t,i)})),e.positionsDecodeMatrix&&ge.decompressAABB(t,e.positionsDecodeMatrix),e.aabb=t}r&&!e.buckets&&(e.edgeIndices||=le(e.positions||e.positionsCompressed,e.indices,e.positions?null:e.positionsDecodeMatrix,2))}if(e.meshMatrix&&(d.AABB3ToOBB3(e.aabb,On),d.transformOBB3(e.meshMatrix,On,On),d.OBB3ToAABB3(On,e.aabb)),e.color=e.color?new Uint8Array(e.color.slice(0,3).map((e=>Math.floor(255*e)))):jn,e.opacity=Math.floor(255*(e.opacity??1)),A)e.type=2,i&&(e.buckets=this._dtxBuckets[t]),e.buckets||(e.buckets=function(e,t,i){let s,r,n,A;t||i?[s,r,n]=yn({positionsCompressed:e.positionsCompressed,indices:e.indices,edgeIndices:e.edgeIndices}):(s=e.positionsCompressed,r=e.indices,n=e.edgeIndices);if(i){A=Mn({positionsCompressed:s,indices:r,edgeIndices:n},s.length/3>65536?16:8)}else A=[{positionsCompressed:s,indices:r,edgeIndices:n}];return A}(i?e.geometry:e,this._enableVertexWelding,this._enableIndexBucketing),i&&(this._dtxBuckets[t]=e.buckets));else if(e.type=i?0:1,e.metallic=Math.floor(255*(e.metallic??0)),e.roughness=Math.floor(255*(e.roughness??1)),n&&(e.textureSet=this._textureSets[n],!i&&!e.textureSet))return this.error(`[createMesh] Texture set not found: ${n} - ensure that you create it first with createTextureSet()`),!1;e.numPrimitives=this._getNumPrimitives(e);const o=new Ds(this,e.id,e.color,e.opacity,e.transform,e.textureSet),a=this.scene._renderer.getPickID(o);return o.pickId=a,o.origin=d.vec3(e.origin),o.layer=2===e.type?this._getDTXLayer(e):this._getVBOLayer(0===e.type,e),o.aabb=e.aabb,e.pickColor=new Uint8Array([255&a,a>>8&255,a>>16&255,a>>24&255]),e.solid="solid"===e.primitive,e.meshMatrix=e.transform?e.transform.worldMatrix:e.meshMatrix,o.portionId=o.layer.createPortion(o,e),o.numPrimitives=e.numPrimitives,this._meshes[e.id]=o,this._unusedMeshes[e.id]=o,this._meshList.push(o),o}_getNumPrimitives(e){let t=0;switch(e.geometry?e.geometry.primitive:e.primitive){case"triangles":case"solid":case"surface":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/3);case"points":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].positionsCompressed.length;break;case 1:t+=e.positions?e.positions.length:e.positionsCompressed.length;break;case 0:const i=e.geometry;t+=i.positions?i.positions.length:i.positionsCompressed.length}return Math.round(t);case"lines":case"line-strip":switch(e.type){case 2:for(let i=0,s=e.buckets.length;i<s;i++)t+=e.buckets[i].indices.length;break;case 1:t+=e.indices.length;break;case 0:t+=e.geometry.indices.length}return Math.round(t/2)}return 0}_getDTXLayer(e){const t=e.origin,i=e.geometry?e.geometry.primitive:e.primitive,s=`.${i}.${Math.round(t[0])}.${Math.round(t[1])}.${Math.round(t[2])}`;let r=this._dtxLayers[s];if(r){if(r.canCreatePortion(e))return r;delete this._dtxLayers[s],r=null}switch(i){case"triangles":case"solid":case"surface":r=new Fr(this,i,t);break;default:return}return this._dtxLayers[s]=r,this.layerList.push(r),this._layersToFinalize.push(r),r}_getVBOLayer(e,t){const i=e&&t.geometry,s=e?i.primitive:t.primitive,r=t.origin,n=!e&&(t.positionsDecodeMatrix||t.positionsDecodeBoundary),A=n?this._createHashStringFromMatrix(n):"-",o=t.textureSetId||"-",a=e?t.geometryId:"-",l=(e?"instancing":"batching")+`.${Math.round(r[0])}.${Math.round(r[1])}.${Math.round(r[2])}.${s}.${A}.${o}.${a}`;if(!e&&l in this._vboLayers){const e=this._vboLayers[l],i=t.positionsCompressed?t.positionsCompressed.length:t.positions.length;e.canCreatePortion(i,"points"===s?0:t.indices.length)||(e.finalize(),delete this._vboLayers[l])}if(!(l in this._vboLayers)){const n=new en(this,s,r,{textureSet:t.textureSet,...e?{geometry:i}:{maxGeometryBatchSize:this._maxGeometryBatchSize,positionsDecodeMatrix:t.positionsDecodeMatrix,uvDecodeMatrix:t.uvDecodeMatrix}});this.layerList.push(n),this._layersToFinalize.push(n),this._vboLayers[l]=n}return this._vboLayers[l]}_createHashStringFromMatrix(e){const t=e.join(";");let i=0;for(let e=0;e<t.length;e++){i=(i<<5)-i+t.charCodeAt(e),i|=0}return(i>>>0).toString(16)}createEntity(e){if(void 0===e.id?e.id=d.createUUID():this.scene.components[e.id]&&(this.error(`Scene already has a Component with this ID: ${e.id} - will assign random ID`),e.id=d.createUUID()),void 0===e.meshIds)return this.error("Config missing: meshIds"),null;const t=e=>!1!==e;let i=0;i|=this._visible&&t(e.visible)&&ks,i|=this._pickable&&t(e.pickable)&&Rs,i|=this._culled&&t(e.culled)&&Qs,i|=this._clippable&&t(e.clippable)&&Os,i|=this._collidable&&t(e.collidable)&&Vs,i|=this._xrayed&&t(e.xrayed)&&Ls,i|=this._highlighted&&t(e.highlighted)&&Hs,i|=this._selected&&t(e.selected)&&Ns,i|=this._edges&&t(e.edges)&&Gs,e.flags=i;let s=[];for(let t=0,i=e.meshIds.length;t<i;t++){const i=e.meshIds[t];let r=this._meshes[i];r?r.parent?this.error(`Mesh with ID "${i}" already belongs to object with ID "${r.parent.id}" - ignoring this mesh`):(s.push(r),delete this._unusedMeshes[i]):this.error(`Mesh with this ID not found: "${i}" - ignoring this mesh`)}const r=new Un(this,e.isObject,e.id,s,e.flags,!0);return this._entityList.push(r),this._entities[e.id]=r,this._entitiesToFinalize.push(r),this.numEntities++,r}preFinalize(){if(this.destroyed)return!1;if(0===this._layersToFinalize.length)return!1;this._createDummyEntityForUnusedMeshes();for(let e=0,t=this._layersToFinalize.length;e<t;e++){this._layersToFinalize[e].finalize()}this._vboLayers={},this._dtxLayers={},this._layersToFinalize=[];for(let e=0,t=this._entitiesToFinalize.length;e<t;e++){this._entitiesToFinalize[e]._finalize()}for(let e=0,t=this._entitiesToFinalize.length;e<t;e++){this._entitiesToFinalize[e]._finalize2()}this._entitiesToFinalize=[],this.scene._aabbDirty=!0,this._viewMatrixDirty=!0,this._matrixDirty=!0,this._aabbDirty=!0,this._setWorldMatrixDirty(),this._sceneModelDirty(),this.position=this._position,this.layerList.sort(((e,t)=>e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0));for(let e=0,t=this.layerList.length;e<t;e++){this.layerList[e].layerIndex=e}this.glRedraw(),this._layersFinalized=!0}finalize(){this.destroyed||(this.preFinalize(),this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={})}stateSortCompare(e,t){}rebuildRenderFlags(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this.layerList.length,e.numVisibleLayers=0;for(let t=0,i=this.layerList.length;t<i;t++){const i=this.layerList[t];this._getActiveSectionPlanesForLayer(i)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}_createDummyEntityForUnusedMeshes(){const e=Object.keys(this._unusedMeshes);if(e.length>0){const t=`${this.id}-${d.createUUID()}`;this.warn(`Creating dummy SceneModelEntity "${t}" for unused SceneMeshes: [${e.join(",")}]`),this.createEntity({id:t,meshIds:e,isObject:!0})}this._unusedMeshes={}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e<s;e++){i[e].active?(t.sectionPlanesActivePerLayer[r+e]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[r+e]=!1}return!0}_updateRenderFlags(){if(0===this.numVisibleLayerPortions)return;if(this.numCulledLayerPortions===this.numPortions)return;const e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0){this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0))}if(this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}_withEachVisibleLayer(e,t){if(e&&0===this.numVisibleLayerPortions)return;const i=this.renderFlags;for(let e=0,s=i.visibleLayers.length;e<s;e++){const s=i.visibleLayers[e];t(this.layerList[s])}}drawColorOpaque(e){this._withEachVisibleLayer(!1,(t=>t.drawColorOpaque(this.renderFlags,e)))}drawColorTransparent(e){this._withEachVisibleLayer(!1,(t=>t.drawColorTransparent(this.renderFlags,e)))}drawDepth(e){this._withEachVisibleLayer(!1,(t=>t.drawDepth(this.renderFlags,e)))}drawSilhouetteXRayed(e){this._withEachVisibleLayer(!1,(t=>t.drawSilhouetteXRayed(this.renderFlags,e)))}drawSilhouetteHighlighted(e){this._withEachVisibleLayer(!1,(t=>t.drawSilhouetteHighlighted(this.renderFlags,e)))}drawSilhouetteSelected(e){this._withEachVisibleLayer(!1,(t=>t.drawSilhouetteSelected(this.renderFlags,e)))}drawEdgesColorOpaque(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesColorOpaque(this.renderFlags,e)))}drawEdgesColorTransparent(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesColorTransparent(this.renderFlags,e)))}drawEdgesXRayed(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesXRayed(this.renderFlags,e)))}drawEdgesHighlighted(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesHighlighted(this.renderFlags,e)))}drawEdgesSelected(e){this._withEachVisibleLayer(!1,(t=>t.drawEdgesSelected(this.renderFlags,e)))}drawOcclusion(e){this._withEachVisibleLayer(!0,(t=>t.drawOcclusion(this.renderFlags,e)))}drawShadow(e){this._withEachVisibleLayer(!0,(t=>t.drawShadow(this.renderFlags,e)))}drawPickMesh(e){this._withEachVisibleLayer(!0,(t=>t.drawPickMesh(this.renderFlags,e)))}drawPickDepths(e){this._withEachVisibleLayer(!0,(t=>t.drawPickDepths(this.renderFlags,e)))}drawPickNormals(e){this._withEachVisibleLayer(!0,(t=>t.drawPickNormals(this.renderFlags,e)))}_drawSnap(e,t){this._withEachVisibleLayer(!0,(i=>i.drawSnap(this.renderFlags,e,t)))}drawSnapInit(e){this._drawSnap(e,!0)}drawSnap(e){this._drawSnap(e,!1)}destroy(){Object.values(this._vboLayers).forEach((e=>e.destroy())),this._vboLayers={},this.scene.camera.off(this._onCameraViewMatrix),this.scene.off(this._onTick);for(let e=0,t=this.layerList.length;e<t;e++)this.layerList[e].destroy();this.layerList=[];for(let e=0,t=this._entityList.length;e<t;e++)this._entityList[e]._destroy();this._layersToFinalize=[],this._geometries={},this._dtxBuckets={},this._textures={},this._textureSets={},this._meshes={},this._entities={},this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),super.destroy()}}class zn extends D{constructor(e,t={}){if(super(e,t),this._positions=t.positions||[],t.indices)this._indices=t.indices;else{this._indices=[];for(let e=0,t=this._positions.length/3-1;e<t;e+=2)this._indices.push(e),this._indices.push(e+1)}this._color=t.color||[1,1,1],this._opacity=t.opacity||1,this._sceneModel=new Wn(this,{isModel:!1}),this._sceneModel.createMesh({id:"linesMesh",primitive:"lines",positions:this._positions,indices:this._indices,color:this._color,opacity:this._opacity}),this._sceneModel.createEntity({meshIds:["linesMesh"],visible:t.visible,clippable:t.clippable,collidable:t.collidable}),this._sceneModel.finalize(),this.scene._lineSetCreated(this)}set visible(e){this._sceneModel.visible=e}get visible(){return this._sceneModel.visible}get positions(){return this._positions}get indices(){return this._indices}destroy(){super.destroy(),this.scene._lineSetDestroyed(this)}}class Xn extends D{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Kn extends Xn{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:d.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Zn{constructor(e,t,i){this.gl=e,this.allocated=!1,this.buffer=null,this.bound=!1,this._colorFormats=t,this._hasDepthTexture=i}setSize(e){this.size=e}bind(){const e=this.size[0],t=this.size[1];if(!this.buffer||this.buffer.width===e&&this.buffer.height===t||(this.buffer.cleanup(),this.buffer=null),this.buffer||(this._allocateBuffer(e,t),this.bound=!1),!this.bound){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}}_allocateBuffer(e,t){const i=this._colorFormats||[],s=this.gl,r=()=>{const e=s.createTexture();return s.bindTexture(s.TEXTURE_2D,e),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),e},n=(i.length>0?i:[null]).map((i=>{const n=r();return i?s.texStorage2D(s.TEXTURE_2D,1,i,e,t):s.texImage2D(s.TEXTURE_2D,0,s.RGBA,e,t,0,s.RGBA,s.UNSIGNED_BYTE,null),n})),A=s.createRenderbuffer();s.bindRenderbuffer(s.RENDERBUFFER,A),s.renderbufferStorage(s.RENDERBUFFER,s.DEPTH_COMPONENT32F,e,t);const o=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,o);for(let e=0;e<n.length;e++)s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0+e,s.TEXTURE_2D,n[e],0);i.length>0&&s.drawBuffers(n.map(((e,t)=>s.COLOR_ATTACHMENT0+t)));const a=this._hasDepthTexture&&r();if(a?(s.texImage2D(s.TEXTURE_2D,0,s.DEPTH_COMPONENT32F,e,t,0,s.DEPTH_COMPONENT,s.FLOAT,null),s.framebufferTexture2D(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.TEXTURE_2D,a,0)):s.framebufferRenderbuffer(s.FRAMEBUFFER,s.DEPTH_ATTACHMENT,s.RENDERBUFFER,A),s.bindTexture(s.TEXTURE_2D,null),s.bindRenderbuffer(s.RENDERBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.bindFramebuffer(s.FRAMEBUFFER,o),!s.isFramebuffer(o))throw"Invalid framebuffer";s.bindFramebuffer(s.FRAMEBUFFER,null);const l=s.checkFramebufferStatus(s.FRAMEBUFFER);switch(l){case s.FRAMEBUFFER_COMPLETE:break;case s.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case s.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case s.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+l}this.buffer={cleanup:()=>{n.forEach((e=>s.deleteTexture(e))),a&&s.deleteTexture(a),s.deleteFramebuffer(o),s.deleteRenderbuffer(A)},framebuf:o,width:e,height:t},this.colorTextures=n.map((e=>({bind:function(t){return s.activeTexture(s["TEXTURE"+t]),s.bindTexture(s.TEXTURE_2D,e),!0}}))),this.depthTexture=a&&{bind:function(e){return s.activeTexture(s["TEXTURE"+e]),s.bindTexture(s.TEXTURE_2D,a),!0}}}read(e,t,i=null,s=null,r=Uint8Array,n=4,A=0){const o=new r(n),a=this.gl;return a.readBuffer(a.COLOR_ATTACHMENT0+A),a.readPixels(e,this.buffer.height-t-1,1,1,i||a.RGBA,s||a.UNSIGNED_BYTE,o,0),o}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}destroy(){this.allocated&&(this.buffer.cleanup(),this.allocated=!1,this.buffer=null,this.bound=!1),this.colorTextures=null,this.depthTexture=null}}class Jn extends Xn{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new oe({type:"dir",dir:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=d.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];d.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=d.identityMat4()),d.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new Zn(this.scene.canvas.gl),this._shadowRenderBuf.setSize([1024,1024])),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class Yn extends Xn{get type(){return"PointLight"}constructor(e,t={}){super(e,t);const i=this;this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const s=this.scene.camera,r=this.scene.canvas;this._onCameraViewMatrix=s.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=s.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=r.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new oe({type:"point",pos:d.vec3([1,1,1]),color:d.vec3([.7,.7,.8]),intensity:1,attenuation:[0,0,0],space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(i._shadowViewMatrixDirty){i._shadowViewMatrix||(i._shadowViewMatrix=d.identityMat4());const e=i._state.pos,t=s.look,r=s.up;d.lookAtMat4v(e,t,r,i._shadowViewMatrix),i._shadowViewMatrixDirty=!1}return i._shadowViewMatrix},getShadowProjMatrix:()=>{if(i._shadowProjMatrixDirty){i._shadowProjMatrix||(i._shadowProjMatrix=d.identityMat4());const e=i.scene.canvas.canvas;d.perspectiveMat4(Math.PI/180*70,e.clientWidth/e.clientHeight,.1,500,i._shadowProjMatrix),i._shadowProjMatrixDirty=!1}return i._shadowProjMatrix},getShadowRenderBuf:()=>(i._shadowRenderBuf||(i._shadowRenderBuf=new Zn(i.scene.canvas.gl),i._shadowRenderBuf.setSize([1024,1024])),i._shadowRenderBuf)}),this.pos=t.pos,this.color=t.color,this.intensity=t.intensity,this.constantAttenuation=t.constantAttenuation,this.linearAttenuation=t.linearAttenuation,this.quadraticAttenuation=t.quadraticAttenuation,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set pos(e){this._state.pos.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get pos(){return this._state.pos}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set constantAttenuation(e){this._state.attenuation[0]=e||0,this.glRedraw()}get constantAttenuation(){return this._state.attenuation[0]}set linearAttenuation(e){this._state.attenuation[1]=e||0,this.glRedraw()}get linearAttenuation(){return this._state.attenuation[1]}set quadraticAttenuation(e){this._state.attenuation[2]=e||0,this.glRedraw()}get quadraticAttenuation(){return this._state.attenuation[2]}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}function $n(e){if(!qn(e.width)||!qn(e.height)){const t=document.createElement("canvas");t.width=eA(e.width),t.height=eA(e.height);t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function qn(e){return 0==(e&e-1)}function eA(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class tA extends D{get type(){return"CubeTexture"}constructor(e,t={}){super(e,t);const i=this.scene.canvas.gl;this._state=new oe({texture:new zi({gl:i,target:i.TEXTURE_CUBE_MAP}),flipY:this._checkFlipY(t.minFilter),encoding:this._checkEncoding(t.encoding),minFilter:1008,magFilter:1006,wrapS:1001,wrapT:1001,mipmaps:!0}),this._src=t.src,this._images=[],this._loadSrc(t.src),m.memory.textures++}_checkFlipY(e){return!!e}_checkEncoding(e){return 3e3!==(e=e||3e3)&&3001!==e&&(this.error("Unsupported value for 'encoding' - supported values are LinearEncoding and sRGBEncoding. Defaulting to LinearEncoding."),e=3e3),e}_loadSrc(e){const t=this,i=this.scene.canvas.gl;this._images=[];let s=!1,r=0;for(let n=0;n<e.length;n++){const A=new Image;A.onload=function(){let e=A;const o=n;return function(){if(!s&&(e=$n(e),t._images[o]=e,r++,6===r)){let e=t._state.texture;e||(e=new zi({gl:i,target:i.TEXTURE_CUBE_MAP}),t._state.texture=e),e.setImage(t._images,t._state),t.fire("loaded",t._src,!1),t.glRedraw()}}}(),A.onerror=function(){s=!0},A.src=e[n]}}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),m.memory.textures--,this._state.destroy()}}class iA extends tA{get type(){return"ReflectionMap"}constructor(e,t={}){super(e,t),this.scene._lightsState.addReflectionMap(this._state),this.scene._reflectionMapCreated(this)}destroy(){super.destroy(),this.scene._reflectionMapDestroyed(this)}}class sA extends tA{get type(){return"LightMap"}constructor(e,t={}){super(e,t),this.scene._lightMapCreated(this)}destroy(){super.destroy(),this.scene._lightMapDestroyed(this)}}const rA=d.vec4(),nA=d.vec4();class AA extends D{constructor(e,t){super(e,t),this._entity=null,this._visible=null,this._worldPos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._viewPos=d.vec3(),this._canvasPos=d.vec2(),this._occludable=!1,this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewPosDirty=!0,this._needUpdate()})),this._onCameraProjMatrix=this.scene.camera.on("projMatrix",(()=>{this._canvasPosDirty=!0,this._needUpdate()})),this._onEntityDestroyed=null,this._onEntityModelDestroyed=null,this._renderer.addMarker(this),this.entity=t.entity,this.worldPos=t.worldPos,this.occludable=t.occludable}_update(){if(this._viewPosDirty&&(d.transformPoint3(this.scene.camera.viewMatrix,this._worldPos,this._viewPos),this._viewPosDirty=!1,this._canvasPosDirty=!0,this.fire("viewPos",this._viewPos)),this._canvasPosDirty){rA.set(this._viewPos),rA[3]=1,d.transformPoint4(this.scene.camera.projMatrix,rA,nA);const e=this.scene.canvas.boundary;this._canvasPos[0]=Math.floor((1+nA[0]/nA[3])*e[2]/2),this._canvasPos[1]=Math.floor((1-nA[1]/nA[3])*e[3]/2),this._canvasPosDirty=!1,this.fire("canvasPos",this._canvasPos)}}_setVisible(e){this._visible,this._visible=e,this.fire("visible",this._visible)}set entity(e){this._entity!==e&&(this._cleanupDestroyedHandlers(),this._entity=e,this._entity&&(this._entity.isSceneModelEntity?this._onEntityModelDestroyed=this._entity.model.on("destroyed",(()=>{this._entity=null,this._onEntityModelDestroyed=null})):this._onEntityDestroyed=this._entity.on("destroyed",(()=>{this._entity=null,this._onEntityDestroyed=null}))),this.fire("entity",this._entity,!0))}get entity(){return this._entity}set occludable(e){(e=!!e)!==this._occludable&&(this._occludable=e,this._occludable&&this._renderer.markerWorldPosUpdated(this))}get occludable(){return this._occludable}set worldPos(e){this._worldPos.set(e||[0,0,0]),Ye(this._worldPos,this._origin,this._rtcPos),this._occludable&&this._renderer.markerWorldPosUpdated(this),this._viewPosDirty=!0,this.fire("worldPos",this._worldPos),this._needUpdate()}get worldPos(){return this._worldPos}get origin(){return this._origin}get rtcPos(){return this._rtcPos}get viewPos(){return this._update(),this._viewPos}get canvasPos(){return this._update(),this._canvasPos}get visible(){return!!this._visible}destroy(){this.fire("destroyed",!0),this.scene.camera.off(this._onCameraViewMatrix),this.scene.camera.off(this._onCameraProjMatrix),this._cleanupDestroyedHandlers(),this._renderer.removeMarker(this),super.destroy()}_cleanupDestroyedHandlers(){this._entity&&(null!==this._onEntityDestroyed&&(this._entity.model?this._entity.model.off(this._onEntityDestroyed):this._entity.off(this._onEntityDestroyed),this._onEntityDestroyed=null),null!==this._onEntityModelDestroyed&&(this._entity.model&&this._entity.model.off(this._onEntityModelDestroyed),this._onEntityModelDestroyed=null))}}class oA extends AA{constructor(e,t={}){super(e,{entity:t.entity,occludable:t.occludable,worldPos:t.worldPos}),this._occluded=!1,this._visible=!0,this._src=null,this._image=null,this._pos=d.vec3(),this._origin=d.vec3(),this._rtcPos=d.vec3(),this._dir=d.vec3(),this._size=1,this._imageSize=d.vec2(),this._texture=new $i(this,{src:t.src}),this._geometry=new be(this,{primitive:"triangles",positions:[3,3,0,-3,3,0,-3,-3,0,3,-3,0],normals:[-1,0,0,-1,0,0,-1,0,0,-1,0,0],uv:[1,-1,0,-1,0,0,1,0],indices:[0,1,2,0,2,3]}),this._mesh=new Qi(this,{geometry:this._geometry,material:new Ni(this,{ambient:[.9,.3,.9],shininess:30,diffuseMap:this._texture,backfaces:!0}),scale:[1,1,1],position:t.worldPos,rotation:[90,0,0],billboard:"spherical",occluder:!1}),this.visible=!0,this.collidable=t.collidable,this.clippable=t.clippable,this.pickable=t.pickable,this.opacity=t.opacity,this.size=t.size,t.image?this.image=t.image:this.src=t.src}_setVisible(e){this._occluded=!e,this._mesh.visible=this._visible&&!this._occluded,super._setVisible(e)}set visible(e){this._visible=null==e||e,this._mesh.visible=this._visible&&!this._occluded}get visible(){return this._visible}set image(e){this._image=e,this._image&&(this._imageSize[0]=this._image.width,this._imageSize[1]=this._image.height,this._updatePlaneSizeFromImage(),this._src=null,this._texture.image=this._image)}get image(){return this._image}set src(e){if(this._src=e,this._src){this._image=null;const e=new Image;e.onload=()=>{this._texture.image=e,this._imageSize[0]=e.width,this._imageSize[1]=e.height,this._updatePlaneSizeFromImage()},e.src=this._src}}get src(){return this._src}set size(e){this._size=null==e?1:e,this._image&&this._updatePlaneSizeFromImage()}get size(){return this._size}set collidable(e){this._mesh.collidable=!1!==e}get collidable(){return this._mesh.collidable}set clippable(e){this._mesh.clippable=!1!==e}get clippable(){return this._mesh.clippable}set pickable(e){this._mesh.pickable=!1!==e}get pickable(){return this._mesh.pickable}set opacity(e){this._mesh.opacity=e}get opacity(){return this._mesh.opacity}_updatePlaneSizeFromImage(){const e=.5*this._size,t=this._imageSize[0],i=this._imageSize[1],s=i/t;this._geometry.positions=t>i?[e,e*s,0,-e,e*s,0,-e,-e*s,0,e,-e*s,0]:[e/s,e,0,-e/s,e,0,-e/s,-e,0,e/s,-e,0]}}class aA{constructor(e){this._eye=d.vec3(),this._look=d.vec3(),this._up=d.vec3(),this._projection={},e&&this.saveCamera(e)}saveCamera(e){const t=e.camera,i=t.project;switch(this._eye.set(t.eye),this._look.set(t.look),this._up.set(t.up),t.projection){case"perspective":this._projection={projection:"perspective",fov:i.fov,fovAxis:i.fovAxis,near:i.near,far:i.far};break;case"ortho":this._projection={projection:"ortho",scale:i.scale,near:i.near,far:i.far};break;case"frustum":this._projection={projection:"frustum",left:i.left,right:i.right,top:i.top,bottom:i.bottom,near:i.near,far:i.far};break;case"custom":this._projection={projection:"custom",matrix:i.matrix.slice()}}}restoreCamera(e,t){const i=e.camera,s=this._projection;function r(){switch(s.type){case"perspective":i.perspective.fov=s.fov,i.perspective.fovAxis=s.fovAxis,i.perspective.near=s.near,i.perspective.far=s.far;break;case"ortho":i.ortho.scale=s.scale,i.ortho.near=s.near,i.ortho.far=s.far;break;case"frustum":i.frustum.left=s.left,i.frustum.right=s.right,i.frustum.top=s.top,i.frustum.bottom=s.bottom,i.frustum.near=s.near,i.frustum.far=s.far;break;case"custom":i.customProjection.matrix=s.matrix}}t?e.viewer.cameraFlight.flyTo({eye:this._eye,look:this._look,up:this._up,orthoScale:s.scale,projection:s.projection},(()=>{r(),t()})):(i.eye=this._eye,i.look=this._look,i.up=this._up,r(),i.projection=s.projection)}}const lA=d.vec3();class cA{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){this.numObjects=0,this._mask=i?w.apply(i,{}):null;const s=!i||i.visible,r=!i||i.edges,n=!i||i.xrayed,A=!i||i.highlighted,o=!i||i.selected,a=!i||i.clippable,l=!i||i.pickable,c=!i||i.colorize,h=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e<t;e++){const t=d[u[e].id];if(t){if(s&&(this.objectsVisible[e]=t.visible),r&&(this.objectsEdges[e]=t.edges),n&&(this.objectsXrayed[e]=t.xrayed),A&&(this.objectsHighlighted[e]=t.highlighted),o&&(this.objectsSelected[e]=t.selected),a&&(this.objectsClippable[e]=t.clippable),l&&(this.objectsPickable[e]=t.pickable),c){const i=t.colorize;this.objectsColorize[3*e+0]=i[0],this.objectsColorize[3*e+1]=i[1],this.objectsColorize[3*e+2]=i[2]}h&&(this.objectsOpacity[e]=t.opacity),this.numObjects++}}}restoreObjects(e,t){const i=this._mask,s=!i||i.visible,r=!i||i.edges,n=!i||i.xrayed,A=!i||i.highlighted,o=!i||i.selected,a=!i||i.clippable,l=!i||i.pickable,c=!i||i.colorize,h=!i||i.opacity,u=t.metaObjects,d=e.objects;for(let e=0,t=u.length;e<t;e++){const t=d[u[e].id];t&&(s&&(t.visible=this.objectsVisible[e]),r&&(t.edges=this.objectsEdges[e]),n&&(t.xrayed=this.objectsXrayed[e]),A&&(t.highlighted=this.objectsHighlighted[e]),o&&(t.selected=this.objectsSelected[e]),a&&(t.clippable=this.objectsClippable[e]),l&&(t.pickable=this.objectsPickable[e]),c&&(lA[0]=this.objectsColorize[3*e+0],lA[1]=this.objectsColorize[3*e+1],lA[2]=this.objectsColorize[3*e+2],t.colorize=lA),h&&(t.opacity=this.objectsOpacity[e]))}}}const hA=d.vec3();class uA{constructor(){this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsHasColorize=[],this.objectsOpacity=[],this.numObjects=0}saveObjects(e,t){this.numObjects=0,this._mask=t?w.apply(t,{}):null;const i=e.objects,s=!t||t.visible,r=!t||t.edges,n=!t||t.xrayed,A=!t||t.highlighted,o=!t||t.selected,a=!t||t.clippable,l=!t||t.pickable,c=!t||t.colorize,h=!t||t.opacity;for(let e in i)if(i.hasOwnProperty(e)){const t=i[e],u=this.numObjects;if(s&&(this.objectsVisible[u]=t.visible),r&&(this.objectsEdges[u]=t.edges),n&&(this.objectsXrayed[u]=t.xrayed),A&&(this.objectsHighlighted[u]=t.highlighted),o&&(this.objectsSelected[u]=t.selected),a&&(this.objectsClippable[u]=t.clippable),l&&(this.objectsPickable[u]=t.pickable),c){const e=t.colorize;e?(this.objectsColorize[3*u+0]=e[0],this.objectsColorize[3*u+1]=e[1],this.objectsColorize[3*u+2]=e[2],this.objectsHasColorize[u]=!0):this.objectsHasColorize[u]=!1}h&&(this.objectsOpacity[u]=t.opacity),this.numObjects++}}restoreObjects(e){const t=this._mask,i=!t||t.visible,s=!t||t.edges,r=!t||t.xrayed,n=!t||t.highlighted,A=!t||t.selected,o=!t||t.clippable,a=!t||t.pickable,l=!t||t.colorize,c=!t||t.opacity;var h=0;const u=e.objects;for(let e in u)if(u.hasOwnProperty(e)){const t=u[e];i&&(t.visible=this.objectsVisible[h]),s&&(t.edges=this.objectsEdges[h]),r&&(t.xrayed=this.objectsXrayed[h]),n&&(t.highlighted=this.objectsHighlighted[h]),A&&(t.selected=this.objectsSelected[h]),o&&(t.clippable=this.objectsClippable[h]),a&&(t.pickable=this.objectsPickable[h]),l&&(this.objectsHasColorize[h]?(hA[0]=this.objectsColorize[3*h+0],hA[1]=this.objectsColorize[3*h+1],hA[2]=this.objectsColorize[3*h+2],t.colorize=hA):t.colorize=null),c&&(t.opacity=this.objectsOpacity[h]),h++}}}class dA extends K{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.v3=t.v3,this.t=t.t}set v0(e){this._v0=e||d.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||d.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||d.vec3([0,0,0])}get v2(){return this._v2}set v3(e){this.fire("v3",this._v3=e||d.vec3([0,0,0]))}get v3(){return this._v3}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b3(e,this._v0[0],this._v1[0],this._v2[0],this._v3[0]),t[1]=d.b3(e,this._v0[1],this._v1[1],this._v2[1],this._v3[1]),t[2]=d.b3(e,this._v0[2],this._v1[2],this._v2[2],this._v3[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,v3:this._v3,t:this._t}}}class fA extends K{constructor(e,t={}){super(e,t),this._cachedLengths=[],this._dirty=!0,this._curves=[],this._t=0,this._dirtySubs=[],this._destroyedSubs=[],this.curves=t.curves||[],this.t=t.t}addCurve(e){this._curves.push(e),this._dirty=!0}set curves(e){var t,i,s;for(e=e||[],i=0,s=this._curves.length;i<s;i++)(t=this._curves[i]).off(this._dirtySubs[i]),t.off(this._destroyedSubs[i]);this._curves=[],this._dirtySubs=[],this._destroyedSubs=[];var r=this;function n(){r._dirty=!0}function A(){var e=this.id;for(i=0,s=r._curves.length;i<s;i++)if(r._curves[i].id===e)return r._curves=r._curves.slice(i,i+1),r._dirtySubs=r._dirtySubs.slice(i,i+1),r._destroyedSubs=r._destroyedSubs.slice(i,i+1),void(r._dirty=!0)}for(i=0,s=e.length;i<s;i++){if(t=e[i],w.isNumeric(t)||w.isString(t)){var o=t;if(!(t=this.scene.components[o])){this.error("Component not found: "+_inQuotes(o));continue}}var a=t.type;"xeokit.SplineCurve"===a||"xeokit.Path"===a||"xeokit.CubicBezierCurve"===a||"xeokit.QuadraticBezierCurve"===a?(this._curves.push(t),this._dirtySubs.push(t.on("dirty",n)),this._destroyedSubs.push(t.once("destroyed",A))):this.error("Component "+_inQuotes(t.id)+" is not a xeokit.SplineCurve, xeokit.Path or xeokit.QuadraticBezierCurve")}this._dirty=!0}get curves(){return this._curves}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}get length(){var e=this._getCurveLengths();return e[e.length-1]}getPoint(e){for(var t,i=e*this.length,s=this._getCurveLengths(),r=0;r<s.length;){if(s[r]>=i){var n=1-(s[r]-i)/(t=this._curves[r]).length;return t.getPointAt(n)}r++}return null}_getCurveLengths(){if(!this._dirty)return this._cachedLengths;var e,t=[],i=0,s=this._curves.length;for(e=0;e<s;e++)i+=this._curves[e].length,t.push(i);return this._cachedLengths=t,this._dirty=!1,t}_getJSON(){for(var e=[],t=0,i=this._curves.length;t<i;t++)e.push(this._curves[t].id);return{curves:e,t:this._t}}destroy(){var e,t,i;for(super.destroy(),e=0,t=this._curves.length;e<t;e++)(i=this._curves[e]).off(this._dirtySubs[e]),i.off(this._destroyedSubs[e])}}class pA extends K{constructor(e,t={}){super(e,t),this.v0=t.v0,this.v1=t.v1,this.v2=t.v2,this.t=t.t}set v0(e){this._v0=e||d.vec3([0,0,0])}get v0(){return this._v0}set v1(e){this._v1=e||d.vec3([0,0,0])}get v1(){return this._v1}set v2(e){this._v2=e||d.vec3([0,0,0])}get v2(){return this._v2}set t(e){e=e||0,this._t=e<0?0:e>1?1:e}get t(){return this._t}get point(){return this.getPoint(this._t)}getPoint(e){var t=d.vec3();return t[0]=d.b2(e,this._v0[0],this._v1[0],this._v2[0]),t[1]=d.b2(e,this._v0[1],this._v1[1],this._v2[1]),t[2]=d.b2(e,this._v0[2],this._v1[2],this._v2[2]),t}getJSON(){return{v0:this._v0,v1:this._v1,v2:this._v2,t:this._t}}}class gA extends Wn{constructor(e,t={}){super(e,t)}}const mA=d.vec3(),_A=d.vec3(),bA=d.vec4(),yA=d.vec3([0,0,-1]),wA=d.vec3([0,0,1]),vA=d.vec3([0,1,0]);class BA extends D{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new oe({active:!0,pos:d.vec3(),quaternion:d.vec4(),roll:0,dir:d.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active),this.scene.fire("sectionPlaneUpdated",this)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-d.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos),this.scene.fire("sectionPlaneUpdated",this)}get pos(){return this._state.pos}set quaternion(e){this._state.quaternion.set(e||[0,0,0,-1]),d.vec3ApplyQuaternion(this._state.quaternion,wA,this._state.dir);const t=d.vec3ApplyQuaternion(this._state.quaternion,vA,mA),i=d.vec3PairToQuaternion(wA,this._state.dir,bA),s=d.vec3ApplyQuaternion(i,vA,_A),r=Math.acos(Math.min(1,d.dotVec3(t,s))),n=Math.sign(d.dotVec3(this._state.dir,d.cross3Vec3(t,s,_A)));this._state.roll=n*r,this._onDirUpdated()}get quaternion(){return this._state.quaternion}set roll(e){this._state.roll=e||0,this._onDirRollUpdated()}get roll(){return this._state.roll}set dir(e){this._state.dir.set(e||yA),this._onDirRollUpdated()}_onDirRollUpdated(){d.vec3PairToQuaternion(wA,this._state.dir,this._state.quaternion),bA[0]=0,bA[1]=0,bA[2]=-1,bA[3]=this._state.roll,d.angleAxisToQuaternion(bA,bA),d.mulQuaternions(this._state.quaternion,bA,this._state.quaternion),this._onDirUpdated()}_onDirUpdated(){this._state.dist=-d.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir),this.scene.fire("sectionPlaneUpdated",this)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){d.mulVec3Scalar(this._state.dir,-1,this._state.dir),this.dir=this._state.dir}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}class CA{transcode(e,t,i={}){}destroy(){}}class MA{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this.pickSurfacePrecision=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1,this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._canvasPos=new Int16Array([0,0]),this._snappedCanvasPos=new Int16Array([0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get snappedCanvasPos(){return this._gotSnappedCanvasPos?this._snappedCanvasPos:null}set snappedCanvasPos(e){e?(this._snappedCanvasPos[0]=e[0],this._snappedCanvasPos[1]=e[1],this._gotSnappedCanvasPos=!0):this._gotSnappedCanvasPos=!1}get worldPos(){return this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}get snapped(){return this.snappedToEdge||this.snappedToVertex}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this.pickSurfacePrecision=!1,this._gotCanvasPos=!1,this._gotSnappedCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1,this.touchInput=!1,this.snappedToEdge=!1,this.snappedToVertex=!1}}const EA={isIphoneSafari(){const e=window.navigator.userAgent,t=/iPhone/i.test(e),i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isIphoneOrIpadSafari(){const e=window.navigator.userAgent,t=/iPhone|iPad/i.test(e)||/Macintosh/i.test(e)&&navigator.maxTouchPoints&&navigator.maxTouchPoints>2,i=/Safari/i.test(e)&&!/Chrome/i.test(e);return t&&i},isTouchDevice:()=>"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.mxMaxTouchPoints>0};class FA{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,t.addPlugin(this)}scheduleTask(e){I.scheduleTask(e,null)}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const n=this._subIdMap.addItem();r[n]={callback:i,scope:s||this},this._subIdEvents[n]=t;const A=this._events[t];return void 0!==A&&i.call(s||this,A),n}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}class UA extends D{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle"> <div class="sk-circle1 sk-circle"></div> <div class="sk-circle2 sk-circle"></div> <div class="sk-circle3 sk-circle"></div> <div class="sk-circle4 sk-circle"></div> <div class="sk-circle5 sk-circle"></div> <div class="sk-circle6 sk-circle"></div> <div class="sk-circle7 sk-circle"></div> <div class="sk-circle8 sk-circle"></div> <div class="sk-circle9 sk-circle"></div> <div class="sk-circle10 sk-circle"></div> <div class="sk-circle11 sk-circle"></div> <div class="sk-circle12 sk-circle"></div> </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle { background: transparent; margin: 20px auto; width: 50px; height:50px; position: relative; } .sk-fading-circle .sk-circle { width: 120%; height: 120%; position: absolute; left: 0; top: 0; } .sk-fading-circle .sk-circle:before { content: ''; display: block; margin: 0 auto; width: 15%; height: 15%; background-color: #ff8800; border-radius: 100%; -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; animation: sk-circleFadeDelay 1.2s infinite ease-in-out both; } .sk-fading-circle .sk-circle2 { -webkit-transform: rotate(30deg); -ms-transform: rotate(30deg); transform: rotate(30deg); } .sk-fading-circle .sk-circle3 { -webkit-transform: rotate(60deg); -ms-transform: rotate(60deg); transform: rotate(60deg); } .sk-fading-circle .sk-circle4 { -webkit-transform: rotate(90deg); -ms-transform: rotate(90deg); transform: rotate(90deg); } .sk-fading-circle .sk-circle5 { -webkit-transform: rotate(120deg); -ms-transform: rotate(120deg); transform: rotate(120deg); } .sk-fading-circle .sk-circle6 { -webkit-transform: rotate(150deg); -ms-transform: rotate(150deg); transform: rotate(150deg); } .sk-fading-circle .sk-circle7 { -webkit-transform: rotate(180deg); -ms-transform: rotate(180deg); transform: rotate(180deg); } .sk-fading-circle .sk-circle8 { -webkit-transform: rotate(210deg); -ms-transform: rotate(210deg); transform: rotate(210deg); } .sk-fading-circle .sk-circle9 { -webkit-transform: rotate(240deg); -ms-transform: rotate(240deg); transform: rotate(240deg); } .sk-fading-circle .sk-circle10 { -webkit-transform: rotate(270deg); -ms-transform: rotate(270deg); transform: rotate(270deg); } .sk-fading-circle .sk-circle11 { -webkit-transform: rotate(300deg); -ms-transform: rotate(300deg); transform: rotate(300deg); } .sk-fading-circle .sk-circle12 { -webkit-transform: rotate(330deg); -ms-transform: rotate(330deg); transform: rotate(330deg); } .sk-fading-circle .sk-circle2:before { -webkit-animation-delay: -1.1s; animation-delay: -1.1s; } .sk-fading-circle .sk-circle3:before { -webkit-animation-delay: -1s; animation-delay: -1s; } .sk-fading-circle .sk-circle4:before { -webkit-animation-delay: -0.9s; animation-delay: -0.9s; } .sk-fading-circle .sk-circle5:before { -webkit-animation-delay: -0.8s; animation-delay: -0.8s; } .sk-fading-circle .sk-circle6:before { -webkit-animation-delay: -0.7s; animation-delay: -0.7s; } .sk-fading-circle .sk-circle7:before { -webkit-animation-delay: -0.6s; animation-delay: -0.6s; } .sk-fading-circle .sk-circle8:before { -webkit-animation-delay: -0.5s; animation-delay: -0.5s; } .sk-fading-circle .sk-circle9:before { -webkit-animation-delay: -0.4s; animation-delay: -0.4s; } .sk-fading-circle .sk-circle10:before { -webkit-animation-delay: -0.3s; animation-delay: -0.3s; } .sk-fading-circle .sk-circle11:before { -webkit-animation-delay: -0.2s; animation-delay: -0.2s; } .sk-fading-circle .sk-circle12:before { -webkit-animation-delay: -0.1s; animation-delay: -0.1s; } @-webkit-keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } } @keyframes sk-circleFadeDelay { 0%, 39%, 100% { opacity: 0; } 40% { opacity: 1; } }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null);const e=document.getElementById("xeokit-spinner-css");e&&e.parentNode.removeChild(e)}}const xA=["webgl2","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class IA extends D{constructor(e,t={}){super(e,t),this._backgroundColor=d.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.resolutionScale=t.resolutionScale,this.canvas.width=Math.round(this.canvas.clientWidth*this._resolutionScale),this.canvas.height=Math.round(this.canvas.clientHeight*this._resolutionScale),this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;let s=!0;new ResizeObserver((e=>{for(const t of e)t.contentBoxSize&&(s=!0)})).observe(this.canvas),this._tick=this.scene.on("tick",(()=>{s&&(s=!1,i.canvas.width=Math.round(i.canvas.clientWidth*i._resolutionScale),i.canvas.height=Math.round(i.canvas.clientHeight*i._resolutionScale),i.boundary[0]=i.canvas.offsetLeft,i.boundary[1]=i.canvas.offsetTop,i.boundary[2]=i.canvas.clientWidth,i.boundary[3]=i.canvas.clientHeight,i.fire("boundary",i.boundary))})),this._spinner=new UA(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}get type(){return"Canvas"}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e,this.glRedraw()}get backgroundColor(){return this._backgroundColor}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get resolutionScale(){return this._resolutionScale}set resolutionScale(e){if((e=e||1)===this._resolutionScale)return;this._resolutionScale=e;const t=this.canvas;t.width=Math.round(t.clientWidth*this._resolutionScale),t.height=Math.round(t.clientHeight*this._resolutionScale),this.glRedraw()}get spinner(){return this._spinner}_createCanvas(){const e="xeokit-canvas-"+d.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<xA.length;e++)try{this.gl=this.canvas.getContext(xA[e],this.contextAttr)}catch(e){}this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0));{const e=this.gl;let t="__",i=e.activeTexture;e.activeTexture=function(e){t!==e&&(t=e,i.call(this,e))};let s={},r=e.bindTexture;e.bindTexture=function(e,i){s[t]!==i&&(s[t]=i,r.call(this,e,i))}}this.gl&&this.webgl2&&(this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST),this.gl,WebGL2RenderingContext)}getSnapshot(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}readPixels(e,t,i){return this.scene._renderer.snapshot.readPixels(e,t,i)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.gl=null,super.destroy()}}class TA{constructor(e){this._matPool=[],this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this.lastProgramId=null,this.pbrEnabled=!1,this.colorTextureEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.viewParams={},this.viewParams.viewMatrix=null,this.viewParams.projMatrix=null,this.viewParams.near=.01,this.viewParams.far=5e3,this.pickInvisible=!1,this.lineWidth=1,this.snapPickLayerParams=[],this.snapPickCoordinateScale=d.vec3(),this.snapPickOrigin=d.vec3()}getRTCViewMatrix(e,t){let i=this._rtcViewMats[e];return i||(i=this._getNewMat(),Je(this.viewParams.viewMatrix,t,i),this._rtcViewMats[e]=i),i}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=d.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}const PA={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},SA=document.createElement("canvas");if(SA){const e=SA.getContext("webgl",{antialias:!0})||SA.getContext("experimental-webgl",{antialias:!0});PA.WEBGL=!!e,PA.WEBGL&&(PA.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?PA.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?PA.FS_MAX_FLOAT_PRECISION="mediump":PA.FS_MAX_FLOAT_PRECISION="lowp":PA.FS_MAX_FLOAT_PRECISION="mediump",PA.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),PA.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),PA.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),PA.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),PA.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),PA.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),PA.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),PA.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),PA.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),PA.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){PA.SUPPORTED_EXTENSIONS[e]=!0})))}class DA{constructor(e){this.aabb=d.AABB3(),this.origin=d.vec3(e),this.originHash=this.origin.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(e,t){if(this.markerListDirty){for(var i in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(i)&&(this.markerList[this.numMarkers]=this.markers[i],this.markerIndices[i]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0}if(this.positionsDirty){let t=0;for(let e=0;e<this.numMarkers;e++)if(this.markerList[e]){const i=this.markerList[e].rtcPos;this.positions[t++]=i[0],this.positions[t++]=i[1],this.positions[t++]=i[2],this.indices[e]=e}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers,this.positionsDirty=!1;const i=this.aabb;d.collapseAABB3(i),d.expandAABB3Points3(i,this.positions);const s=this.origin;i[0]+=s[0],i[1]+=s[1],i[2]+=s[2],i[3]+=s[0],i[4]+=s[1],i[5]+=s[2],this.positionsBuf&&this.lenPositionsBuf!==this.positions.length&&(this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null);const r=new Float32Array(this.positions);this.positionsBuf?this.positionsBuf.setData(r):(this.positionsBuf=new ae(e,e.ARRAY_BUFFER,r,r.length,3,e.STATIC_DRAW),this.indicesBuf=new ae(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),this.indices.length,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length)}if(this.occlusionTestListDirty){let e=0;this.lenOcclusionTestList=0;for(let i=0;i<this.numMarkers;i++){const s=this.markerList[i];s.entity&&!s.entity.visible||!t(s)?s._setVisible(!1):s.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=s,this.pixels[e++]=s.canvasPos[0],this.pixels[e++]=s.canvasPos[1]):s._setVisible(!0)}}}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const kA=d.vec3([255,0,0]);d.vec3();class QA{constructor(e){this._scene=e,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._drawable=null,this._markersToOcclusionLayersMap={};const t=e.camera,i=()=>{this._occlusionTestListDirty=!0};this._onCameraViewMatrix=t.on("viewMatrix",i),this._onCameraProjMatrix=t.on("projMatrix",i),this._onCanvasBoundary=e.canvas.on("boundary",i)}_addMarker(e,t){this._occlusionLayers[t]||(this._occlusionLayers[t]=new DA(e.origin),this._occlusionLayersListDirty=!0);const i=this._occlusionLayers[t];i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i}_removeMarker(e,t){1===e.numMarkers?(e.destroy(),delete this._occlusionLayers[e.originHash],this._occlusionLayersListDirty=!0):e.removeMarker(t),delete this._markersToOcclusionLayersMap[t.id]}addMarker(e){const t=e.origin.join();this._addMarker(e,t),this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(t){const i=e.origin.join();i!==t.originHash?(this._removeMarker(t,e),this._addMarker(e,i)):t.markerWorldPosUpdated(e)}}removeMarker(e){const t=e.origin.join(),i=this._occlusionLayers[t];i&&this._removeMarker(i,e)}get needOcclusionTest(){return this._occlusionTestListDirty}drawMarkers(){const e=this._scene,t=e.canvas,i=t.gl,s=e._sectionPlanesState,r=[t.canvas.id,s.getHash()].join(";");if(!this._drawable||r!==this._drawable.shaderSourceHash){this._drawable&&this._drawable.destroy();const n=mi(),A=n.programVariables,o=A.createUniform("mat4","viewMatrix"),a=A.createUniform("mat4","projMatrix"),l=A.createAttribute("vec3","position"),c=A.createOutput("vec4","outColor"),h="clipPos",[u,f]=n.buildProgram(i,"OcclusionTester",{sectionPlanesState:s,getLogDepth:e.logarithmicDepthBufferEnabled&&(e=>e),clippableTest:()=>"true",getVertexData:()=>{const t=[];return t.push(`vec4 worldPosition = vec4(${l}, 1.0);`),t.push(`vec4 ${h} = ${a} * ${o} * worldPosition;`),!e.logarithmicDepthBufferEnabled&&e.markerZOffset<0&&t.push(`${h}.z += ${e.markerZOffset};`),t},worldPositionAttribute:"worldPosition",getPointSize:()=>"20.0",clipPos:h,appendFragmentOutputs:e=>e.push(`${c} = vec4(1.0, 0.0, 0.0, 1.0);`)});if(f)throw console.error(f.join("\n")),f.join("\n");this._occlusionTestListDirty=!0,this._drawable={shaderSourceHash:r,destroy:()=>u.destroy(),drawCall:()=>{const r=e.camera,n=r.project;u.bind(),a.setInputValue(n.matrix);const A=t.boundary,c=A[2],h=A[3],f=r.perspective.near,p=e=>{const t=e.viewPos,i=e.canvasPos,s=i[0],r=i[1];return t[2]<=-f&&s>=-10&&r>=-10&&s<=c+10&&r<=h+10};this._occlusionLayersList.forEach((e=>{e.update(i,p);const t=s.sectionPlanes.some(((t,i)=>{const s=t.active?d.planeAABB3Intersect(t.dir,t.dist,e.aabb):1,r=-1===s;return e.sectionPlanesActive[i]=0===s,r}));if(!t){const t=e.origin;o.setInputValue(Je(r.viewMatrix,t)),u.inputSetters.setUniforms(null,{view:{far:n.far},mesh:{origin:t,renderFlags:{sectionPlanesActivePerLayer:e.sectionPlanesActive}}}),l.setInputValue(e.positionsBuf);const s=e.indicesBuf;s.bind(),i.drawElements(i.POINTS,s.numItems,s.itemType,0)}}))}}}if(this._occlusionLayersListDirty){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e,this._occlusionLayersListDirty=!1}if(this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++){this._occlusionLayersList[e].occlusionTestListDirty=!0}this._occlusionTestListDirty=!1}this._drawable.drawCall()}doOcclusionTest(e){this._occlusionLayersList.forEach((t=>{for(let i=0;i<t.lenOcclusionTestList;i++){const s=2*i,r=e(t.pixels[s],t.pixels[s+1]);t.occlusionTestList[i]._setVisible(d.compareVec3(kA,r))}}))}destroy(){this.destroyed||(this._occlusionLayersList.forEach((e=>e.destroy())),this._drawable&&this._drawable.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0)}}const RA=d.vec3([0,0,0]),OA=d.vec4([1/4294967296,1/16777216,1/65536,1/256]),VA=e=>e[0]+(e[1]<<8)+(e[2]<<16)+(e[3]<<24),LA=e=>d.normalizeVec3(d.divVec3Scalar(e,d.MAX_INT,d.vec3())),HA=(e,t,i)=>d.vec3([e[0]*i[0]+t[0],e[1]*i[1]+t[1],e[2]*i[2]+t[2]]),NA=function(t,i){i=i||{};const s=new TA,r=t.canvas.canvas,n=t.canvas.gl,A=!!i.transparent,o=i.alphaDepthMask,a=new e({});let l={},c={},h=[],u=[],f=[],p=!0,g=!0,_=!0,b=!0,y=!0,w=!0,v=!0,B=!0;const C=function(){const e={},i={};return{getRenderBuffer:(s,r,A)=>{const o=1===t.canvas.resolutionScale?e:i;return o[s]||(o[s]=new Zn(n,r,A)),o[s]},destroy:()=>{Object.values(e).forEach((e=>e.destroy())),Object.values(i).forEach((e=>e.destroy()))}}}(),M=(e,t,i,s)=>{const r=i.programVariables,n=r.createUniform("vec2","uViewportInv"),A=r.createUniform("float","uCameraNear"),o=r.createUniform("float","uCameraFar"),a=r.createUniform("sampler2D","uDepthTexture"),l=r.createAttribute("vec2","uv"),c=r.createVarying("vec2","vUV",(()=>l)),h=r.createOutput("vec4","outColor"),u=r.createFragmentDefinition("getOutColor",((e,t)=>{const i="getDepth";t.push(`\n float getDepth(const in vec2 uv) {\n return texture(${a}, uv).r;\n }\n `),t.push(s(e,c,n,A,o,i))})),[d,f]=i.buildProgram(e,t,{clipPos:`vec4(2.0 * ${l} - 1.0, 0.0, 1.0)`,appendFragmentOutputs:e=>e.push(`${h} = ${u}();`)});if(f)throw console.error(f.join("\n")),f;{const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new ae(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),s=new Uint32Array([0,1,2,0,2,3]),r=new ae(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW);return{destroy:d.destroy,bind:(e,t,s)=>{d.bind(),n.setInputValue([1/e[0],1/e[1]]),A.setInputValue(t.near),o.setInputValue(t.far),a.setInputValue(s),l.setInputValue(i)},draw:()=>{r.bind(),e.drawElements(e.TRIANGLES,r.numItems,r.itemType,0)}}}},E=function(){let e=null,t=null;return{destroy:()=>e&&e.destroy(),render:(i,s,r,A)=>{const o=Math.floor(r.numSamples);if(t!==o){e&&e.destroy();const i=mi(),s=i.programVariables,r=s.createUniform("mat4","uProjectMatrix"),A=s.createUniform("mat4","uInvProjMatrix"),a=s.createUniform("bool","uPerspective"),l=s.createUniform("float","uScale"),c=s.createUniform("float","uIntensity"),h=s.createUniform("float","uBias"),u=s.createUniform("float","uKernelRadius"),d=s.createUniform("float","uMinResolution"),f=s.createUniform("float","uRandomSeed"),p=M(n,"SAOOcclusionRenderer",i,((e,t,i,s,n,p)=>`\n #define EPSILON 1e-6\n #define PI 3.14159265359\n #define PI2 6.28318530718\n #define NUM_SAMPLES ${o}\n #define NUM_RINGS 4\n\n const vec3 packFactors = vec3(256. * 256. * 256., 256. * 256., 256.);\n\n vec4 packFloatToRGBA(const in float v) {\n vec4 r = vec4(fract(v * packFactors), v);\n r.yzw -= r.xyz / 256.;\n return r * 256. / 255.;\n }\n\n highp float rand(const in vec2 uv) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n return fract(sin(mod(dot(uv, vec2(a, b)), PI)) * c);\n }\n\n vec3 getViewPos(const in vec2 screenPos, const in float depth) {\n float near = ${s};\n float far = ${n};\n float viewZ = (${a}\n ? ((near * far) / ((far - near) * depth - far))\n : (depth * (near - far) - near));\n float clipW = ${r}[2][3] * viewZ + ${r}[3][3];\n return (${A} * (clipW * vec4((vec3(screenPos, depth) - 0.5) * 2.0, 1.0))).xyz;\n }\n\n vec4 ${e}() {\n float centerDepth = ${p}(${t});\n if (centerDepth >= (1.0 - EPSILON)) {\n discard;\n }\n\n vec3 centerViewPosition = getViewPos(${t}, centerDepth);\n float scaleDividedByCameraFar = ${l} / ${n};\n float minResolutionMultipliedByCameraFar = ${d} * ${n};\n vec3 centerViewNormal = normalize(cross(dFdx(centerViewPosition), dFdy(centerViewPosition)));\n\n vec2 radiusStep = ${u} * ${i} / float(NUM_SAMPLES);\n vec2 radius = radiusStep;\n const float angleStep = PI2 * float(NUM_RINGS) / float(NUM_SAMPLES);\n float angle = PI2 * rand(${t} + ${f});\n\n float occlusionSum = 0.0;\n float weightSum = 0.0;\n\n for (int i = 0; i < NUM_SAMPLES; i++) {\n vec2 sampleUv = ${t} + vec2(cos(angle), sin(angle)) * radius;\n radius += radiusStep;\n angle += angleStep;\n\n float sampleDepth = ${p}(sampleUv);\n if (sampleDepth >= (1.0 - EPSILON)) {\n continue;\n }\n\n vec3 sampleViewPosition = getViewPos(sampleUv, sampleDepth);\n vec3 viewDelta = sampleViewPosition - centerViewPosition;\n float scaledScreenDistance = scaleDividedByCameraFar * length(viewDelta);\n occlusionSum += max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - ${h}) / (1.0 + scaledScreenDistance * scaledScreenDistance );\n weightSum += 1.0;\n }\n\n return packFloatToRGBA(1.0 - occlusionSum * ${c} / weightSum);\n }`));e={destroy:p.destroy,render:(e,t,i,s)=>{p.bind(e,t,s),r.setInputValue(t.matrix),A.setInputValue(t.inverseMatrix),a.setInputValue("Perspective"===t.type),l.setInputValue(i.scale*t.far/5),c.setInputValue(i.intensity),h.setInputValue(i.bias),u.setInputValue(i.kernelRadius),d.setInputValue(i.minResolution),f.setInputValue(Math.random()),p.draw()}},t=o}e.render(i,s,r,A)}}}(),F=function(){const e=e=>{const t=[];for(let i=0;i<=17;i++)t.push(e[0]*i),t.push(e[1]*i);return new Float32Array(t)},t=e([0,1]),i=e([1,0]),s=new Float32Array((e=>{const t=[];for(let i=0;i<e;++i)t.push(i);return t})(17).map((e=>((e,t)=>Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t))(e,4)))),r=mi(),A=r.programVariables,o=A.createUniform("float","uDepthCutoff"),a=A.createUniformArray("vec2","uSampleOffsets",17),l=A.createUniformArray("float","uSampleWeights",17),c=A.createUniform("sampler2D","uOcclusionTex"),h=M(n,"SAODepthLimitedBlurRenderer",r,((e,t,i,s,r,n)=>`\n #define EPSILON 1e-6\n\n const vec3 packFactors = vec3(256. * 256. * 256., 256. * 256., 256.);\n\n vec4 packFloatToRGBA(const in float v) {\n vec4 r = vec4(fract(v * packFactors), v);\n r.yzw -= r.xyz / 256.;\n return r * 256. / 255.;\n }\n\n float getOcclusion(const in vec2 uv) {\n vec4 v = texture(${c}, uv);\n return dot(floor(v * 255.0 + 0.5) / 255.0, 255. / 256. / vec4(packFactors, 1.)); // unpackRGBAToFloat\n }\n\n float getViewZ(const in float depth) {\n return (${s} * ${r}) / ((${r} - ${s}) * depth - ${r});\n }\n\n vec4 ${e}() {\n float centerDepth = ${n}(${t});\n if (centerDepth >= (1.0 - EPSILON)) {\n discard;\n }\n\n float centerViewZ = getViewZ(centerDepth);\n bool rBreak = false;\n bool lBreak = false;\n\n float weightSum = ${l}[0];\n float occlusionSum = getOcclusion(${t}) * weightSum;\n\n for (int i = 1; i <= 16; i++) {\n float sampleWeight = ${l}[i];\n vec2 sampleUVOffset = ${a}[i] * ${i};\n\n if (! rBreak) {\n vec2 rSampleUV = ${t} + sampleUVOffset;\n if (abs(centerViewZ - getViewZ(${n}(rSampleUV))) > ${o}) {\n rBreak = true;\n } else {\n occlusionSum += getOcclusion(rSampleUV) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n\n if (! lBreak) {\n vec2 lSampleUV = ${t} - sampleUVOffset;\n if (abs(centerViewZ - getViewZ(${n}(lSampleUV))) > ${o}) {\n lBreak = true;\n } else {\n occlusionSum += getOcclusion(lSampleUV) * sampleWeight;\n weightSum += sampleWeight;\n }\n }\n }\n\n return packFloatToRGBA(occlusionSum / weightSum);\n }`));return{destroy:h.destroy,render:(e,r,n,A,u)=>{h.bind(e,r,A),o.setInputValue(.01),a.setInputValue(0===n?i:t),l.setInputValue(s),c.setInputValue(u),h.draw()}}}(),U=function(){let e=null;return function(){if(!e){const i=t.camera;e={get eye(){return i.eye},get far(){return i.project.far},get projMatrix(){return i.projMatrix},get viewMatrix(){return i.viewMatrix},get viewNormalMatrix(){return i.viewNormalMatrix}}}return e}}(),x=(e,t)=>"ortho"===e.projection?1:t/(2*Math.tan(.5*e.perspective.fov*Math.PI/180));function I(){if(p&&(Object.values(l).forEach((e=>{const t=e.drawableListPreCull;let i=0;Object.values(e.drawableMap).forEach((e=>{t[i++]=e})),t.length=i})),p=!1,g=!0),g){let e=0;Object.values(l).forEach((t=>{t.drawableListPreCull.forEach((t=>{h[e++]=t}))})),h.length=e,h.sort(((e,t)=>e.renderOrder-t.renderOrder)),g=!1,_=!0}if(_){let e=0,t=0;h.forEach((i=>{i.rebuildRenderFlags(),i.renderFlags.culled||(i.isUI?f[t++]=i:u[e++]=i)})),u.length=e,f.length=t}}this.scene=t,this._occlusionTester=null,this.capabilities={astcSupported:!!Gi(n,"WEBGL_compressed_texture_astc"),etc1Supported:!0,etc2Supported:!!Gi(n,"WEBGL_compressed_texture_etc"),dxtSupported:!!Gi(n,"WEBGL_compressed_texture_s3tc"),bptcSupported:!!Gi(n,"EXT_texture_compression_bptc"),pvrtcSupported:!(!Gi(n,"WEBGL_compressed_texture_pvrtc")&&!Gi(n,"WEBKIT_WEBGL_compressed_texture_pvrtc"))},this.setTransparentEnabled=function(e){b=e,_=!0},this.setEdgesEnabled=function(e){y=e,_=!0},this.setSAOEnabled=function(e){w=e,_=!0},this.setPBREnabled=function(e){v=e,_=!0},this.setColorTextureEnabled=function(e){B=e,_=!0},this.needStateSort=function(){g=!0},this.shadowsDirty=function(){},this.imageDirty=function(){_=!0},this.addDrawable=function(e,t){const i=t.type;if(!i)return void console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring");let s=l[i];s||(s={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},l[i]=s),s.count++,s.drawableMap[e]=t,c[e]=t,p=!0},this.removeDrawable=function(e){const t=c[e];if(!t)return void console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring");const i=t.type,s=l[i];--s.count<=0?delete l[i]:delete s.drawableMap[e],delete c[e],p=!0},this.getPickID=function(e){return a.addItem(e)},this.putPickID=function(e){a.removeItem(e)},this.clear=function(e){if(n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),A)n.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;n.clearColor(e[0],e[1],e[2],1)}n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT)},this.needsRender=function(){return _||p||g},this.render=function(e,i){I(),_&&(!function(e,i){const r=t.sao,a=w&&r.possible&&r.numSamples>=1&&function(e){const i=t.sao,r=[n.drawingBufferWidth,n.drawingBufferHeight],A=C.getRenderBuffer("saoDepth",[],!0);A.setSize(r),A.bind(),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),s.reset(),s.pass=e,s.viewParams=U(),s.nearPlaneHeight=x(t.camera,n.drawingBufferHeight),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.enable(n.CULL_FACE),n.depthMask(!0),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),u.forEach((e=>{!e.culled&&e.visible&&e.drawDepth&&e.saoEnabled&&e.renderFlags.colorOpaque&&e.drawDepth(s)})),A.unbind();const o=A.depthTexture,a=C.getRenderBuffer("saoOcclusion");if(a.setSize(r),a.bind(),n.viewport(0,0,r[0],r[1]),n.clearColor(0,0,0,1),n.disable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT),E.render(r,t.camera.project,i,o),a.unbind(),i.blur){const e=C.getRenderBuffer("saoOcclusion2");e.setSize(r);const i=(e,i,s)=>{i.bind(),n.viewport(0,0,r[0],r[1]),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.frontFace(n.CCW),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);const A=t.camera.project;F.render(r,A,s,o,e.colorTextures[0]),i.unbind()};i(a,e,0),i(e,a,1)}return a.colorTextures[0]}(e);t._lightsState.lights.forEach((e=>{if(e.castsShadow){const i=e.getShadowRenderBuf();i.bind(),s.reset(),s.backfaces=!0,s.frontface=!0,s.viewParams.viewMatrix=e.getShadowViewMatrix(),s.viewParams.projMatrix=e.getShadowProjMatrix(),s.nearPlaneHeight=x(t.camera,n.drawingBufferHeight),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,1),n.enable(n.DEPTH_TEST),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),Object.values(l).forEach((e=>{e.drawableList.forEach((e=>{!1!==e.visible&&e.castsShadow&&e.drawShadow&&e.renderFlags.colorOpaque&&e.drawShadow(s)}))})),i.unbind()}})),function(e,i,r){const a=[],l=[],c=[],h=[],p=[],g=[],_=[],w=[],C=[],M=[],E=[],F=[],I=[],T=[],P=[],S=[],D=t._lightsState.getAmbientColorAndIntensity();if(s.reset(),s.pass=e,s.withSAO=!1,s.pbrEnabled=v&&!!t.pbrEnabled,s.colorTextureEnabled=B&&!!t.colorTextureEnabled,s.viewParams=U(),s.nearPlaneHeight=x(t.camera,n.drawingBufferHeight),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),A)n.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?D:t.canvas.backgroundColor;n.clearColor(e[0],e[1],e[2],1)}let k,Q;n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.enable(n.CULL_FACE),n.depthMask(!0),n.lineWidth(1),s.lineWidth=1,t.sao,s.saoParams=[n.drawingBufferWidth,n.drawingBufferHeight,t.sao.blendCutoff,t.sao.blendFactor],s.occlusionTexture=r;const R=Date.now();i&&n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);const O=function(e){let i=0,u=0,f=0,m=0,v=0,B=0,U=0,x=0,D=0,R=0,O=0,V=0,L=0,H=0,N=0,G=0;for(let t=0,n=e.length;t<n;t++){if(Q=e[t],!0===Q.culled||!1===Q.visible)continue;const n=Q.renderFlags;n.colorOpaque&&(Q.saoEnabled&&r?a[i++]=Q:Q.drawColorOpaque(s)),b&&n.colorTransparent&&(c[f++]=Q),n.xrayedSilhouetteTransparent&&(_[U++]=Q),n.xrayedSilhouetteOpaque&&(p[v++]=Q),n.highlightedSilhouetteTransparent&&(E[O++]=Q),n.highlightedSilhouetteOpaque&&(C[D++]=Q),n.selectedSilhouetteTransparent&&(P[N++]=Q),n.selectedSilhouetteOpaque&&(I[L++]=Q),Q.edges&&y&&(n.edgesOpaque&&(l[u++]=Q),n.edgesTransparent&&(h[m++]=Q),n.selectedEdgesTransparent&&(S[G++]=Q),n.selectedEdgesOpaque&&(T[H++]=Q),n.xrayedEdgesTransparent&&(w[x++]=Q),n.xrayedEdgesOpaque&&(g[B++]=Q),n.highlightedEdgesTransparent&&(F[V++]=Q),n.highlightedEdgesOpaque&&(M[R++]=Q))}if(i>0)for(s.withSAO=!0,k=0;k<i;k++)a[k].drawColorOpaque(s);if(u>0)for(k=0;k<u;k++)l[k].drawEdgesColorOpaque(s);if(v>0)for(k=0;k<v;k++)p[k].drawSilhouetteXRayed(s);if(B>0)for(k=0;k<B;k++)g[k].drawEdgesXRayed(s);if(U>0||x>0||f>0||m>0){if(n.enable(n.CULL_FACE),n.enable(n.BLEND),A?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):(n.blendEquation(n.FUNC_ADD),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,o||n.depthMask(!1),(f>0||m>0)&&n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),m>0)for(k=0;k<m;k++)Q=h[k],Q.drawEdgesColorTransparent(s);if(f>0){const e=s.viewParams.eye,t=c.map((t=>({drawable:t,distSq:d.distVec3(t.origin||RA,e)})));for(t.sort(((e,t)=>t.distSq-e.distSq)),k=0;k<f;k++)t[k].drawable.drawColorTransparent(s)}if(x>0)for(k=0;k<x;k++)w[k].drawEdgesXRayed(s);if(U>0)for(k=0;k<U;k++)_[k].drawSilhouetteXRayed(s);n.disable(n.BLEND),o||n.depthMask(!0)}if(D>0||R>0){if(s.lastProgramId=null,t.highlightMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),R>0)for(k=0;k<R;k++)M[k].drawEdgesHighlighted(s);if(D>0)for(k=0;k<D;k++)C[k].drawSilhouetteHighlighted(s)}if(O>0||V>0||D>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),n.enable(n.BLEND),A?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),n.enable(n.CULL_FACE),V>0)for(k=0;k<V;k++)F[k].drawEdgesHighlighted(s);if(O>0)for(k=0;k<O;k++)E[k].drawSilhouetteHighlighted(s);n.disable(n.BLEND)}if(L>0||H>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),H>0)for(k=0;k<H;k++)T[k].drawEdgesSelected(s);if(L>0)for(k=0;k<L;k++)I[k].drawSilhouetteSelected(s)}if(N>0||G>0){if(s.lastProgramId=null,t.selectedMaterial.glowThrough&&n.clear(n.DEPTH_BUFFER_BIT),n.enable(n.CULL_FACE),n.enable(n.BLEND),A?(n.blendEquation(n.FUNC_ADD),n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA)):n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),G>0)for(k=0;k<G;k++)S[k].drawEdgesSelected(s);if(N>0)for(k=0;k<N;k++)P[k].drawSilhouetteSelected(s);n.disable(n.BLEND)}};O(u),f.length>0&&(n.clear(n.DEPTH_BUFFER_BIT),O(f));const V=Date.now(),L=m.frame;L.renderTime=(V-R)/1e3,L.drawElements=s.drawElements,L.drawArrays=s.drawArrays,L.useProgram=s.useProgram,L.bindTexture=s.bindTexture,L.bindArray=s.bindArray;const H=PA.MAX_TEXTURE_IMAGE_UNITS;for(let e=0;e<H;e++)n.activeTexture(n.TEXTURE0+e);n.bindTexture(n.TEXTURE_CUBE_MAP,null),n.bindTexture(n.TEXTURE_2D,null);const N=PA.MAX_VERTEX_ATTRIBS;for(let e=0;e<N;e++)n.disableVertexAttribArray(e)}(e,i,a)}(e,i),m.frame.frameCount++,_=!1)};const T=(e,i,s,r,A,o,a)=>{a.reset(),a.backfaces=!0,a.frontface=!0,a.viewParams.eye=r,a.viewParams.projMatrix=A,a.viewParams.viewMatrix=o,a.nearPlaneHeight=x(s,n.drawingBufferHeight);const l=t.canvas.resolutionScale;a.pickClipPos=[e?2*e[0]*l/n.drawingBufferWidth-1:0,e?1-2*e[1]*l/n.drawingBufferHeight:0],a.pickClipPosInv=[n.drawingBufferWidth/i,n.drawingBufferHeight/i]};this.pick=function(){const e=d.vec3(),i=d.vec3(),A=d.vec4(),o=d.vec4(),l=d.vec4(),c=d.vec4(),h=d.vec4(),p=d.mat4(),g=d.mat4(),m=d.mat4(),_=d.mat4(),b=d.vec3([0,1,0]),y=new MA,w=d.vec2(),v=d.vec3(),B=d.vec3(),C=d.vec3();d.vec3(),d.vec3();const M=new Zn(n);M.setSize([1,1]);const E=new Zn(n,[n.RGBA32I]);return E.setSize([3,3]),function(F,U=y){U.reset(),I();let x=null,P=null,S=null;const D=t.camera;if(U.pickSurface=F.pickSurface,F.canvasPos)v[0]=F.canvasPos[0],v[1]=F.canvasPos[1],x=D.viewMatrix,P=D.projMatrix,S=D.projection,w[0]=D.project.near,w[1]=D.project.far,U.canvasPos=F.canvasPos;else{if(F.matrix)x=F.matrix,P=D.projMatrix,S=D.projection,w[0]=D.project.near,w[1]=D.project.far;else{B.set(F.origin||[0,0,0]),C.set(F.direction||[0,0,1]);const t=d.addVec3(B,C,e),s=i;Math.abs(d.dotVec3(C,b))>.999999?(s[0]=0,s[1]=0,s[2]=Math.sign(C[1])):(d.cross3Vec3(C,b,s),d.cross3Vec3(s,C,s),d.normalizeVec3(s,s)),x=d.lookAtMat4v(B,t,s,g),P=D.ortho.matrix,S="ortho",w[0]=D.ortho.near,w[1]=D.ortho.far,U.origin=B,U.direction=C}v[0]=.5*r.clientWidth,v[1]=.5*r.clientHeight}M.bind();const k=e=>T(v,e,D,U.origin||D.eye,P||D.projMatrix,x||D.viewMatrix,s);k(1),s.pickInvisible=!!F.pickInvisible,n.viewport(0,0,1,1),n.depthMask(!0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT);const Q=F.includeEntityIds,R=F.excludeEntityIds,O=function(e){e.forEach((e=>{e.culled||!e.visible||!e.pickable||!e.drawPickMesh||Q&&!Q[e.id]||R&&R[e.id]||e.drawPickMesh(s)}))};O(u),f.length>0&&(n.clear(n.DEPTH_BUFFER_BIT),O(f));const V=VA(M.read(0,0)),L=V>=0&&a.items[V];if(!L)return M.unbind(),null;const H=L.delegatePickedEntity?L.delegatePickedEntity():L;if(!H)return M.unbind(),null;if(F.pickSurface)if(L.canPickTriangle&&L.canPickTriangle())L.drawPickTriangles&&(k(1),n.viewport(0,0,1,1),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),L.drawPickTriangles(s),U.primIndex=3*VA(M.read(0,0))),L.pickTriangleSurface(x,P,S,U),U.pickSurfacePrecision=!1;else if(L.canPickWorldPos&&L.canPickWorldPos()){k(1),s.viewParams.near=w[0],s.viewParams.far=w[1],n.viewport(0,0,1,1),n.clearColor(0,0,0,0),n.depthMask(!0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),L.drawPickDepths(s);const e=d.dotVec4(M.read(0,0),OA),t=(v[0]-r.clientWidth/2)/(r.clientWidth/2),i=-(v[1]-r.clientHeight/2)/(r.clientHeight/2),a=L.origin,u=d.inverseMat4(d.mulMat4(P,a?Je(x,a,p):x,m),_),f=(e,s)=>(s[0]=t,s[1]=i,s[2]=e,s[3]=1,d.transformVec4(u,s,s),d.mulVec4Scalar(s,1/s[3])),g=f(-1,A),b=f(1,o),y=d.subVec3(b,g,l),B=d.addVec3(g,d.mulVec4Scalar(y,e,c),h);if(a&&d.addVec3(B,a),U.worldPos=B,!1!==F.pickSurfaceNormal){k(3),E.bind(),n.viewport(0,0,E.size[0],E.size[1]),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.DEPTH_BUFFER_BIT),n.clearBufferiv(n.COLOR,0,new Int32Array([0,0,0,0])),L.drawPickNormals(s);const e=E.read(1,1,n.RGBA_INTEGER,n.INT,Int32Array,4);E.unbind(),U.worldNormal=LA(e)}U.pickSurfacePrecision=!1}return M.unbind(),U.entity=H,U}}(),this.snapPick=function(){const e=new MA,i=function(){const e={};return t=>{if(!(t in e)){const i=new Zn(n,[n.RGBA32I,n.RGBA32I,n.RGBA8UI],!0);i.setSize([2*t+1,2*t+1]),e[t]=i}return e[t]}}();return function(r,A=e){const{canvasPos:o,origin:l,direction:c,snapRadius:h,snapToVertex:f,snapToEdge:p}=r;if(!f&&!p)return this.pick({canvasPos:o,pickSurface:!0});const g=t.camera,m=h||30,_=o?g.viewMatrix:d.lookAtMat4v(l,d.addVec3(l,c,d.vec3()),d.vec3([0,1,0]),d.mat4());T(o,2*m,g,g.eye,g.projMatrix,_,s);const b=i(m);b.bind(),n.viewport(0,0,b.size[0],b.size[1]),n.enable(n.DEPTH_TEST),n.frontFace(n.CCW),n.disable(n.CULL_FACE),n.depthMask(!0),n.disable(n.BLEND),n.depthFunc(n.LEQUAL),n.clear(n.DEPTH_BUFFER_BIT),n.clearBufferiv(n.COLOR,0,new Int32Array([0,0,0,0])),n.clearBufferiv(n.COLOR,1,new Int32Array([0,0,0,0])),n.clearBufferuiv(n.COLOR,2,new Uint32Array([0,0,0,0])),n.drawBuffers([n.COLOR_ATTACHMENT0,n.COLOR_ATTACHMENT1,n.COLOR_ATTACHMENT2]),s.snapPickLayerParams=[],s.snapPickLayerParams.push(null),u.forEach((e=>{!e.culled&&e.visible&&e.pickable&&e.drawSnapInit&&e.drawSnapInit(s)}));const y=s.snapPickLayerParams;s.snapPickLayerParams=[],n.depthMask(!1),n.drawBuffers([n.COLOR_ATTACHMENT0]);const w=e=>{s.snapMode=e,s.snapPickLayerParams.push(null),u.forEach((e=>{!e.culled&&e.visible&&e.pickable&&e.drawSnap&&e.drawSnap(s)}))};p&&w("edge"),f&&w("vertex"),n.depthMask(!0);const v=s.snapPickLayerParams,B=(e,t,i)=>{const s=b.buffer.width,r=b.buffer.height,A=new t(4*s*r);return n.readBuffer(e),n.readPixels(0,0,s,r,n.RGBA_INTEGER,i,A,0),A},C=B(n.COLOR_ATTACHMENT0,Int32Array,n.INT),M=B(n.COLOR_ATTACHMENT1,Int32Array,n.INT),E=B(n.COLOR_ATTACHMENT2,Uint32Array,n.UNSIGNED_INT);b.unbind();let F=null,U=null,x=null;const I=4*m+m*b.size[0]*4,P=C.slice(I,I+4),S=M.slice(I,I+4),D=E.slice(I,I+4);if(0!==P[3]){const e=y[Math.abs(P[3])%y.length];F=HA(P,e.origin,e.coordinateScale),U=LA(S),x=a.items[VA(D)]}const k=[];for(let e=0;e<C.length;e+=4){const t=C[e+3];if(t>0){const i=Math.floor(e/4),s=b.size[0],r=i%s-Math.floor(s/2),n=Math.floor(i/s)-Math.floor(s/2);k.push({dist:d.lenVec2([r,n]),isVertex:f&&p?t>v.length/2:f,result:C.subarray(e,e+4),normal:M.subarray(e,e+4),id:E.subarray(e,e+4)})}}const Q=e=>e&&e.delegatePickedEntity?e.delegatePickedEntity():e;if(k.length>0){const e=k.reduce(((e,t)=>(e.isVertex-t.isVertex||t.dist-e.dist)>0?e:t)),t=e.result,i=v[t[3]],s=HA(t,i.origin,i.coordinateScale),r=g.projectWorldPos(s);return A.reset(),A.snappedToEdge=!e.isVertex,A.snappedToVertex=e.isVertex,A.worldPos=s,A.worldNormal=LA(e.normal),A.entity=Q(a.items[VA(e.id)]),A.canvasPos=o||F&&g.projectWorldPos(F)||r,A.snappedCanvasPos=r,A}return F?(A.reset(),A.snappedToEdge=!1,A.snappedToVertex=!1,A.worldPos=F,A.worldNormal=U,A.entity=Q(x),A.canvasPos=o||g.projectWorldPos(F),A.snappedCanvasPos=o,A):null}}(),this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new QA(t),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){I();const e=C.getRenderBuffer("occlusionReadPix");if(e&&(e.setSize([n.drawingBufferWidth,n.drawingBufferHeight]),e.bind()),s.reset(),s.backfaces=!0,s.frontface=!0,s.viewParams=U(),s.nearPlaneHeight=x(t.camera,n.drawingBufferHeight),n.viewport(0,0,n.drawingBufferWidth,n.drawingBufferHeight),n.clearColor(0,0,0,0),n.enable(n.DEPTH_TEST),n.disable(n.CULL_FACE),n.disable(n.BLEND),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),u.forEach((e=>{!e.culled&&e.visible&&e.pickable&&e.drawOcclusion&&e.drawOcclusion(s)})),this._occlusionTester.drawMarkers(),e){const i=t.canvas.resolutionScale;this._occlusionTester.doOcclusionTest(((t,s)=>e.read(Math.round(i*t),Math.round(i*s)))),e.unbind()}}},this.snapshot=(()=>{let e=!1;const t=new Zn(n);let i=null;return{readPixels:(e,i,s)=>{t.bind(),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),_=!0,this.render();for(let r=0;r<s;r++){const s=2*r,n=4*r,A=t.read(e[s],e[s+1]);i[n]=A[0],i[n+1]=A[1],i[n+2]=A[2],i[n+3]=A[3]}t.unbind(),_=!0},beginSnapshot:()=>{t.setSize([n.drawingBufferWidth,n.drawingBufferHeight]),t.bind(),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),e=!0},renderSnapshotToCanvas:()=>{const s=t.buffer.width,r=t.buffer.height;return i&&i.width===s&&i.height===r||(i=function(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=s,e.height=r;const i=new Uint8Array(s*r*4),A=t.createImageData(s,r);return{width:s,height:r,getUpdatedCanvas:()=>{n.readPixels(0,0,s,r,n.RGBA,n.UNSIGNED_BYTE,i);const o=Math.floor(r/2),a=4*s,l=new Uint8Array(a);for(let e=0;e<o;++e){const t=e*a,s=(r-e-1)*a;l.set(i.subarray(t,t+a)),i.copyWithin(t,s,s+a),i.set(l,s)}return A.data.set(i),t.resetTransform(),t.putImageData(A,0,0),e}}}()),e&&(n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),_=!0,this.render(),_=!0),i.getUpdatedCanvas()},endSnapshot:()=>{e&&(t.unbind(),e=!1),_=!0,this.render()}}})(),this.destroy=function(){l={},c={},C.destroy(),E.destroy(),F.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class GA extends D{constructor(e,t={}){super(e,t),this.KEY_BACKSPACE=8,this.KEY_TAB=9,this.KEY_ENTER=13,this.KEY_SHIFT=16,this.KEY_CTRL=17,this.KEY_ALT=18,this.KEY_PAUSE_BREAK=19,this.KEY_CAPS_LOCK=20,this.KEY_ESCAPE=27,this.KEY_PAGE_UP=33,this.KEY_PAGE_DOWN=34,this.KEY_END=35,this.KEY_HOME=36,this.KEY_LEFT_ARROW=37,this.KEY_UP_ARROW=38,this.KEY_RIGHT_ARROW=39,this.KEY_DOWN_ARROW=40,this.KEY_INSERT=45,this.KEY_DELETE=46,this.KEY_NUM_0=48,this.KEY_NUM_1=49,this.KEY_NUM_2=50,this.KEY_NUM_3=51,this.KEY_NUM_4=52,this.KEY_NUM_5=53,this.KEY_NUM_6=54,this.KEY_NUM_7=55,this.KEY_NUM_8=56,this.KEY_NUM_9=57,this.KEY_A=65,this.KEY_B=66,this.KEY_C=67,this.KEY_D=68,this.KEY_E=69,this.KEY_F=70,this.KEY_G=71,this.KEY_H=72,this.KEY_I=73,this.KEY_J=74,this.KEY_K=75,this.KEY_L=76,this.KEY_M=77,this.KEY_N=78,this.KEY_O=79,this.KEY_P=80,this.KEY_Q=81,this.KEY_R=82,this.KEY_S=83,this.KEY_T=84,this.KEY_U=85,this.KEY_V=86,this.KEY_W=87,this.KEY_X=88,this.KEY_Y=89,this.KEY_Z=90,this.KEY_LEFT_WINDOW=91,this.KEY_RIGHT_WINDOW=92,this.KEY_SELECT_KEY=93,this.KEY_NUMPAD_0=96,this.KEY_NUMPAD_1=97,this.KEY_NUMPAD_2=98,this.KEY_NUMPAD_3=99,this.KEY_NUMPAD_4=100,this.KEY_NUMPAD_5=101,this.KEY_NUMPAD_6=102,this.KEY_NUMPAD_7=103,this.KEY_NUMPAD_8=104,this.KEY_NUMPAD_9=105,this.KEY_MULTIPLY=106,this.KEY_ADD=107,this.KEY_SUBTRACT=109,this.KEY_DECIMAL_POINT=110,this.KEY_DIVIDE=111,this.KEY_F1=112,this.KEY_F2=113,this.KEY_F3=114,this.KEY_F4=115,this.KEY_F5=116,this.KEY_F6=117,this.KEY_F7=118,this.KEY_F8=119,this.KEY_F9=120,this.KEY_F10=121,this.KEY_F11=122,this.KEY_F12=123,this.KEY_NUM_LOCK=144,this.KEY_SCROLL_LOCK=145,this.KEY_SEMI_COLON=186,this.KEY_EQUAL_SIGN=187,this.KEY_COMMA=188,this.KEY_DASH=189,this.KEY_PERIOD=190,this.KEY_FORWARD_SLASH=191,this.KEY_GRAVE_ACCENT=192,this.KEY_OPEN_BRACKET=219,this.KEY_BACK_SLASH=220,this.KEY_CLOSE_BRACKET=221,this.KEY_SINGLE_QUOTE=222,this.KEY_SPACE=32,this.MOUSE_LEFT_BUTTON=260,this.MOUSE_MIDDLE_BUTTON=261,this.MOUSE_RIGHT_BUTTON=262,this.element=t.element,this.altDown=!1,this.ctrlDown=!1,this.mouseDownLeft=!1,this.mouseDownMiddle=!1,this.mouseDownRight=!1,this.keyDown=[],this.enabled=!0,this.keyboardEnabled=!0,this.mouseover=!1,this.mouseCanvasPos=d.vec2(),this._keyboardEventsElement=t.keyboardEventsElement||document,this._bindEvents()}_bindEvents(){if(this._eventsBound)return;this._keyboardEventsElement.addEventListener("keydown",this._keyDownListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),this._keyboardEventsElement.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}});const e=this.scene.tickify((()=>this.fire("mousemove",this.mouseCanvasPos,!0)));this.element.addEventListener("mousemove",this._mouseMoveListener=t=>{this.enabled&&(this._getMouseCanvasPos(t),e(),this.mouseover&&t.preventDefault())}),this.element.addEventListener("contextmenu",this._contextmenuListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("contextmenu",this.mouseCanvasPos,!0))});const t=this.scene.tickify((e=>{this.fire("mousewheel",e,!0)}));this.element.addEventListener("wheel",this._mouseWheelListener=(e,i)=>{if(!this.enabled)return;const s=Math.max(-1,Math.min(1,40*-e.deltaY));t(s)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}this.element.addEventListener("touchstart",this._touchstartListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchstart",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this.element.addEventListener("touchend",this._touchendListener=e=>{this.enabled&&[...e.changedTouches].forEach((e=>{this.fire("touchend",[e.identifier,this._getTouchCanvasPos(e)],!0)}))}),this._eventsBound=!0}_unbindEvents(){this._eventsBound&&(this._keyboardEventsElement.removeEventListener("keydown",this._keyDownListener),this._keyboardEventsElement.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("contextmenu",this._contextmenuListener),this.element.removeEventListener("wheel",this._mouseWheelListener),this.element.removeEventListener("touchstart",this._touchstartListener),this.element.removeEventListener("touchend",this._touchendListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getTouchCanvasPos(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;return[e.pageX-i,e.pageY-s]}_getMouseCanvasPos(e){if(e){const t=e.target.getBoundingClientRect();this.mouseCanvasPos[0]=e.clientX-t.left,this.mouseCanvasPos[1]=e.clientY-t.top}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}class jA extends D{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new oe({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class WA extends D{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new oe({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.canvas.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),d.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.camera._updateScheduled=!0,this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const n=this.scene.canvas.canvas,A=n.offsetWidth/2,o=n.offsetHeight/2;return i[0]=(e[0]-A)/A,i[1]=(e[1]-o)/o,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class zA extends D{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new oe({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.canvas.boundary,s=i[2],r=i[3],n=s/r;let A,o,a,l;s>r?(A=-t,o=t,a=t/n,l=-t/n):(A=-t*n,o=t*n,a=t,l=-t),d.orthoMat4c(A,o,l,a,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:1e4;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const n=this.scene.canvas.canvas,A=n.offsetWidth/2,o=n.offsetHeight/2;return i[0]=(e[0]-A)/A,i[1]=(e[1]-o)/o,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class XA extends D{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new oe({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){d.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const n=this.scene.canvas.canvas,A=n.offsetWidth/2,o=n.offsetHeight/2;return i[0]=(e[0]-A)/A,i[1]=(e[1]-o)/o,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class KA extends D{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new oe({matrix:d.mat4(),inverseMatrix:d.mat4(),transposedMatrix:d.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(d.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(d.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const n=this.scene.canvas.canvas,A=n.offsetWidth/2,o=n.offsetHeight/2;return i[0]=(e[0]-A)/A,i[1]=(e[1]-o)/o,i[2]=t,i[3]=1,d.mulMat4v4(this.inverseMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,d.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const ZA=d.vec3(),JA=d.vec3(),YA=d.vec3(),$A=d.vec3(),qA=d.vec3(),eo=d.vec3(),to=d.vec4(),io=d.vec4(),so=d.vec4(),ro=d.mat4(),no=d.mat4(),Ao=d.vec3(),oo=d.vec3(),ao=d.vec3(),lo=d.vec3();class co extends D{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new oe({offsetEyeFromLook:!0,deviceMatrix:d.mat4(),hasDeviceMatrix:!1,matrix:d.mat4(),normalMatrix:d.mat4(),inverseMatrix:d.mat4()}),this._perspective=new WA(this),this._ortho=new zA(this),this._frustum=new XA(this),this._customProjection=new KA(this),this._project=this._perspective,this._eye=d.vec3([0,0,10]),this._look=d.vec3([0,0,0]),this._up=d.vec3([0,1,0]),this._worldUp=d.vec3([0,1,0]),this._worldRight=d.vec3([1,0,0]),this._worldForward=d.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection&&this._state.offsetEyeFromLook?(d.subVec3(this._eye,this._look,Ao),d.normalizeVec3(Ao,oo),d.mulVec3Scalar(oo,1e3,ao),d.addVec3(this._look,ao,lo),t=lo):t=this._eye,e.hasDeviceMatrix?(d.lookAtMat4v(t,this._look,this._up,no),d.mulMat4(e.deviceMatrix,no,e.matrix)):d.lookAtMat4v(t,this._look,this._up,e.matrix),d.inverseMat4(this._state.matrix,this._state.inverseMatrix),d.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=d.subVec3(this._eye,this._look,ZA);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,ro),t=d.transformPoint3(ro,t,JA),this.eye=d.addVec3(this._look,t,YA),this.up=d.transformPoint3(ro,this._up,$A)}orbitPitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._eye,this._look,ZA);const i=d.cross3Vec3(d.normalizeVec3(t,JA),d.normalizeVec3(this._up,YA));d.rotationMat4v(.0174532925*e,i,ro),t=d.transformPoint3(ro,t,$A),this.up=d.transformPoint3(ro,this._up,qA),this.eye=d.addVec3(t,this._look,eo)}yaw(e){let t=d.subVec3(this._look,this._eye,ZA);d.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,ro),t=d.transformPoint3(ro,t,JA),this.look=d.addVec3(t,this._eye,YA),this._gimbalLock&&(this.up=d.transformPoint3(ro,this._up,$A))}pitch(e){if(this._constrainPitch&&(e=d.dotVec3(this._up,this._worldUp)/d.DEGTORAD)<1)return;let t=d.subVec3(this._look,this._eye,ZA);const i=d.cross3Vec3(d.normalizeVec3(t,JA),d.normalizeVec3(this._up,YA));d.rotationMat4v(.0174532925*e,i,ro),this.up=d.transformPoint3(ro,this._up,eo),t=d.transformPoint3(ro,t,$A),this.look=d.addVec3(t,this._eye,qA)}pan(e){const t=d.subVec3(this._eye,this._look,ZA),i=[0,0,0];let s;if(0!==e[0]){const r=d.cross3Vec3(d.normalizeVec3(t,[]),d.normalizeVec3(this._up,JA));s=d.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=d.mulVec3Scalar(d.normalizeVec3(this._up,YA),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=d.mulVec3Scalar(d.normalizeVec3(t,$A),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=d.addVec3(this._eye,i,qA),this.look=d.addVec3(this._look,i,eo)}zoom(e){const t=d.subVec3(this._eye,this._look,ZA),i=Math.abs(d.lenVec3(t,JA)),s=Math.abs(i+e);if(s<.5)return;const r=d.normalizeVec3(t,YA);this.eye=d.addVec3(this._look,d.mulVec3Scalar(r,s),$A)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=d.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return d.lenVec3(d.subVec3(this._look,this._eye,ZA))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}get offsetEyeFromLook(){return this._state.offsetEyeFromLook}set offsetEyeFromLook(e){this._state.offsetEyeFromLook=e,this._needUpdate(0)}projectWorldPos(e){const t=to,i=io,s=so;t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,d.mulMat4v4(this.viewMatrix,t,i),d.mulMat4v4(this.projMatrix,i,s),d.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1;const r=this.scene.canvas.canvas,n=r.offsetWidth/2,A=r.offsetHeight/2;return[s[0]*n+n,s[1]*A+A]}destroy(){super.destroy(),this._state.destroy()}}const ho={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class uo extends D{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=d.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return ho}set units(e){e||(e="meters");ho[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=d.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=d.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class fo extends D{constructor(e,t={}){super(e,t),this._supported=PA.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}class po extends D{constructor(e,t={}){super(e,t),this.sliceColor=t.sliceColor,this.sliceThickness=t.sliceThickness}set sliceThickness(e){null==e&&(e=0),this._sliceThickness!==e&&(this._sliceThickness=e,this.glRedraw())}get sliceThickness(){return this._sliceThickness}set sliceColor(e){null==e&&(e=[0,0,0,1]),this._sliceColor!==e&&(this._sliceColor=e,this.glRedraw())}get sliceColor(){return this._sliceColor}destroy(){super.destroy()}}const go={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class mo extends Vi{get type(){return"PointsMaterial"}get presets(){return go}constructor(e,t={}){super(e,t),this._state=new oe({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null,filterIntensity:null,minIntensity:null,maxIntensity:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize),this.filterIntensity=t.filterIntensity,this.minIntensity=t.minIntensity,this.maxIntensity=t.maxIntensity}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set filterIntensity(e){e=!1!==e,this._state.filterIntensity!==e&&(this._state.filterIntensity=e,this.scene._needRecompile=!0,this.glRedraw())}get filterIntensity(){return this._state.filterIntensity}set minIntensity(e){this._state.minIntensity=null!=e?e:0,this.glRedraw()}get minIntensity(){return this._state.minIntensity}set maxIntensity(e){this._state.maxIntensity=null!=e?e:1,this.glRedraw()}get maxIntensity(){return this._state.maxIntensity}set preset(e){if(e=e||"default",this._preset===e)return;const t=go[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(go).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize,this.filterIntensity].join(";")}destroy(){super.destroy(),this._state.destroy()}}const _o={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class bo extends Vi{get type(){return"LinesMaterial"}get presets(){return _o}constructor(e,t={}){super(e,t),this._state=new oe({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=_o[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(_o).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function yo(e,t,i=2){const s=t&&t.length,r=s?t[0]*i:e.length;let n=wo(e,0,r,i,!0);const A=[];if(!n||n.next===n.prev)return A;let o,a,l;if(s&&(n=function(e,t,i,s){const r=[];for(let i=0,n=t.length;i<n;i++){const A=wo(e,t[i]*s,i<n-1?t[i+1]*s:e.length,s,!1);A===A.next&&(A.steiner=!0),r.push(Po(A))}r.sort(Uo);for(let e=0;e<r.length;e++)i=xo(r[e],i);return i}(e,t,n,i)),e.length>80*i){o=1/0,a=1/0;let t=-1/0,s=-1/0;for(let n=i;n<r;n+=i){const i=e[n],r=e[n+1];i<o&&(o=i),r<a&&(a=r),i>t&&(t=i),r>s&&(s=r)}l=Math.max(t-o,s-a),l=0!==l?32767/l:0}return Bo(n,A,i,o,a,l,0),A}function wo(e,t,i,s,r){let n;if(r===function(e,t,i,s){let r=0;for(let n=t,A=i-s;n<i;n+=s)r+=(e[A]-e[n])*(e[n+1]+e[A+1]),A=n;return r}(e,t,i,s)>0)for(let r=t;r<i;r+=s)n=Go(r/s|0,e[r],e[r+1],n);else for(let r=i-s;r>=t;r-=s)n=Go(r/s|0,e[r],e[r+1],n);return n&&Ro(n,n.next)&&(jo(n),n=n.next),n}function vo(e,t){if(!e)return e;t||(t=e);let i,s=e;do{if(i=!1,s.steiner||!Ro(s,s.next)&&0!==Qo(s.prev,s,s.next))s=s.next;else{if(jo(s),s=t=s.prev,s===s.next)break;i=!0}}while(i||s!==t);return t}function Bo(e,t,i,s,r,n,A){if(!e)return;!A&&n&&function(e,t,i,s){let r=e;do{0===r.z&&(r.z=To(r.x,r.y,t,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==e);r.prevZ.nextZ=null,r.prevZ=null,function(e){let t,i=1;do{let s,r=e;e=null;let n=null;for(t=0;r;){t++;let A=r,o=0;for(let e=0;e<i&&(o++,A=A.nextZ,A);e++);let a=i;for(;o>0||a>0&&A;)0!==o&&(0===a||!A||r.z<=A.z)?(s=r,r=r.nextZ,o--):(s=A,A=A.nextZ,a--),n?n.nextZ=s:e=s,s.prevZ=n,n=s;r=A}n.nextZ=null,i*=2}while(t>1)}(r)}(e,s,r,n);let o=e;for(;e.prev!==e.next;){const a=e.prev,l=e.next;if(n?Mo(e,s,r,n):Co(e))t.push(a.i,e.i,l.i),jo(e),e=l.next,o=l.next;else if((e=l)===o){A?1===A?Bo(e=Eo(vo(e),t),t,i,s,r,n,2):2===A&&Fo(e,t,i,s,r,n):Bo(vo(e),t,i,s,r,n,1);break}}}function Co(e){const t=e.prev,i=e,s=e.next;if(Qo(t,i,s)>=0)return!1;const r=t.x,n=i.x,A=s.x,o=t.y,a=i.y,l=s.y,c=Math.min(r,n,A),h=Math.min(o,a,l),u=Math.max(r,n,A),d=Math.max(o,a,l);let f=s.next;for(;f!==t;){if(f.x>=c&&f.x<=u&&f.y>=h&&f.y<=d&&Do(r,o,n,a,A,l,f.x,f.y)&&Qo(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function Mo(e,t,i,s){const r=e.prev,n=e,A=e.next;if(Qo(r,n,A)>=0)return!1;const o=r.x,a=n.x,l=A.x,c=r.y,h=n.y,u=A.y,d=Math.min(o,a,l),f=Math.min(c,h,u),p=Math.max(o,a,l),g=Math.max(c,h,u),m=To(d,f,t,i,s),_=To(p,g,t,i,s);let b=e.prevZ,y=e.nextZ;for(;b&&b.z>=m&&y&&y.z<=_;){if(b.x>=d&&b.x<=p&&b.y>=f&&b.y<=g&&b!==r&&b!==A&&Do(o,c,a,h,l,u,b.x,b.y)&&Qo(b.prev,b,b.next)>=0)return!1;if(b=b.prevZ,y.x>=d&&y.x<=p&&y.y>=f&&y.y<=g&&y!==r&&y!==A&&Do(o,c,a,h,l,u,y.x,y.y)&&Qo(y.prev,y,y.next)>=0)return!1;y=y.nextZ}for(;b&&b.z>=m;){if(b.x>=d&&b.x<=p&&b.y>=f&&b.y<=g&&b!==r&&b!==A&&Do(o,c,a,h,l,u,b.x,b.y)&&Qo(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;y&&y.z<=_;){if(y.x>=d&&y.x<=p&&y.y>=f&&y.y<=g&&y!==r&&y!==A&&Do(o,c,a,h,l,u,y.x,y.y)&&Qo(y.prev,y,y.next)>=0)return!1;y=y.nextZ}return!0}function Eo(e,t){let i=e;do{const s=i.prev,r=i.next.next;!Ro(s,r)&&Oo(s,i,i.next,r)&&Ho(s,r)&&Ho(r,s)&&(t.push(s.i,i.i,r.i),jo(i),jo(i.next),i=e=r),i=i.next}while(i!==e);return vo(i)}function Fo(e,t,i,s,r,n){let A=e;do{let e=A.next.next;for(;e!==A.prev;){if(A.i!==e.i&&ko(A,e)){let o=No(A,e);return A=vo(A,A.next),o=vo(o,o.next),Bo(A,t,i,s,r,n,0),void Bo(o,t,i,s,r,n,0)}e=e.next}A=A.next}while(A!==e)}function Uo(e,t){let i=e.x-t.x;if(0===i&&(i=e.y-t.y,0===i)){i=(e.next.y-e.y)/(e.next.x-e.x)-(t.next.y-t.y)/(t.next.x-t.x)}return i}function xo(e,t){const i=function(e,t){let i=t;const s=e.x,r=e.y;let n,A=-1/0;if(Ro(e,i))return i;do{if(Ro(e,i.next))return i.next;if(r<=i.y&&r>=i.next.y&&i.next.y!==i.y){const e=i.x+(r-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(e<=s&&e>A&&(A=e,n=i.x<i.next.x?i:i.next,e===s))return n}i=i.next}while(i!==t);if(!n)return null;const o=n,a=n.x,l=n.y;let c=1/0;i=n;do{if(s>=i.x&&i.x>=a&&s!==i.x&&So(r<l?s:A,r,a,l,r<l?A:s,r,i.x,i.y)){const t=Math.abs(r-i.y)/(s-i.x);Ho(i,e)&&(t<c||t===c&&(i.x>n.x||i.x===n.x&&Io(n,i)))&&(n=i,c=t)}i=i.next}while(i!==o);return n}(e,t);if(!i)return t;const s=No(i,e);return vo(s,s.next),vo(i,i.next)}function Io(e,t){return Qo(e.prev,e,t.prev)<0&&Qo(t.next,e,e.next)<0}function To(e,t,i,s,r){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-i)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-s)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function Po(e){let t=e,i=e;do{(t.x<i.x||t.x===i.x&&t.y<i.y)&&(i=t),t=t.next}while(t!==e);return i}function So(e,t,i,s,r,n,A,o){return(r-A)*(t-o)>=(e-A)*(n-o)&&(e-A)*(s-o)>=(i-A)*(t-o)&&(i-A)*(n-o)>=(r-A)*(s-o)}function Do(e,t,i,s,r,n,A,o){return!(e===A&&t===o)&&So(e,t,i,s,r,n,A,o)}function ko(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){let i=e;do{if(i.i!==e.i&&i.next.i!==e.i&&i.i!==t.i&&i.next.i!==t.i&&Oo(i,i.next,e,t))return!0;i=i.next}while(i!==e);return!1}(e,t)&&(Ho(e,t)&&Ho(t,e)&&function(e,t){let i=e,s=!1;const r=(e.x+t.x)/2,n=(e.y+t.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==e);return s}(e,t)&&(Qo(e.prev,e,t.prev)||Qo(e,t.prev,t))||Ro(e,t)&&Qo(e.prev,e,e.next)>0&&Qo(t.prev,t,t.next)>0)}function Qo(e,t,i){return(t.y-e.y)*(i.x-t.x)-(t.x-e.x)*(i.y-t.y)}function Ro(e,t){return e.x===t.x&&e.y===t.y}function Oo(e,t,i,s){const r=Lo(Qo(e,t,i)),n=Lo(Qo(e,t,s)),A=Lo(Qo(i,s,e)),o=Lo(Qo(i,s,t));return r!==n&&A!==o||(!(0!==r||!Vo(e,i,t))||(!(0!==n||!Vo(e,s,t))||(!(0!==A||!Vo(i,e,s))||!(0!==o||!Vo(i,t,s)))))}function Vo(e,t,i){return t.x<=Math.max(e.x,i.x)&&t.x>=Math.min(e.x,i.x)&&t.y<=Math.max(e.y,i.y)&&t.y>=Math.min(e.y,i.y)}function Lo(e){return e>0?1:e<0?-1:0}function Ho(e,t){return Qo(e.prev,e,e.next)<0?Qo(e,t,e.next)>=0&&Qo(e,e.prev,t)>=0:Qo(e,t,e.prev)<0||Qo(e,e.next,t)<0}function No(e,t){const i=Wo(e.i,e.x,e.y),s=Wo(t.i,t.x,t.y),r=e.next,n=t.prev;return e.next=t,t.prev=e,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function Go(e,t,i,s){const r=Wo(e,t,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function jo(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function Wo(e,t,i){return{i:e,x:t,y:i,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}const zo=[0,1,0],Xo=[1,0,0],Ko=d.vec3(),Zo=d.vec3(),Jo=d.vec3(),Yo=d.vec3(),$o=d.vec3();function qo(e,t){return Math.abs(e[0]-t[0])<1e-6&&Math.abs(e[1]-t[1])<1e-6&&Math.abs(e[2]-t[2])<1e-6}class ea{constructor(e){this.scene=e,this._resourcesAllocated=!1}_onCapMaterialUpdated(e,t){if(!this._resourcesAllocated){this._resourcesAllocated=!0,this._sectionPlanes=[],this._sceneModelsData={},this._dirtyMap={},this._prevIntersectionModelsMap={},this._sectionPlaneTimeout=null,this._updateTimeout=null;const e=e=>{const t=()=>{this._setAllDirty(!0),this._update()};this._sectionPlanes.push(e),e.on("pos",t),e.on("dir",t),e.on("active",t),e.once("destroyed",(()=>{const t=e.id;t&&(this._sectionPlanes=this._sectionPlanes.filter((e=>e.id!==t)),this._update())}).bind(this))};for(const t in this.scene.sectionPlanes)e(this.scene.sectionPlanes[t]);this._onSectionPlaneCreated=this.scene.on("sectionPlaneCreated",e),this._onTick=this.scene.on("tick",(()=>{let e=!1;for(const t in this._sceneModelsData)this.scene.models[t]?this._sceneModelsData[t].visible!==!!this.scene.models[t].visible&&(this._sceneModelsData[t].visible=!!this.scene.models[t].visible,e=!0):(delete this._sceneModelsData[t],e=!0);e&&this._update()}))}this._dirtyMap[t]||(this._dirtyMap[t]=new Map),this._dirtyMap[t].set(e,!0),this._update()}_update(){clearTimeout(this._updateTimeout),this._deletePreviousModels(),this._updateTimeout=setTimeout((()=>{clearTimeout(this._updateTimeout);const e=Object.values(this.scene.models).filter((e=>e.visible));this._addHatches(e,this._sectionPlanes.filter((e=>e.active))),this._setAllDirty(!1)}),100)}_setAllDirty(e){for(const t in this._dirty)this._dirtyMap[t].forEach(((i,s)=>this._dirtyMap[t].set(s,e)))}_addHatches(e,t){t.forEach((t=>{e.forEach((e=>{if(!this._doesPlaneIntersectBoundingBox(e.aabb,t))return;if(!this._dirtyMap[e.id])return;const i=new Map,s=e.objects,r=[d.vec3(),d.vec3(),d.vec3()];this._dirtyMap[e.id].forEach(((n,A)=>{if(!n)return;const o=s[A];if(!this._doesPlaneIntersectBoundingBox(o.aabb,t))return;if(!this._sceneModelsData[e.id]){const t=e.aabb;this._sceneModelsData[e.id]={verticesMap:new Map,indicesMap:new Map,modelOrigin:d.vec3([(t[0]+t[3])/2,(t[1]+t[4])/2,(t[2]+t[5])/2])}}const a=this._sceneModelsData[e.id],l=a.modelOrigin;if(!a.verticesMap.has(A)){const e=o.meshes[0].isSolid(),t=[],i=[];e&&o.capMaterial&&(o.getEachVertex((e=>t.push(e[0]-l[0],e[1]-l[1],e[2]-l[2]))),o.getEachIndex((e=>i.push(e)))),a.verticesMap.set(A,t),a.indicesMap.set(A,i)}const c=a.verticesMap.get(A),h=a.indicesMap.get(A),u=-d.dotVec3(d.subVec3(t.pos,l,Ko),t.dir),f=[],p=h.length;for(let e=0;e<p;e+=3){for(let t=0;t<3;t++){const i=3*h[e+t];r[t][0]=c[i],r[t][1]=c[i+1],r[t][2]=c[i+2]}if(!r[0][0]&&!r[0][1]&&!r[0][2])continue;const i=[];for(let e=0;e<3;e++){const s=r[e],n=r[(e+1)%3],A=u+d.dotVec3(t.dir,s),o=u+d.dotVec3(t.dir,n);if(A*o>0)continue;const a=-A/(o-A);i.push(d.lerpVec3(a,0,1,s,n,d.vec3()))}2===i.length&&f.push(i)}f.length>0&&i.set(A,f)}));const n=new Map;i.forEach(((e,t)=>{n.set(t,[[e[0]]]),e.splice(0,1);let s=0;for(;e.length>0;){const r=n.get(t)[s][n.get(t)[s].length-1][1];let A=!1;for(let i=0;i<e.length;i++){const[o,a]=e[i];if(qo(r,o)){n.get(t)[s].push(e[i]),e.splice(i,1),A=!0;break}if(qo(r,a)){n.get(t)[s].push([a,o]),e.splice(i,1),A=!0;break}}if(!A&&qo(r,n.get(t)[s][0][0])&&e.length>1)n.get(t).push([i.get(t)[0]]),e.splice(0,1),s++;else if(!A)break}}));const A=new Map;n.forEach(((e,i)=>{const s=[];for(let i=0;i<e.length;i++)s.push([]),e[i].forEach((e=>{s[i].push([this._projectTo2D(e[0],t.dir),this._projectTo2D(e[1],t.dir)])}));A.set(i,s)}));const o=new Map;let a;A.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin;a=[];const n=i,A=[],l=new Set;for(let e=0;e<n.length;e++){if(l.has(e))continue;const t=[n[e]];l.add(e);for(let i=e+1;i<n.length;i++)l.has(i)||(this._isLoopInside(n[e],n[i])||this._isLoopInside(n[i],n[e]))&&(t.push(n[i]),l.add(i));A.push(t)}A.forEach((e=>{const i=[],s=[];let n=0;const A=e.map((e=>{let t=0;for(let i=0;i<e.length;i++){const s=(i+1)%e.length;t+=e[i][0][0]*e[s][0][1],t-=e[s][0][0]*e[i][0][1]}return Math.abs(t)/2})),o=A.indexOf(Math.max(...A));e[o].forEach((e=>{i.push(e[0][0],e[0][1]),n+=2}));for(let t=0;t<e.length;t++)t!==o&&(s.push(n/2),e[t].forEach((e=>{i.push(e[0][0],e[0][1]),n+=2})));const l=yo(i,s),c=[];for(let e=0;e<l.length;e+=3){const s=[];for(let n=0;n<3;n++){const A=2*l[e+n],o=[i[A],i[A+1]],a=this._convertTo3D(o,t,r);s.push(a)}c.push(s)}a.push(c)})),o.set(s,a)}));const l=new Map;o.forEach(((e,t)=>{a=[],e.forEach((e=>{const t=new Map,i=[],s=[];let r=0;e.forEach((e=>{const n=[];e.forEach((e=>{const s=`${e[0].toFixed(6)},${e[1].toFixed(6)},${e[2].toFixed(6)}`;t.has(s)?n.push(t.get(s)):(i.push(e[0],e[1],e[2]),t.set(s,r),n.push(r),r++)})),s.push(...n)})),a.push({positions:i,indices:s})})),l.set(t,a)})),this._prevIntersectionModelsMap[e.id]||(this._prevIntersectionModelsMap[e.id]=new Map),d.mulVec3Scalar(t.dir,.001,$o),l.forEach(((i,s)=>{const r=this._sceneModelsData[e.id].modelOrigin,n=new Array(i.size);let A=0;i.forEach(((i,o)=>{const a=i.positions,l=i.indices;a.length;const c=d.buildNormals(a,l),h=this._createUVs(a,t,r);n[A++]=new Qi(this.scene,{id:`${t.id}-${s}-${o}`,geometry:new be(this.scene,{primitive:"triangles",positions:a,indices:l,normals:c,uv:h}),origin:d.addVec3(r,$o,Ko),position:[0,0,0],rotation:[0,0,0],material:e.objects[s].capMaterial})})),this._prevIntersectionModelsMap[e.id].has(s)?this._prevIntersectionModelsMap[e.id].get(s).push(...n):this._prevIntersectionModelsMap[e.id].set(s,n)}))}))}))}_doesPlaneIntersectBoundingBox(e,t){const i=[e[0],e[1],e[2]],s=[e[3],e[4],e[5]],r=[[i[0],i[1],i[2]],[s[0],i[1],i[2]],[i[0],s[1],i[2]],[s[0],s[1],i[2]],[i[0],i[1],s[2]],[s[0],i[1],s[2]],[i[0],s[1],s[2]],[s[0],s[1],s[2]]];let n=!1,A=!1;for(const e of r){const i=t.dist+d.dotVec3(t.dir,e);if(i>0&&(n=!0),i<0&&(A=!0),n&&A)return!0}return!1}_buildLines(e){for(const t in e)for(let i=0;i<e[t].length;i++){const s=e[t][i];s.length<=0||s.forEach(((e,t)=>{new Qi(this.scene,{clippable:!1,geometry:new be(this.scene,Oe({startPoint:e[0],endPoint:e[1]})),material:new Ni(this.scene,{emissive:[1,0,0]})})}))}}_projectTo2D(e,t){let i;i=Math.abs(t[0])>Math.abs(t[1])?[-t[2],0,t[0]]:[0,t[2],-t[1]],i=d.normalizeVec3(i);const s=d.vec3(t),r=d.cross3Vec3(s,i),n=d.normalizeVec3(r);return[d.dotVec3(e,i),d.dotVec3(e,n)]}_isLoopInside(e,t){const i=e[0][0];let s=!1;for(let e=0,r=t.length-1;e<t.length;r=e++){const n=t[e][0][0],A=t[e][0][1],o=t[r][0][0],a=t[r][0][1];A>i[1]!=a>i[1]&&i[0]<(o-n)*(i[1]-A)/(a-A)+n&&(s=!s)}return s}_convertTo3D(e,t,i){let s,r=t.dir,n=t.pos;s=Math.abs(r[0])>Math.abs(r[1])?[-r[2],0,r[0]]:[0,r[2],-r[1]],s=d.normalizeVec3(s);const A=d.vec3(r),o=d.cross3Vec3(A,s),a=d.normalizeVec3(o),l=e[0],c=e[1],h=[s[0]*l+a[0]*c,s[1]*l+a[1]*c,s[2]*l+a[2]*c],u=d.dotVec3(r,[n[0]-h[0]-i[0],n[1]-h[1]-i[1],n[2]-h[2]-i[2]]);return[h[0]+r[0]*u,h[1]+r[1]*u,h[2]+r[2]*u]}_deletePreviousModels(){for(const e in this._prevIntersectionModelsMap){this._prevIntersectionModelsMap[e].forEach(((t,i)=>{this._dirtyMap[e].get(i)&&(t.forEach((e=>{e.destroy()})),this._prevIntersectionModelsMap[e].delete(i))})),this._prevIntersectionModelsMap[e].size<=0&&delete this._prevIntersectionModelsMap[e]}}_createUVs(e,t,i){const s=t.pos,r=Ko;r.set(t.dir),d.normalizeVec3(r);const n=Zo,A=[];for(let t=0;t<e.length;t+=3){n[0]=e[t]+i[0],n[1]=e[t+1]+i[1],n[2]=e[t+2]+i[2];const o=d.subVec3(n,s,Jo),a=d.dotVec3(o,r);d.subVec3(n,d.mulVec3Scalar(r,a,Jo),n);const l=Math.abs(d.dotVec3(r,zo))<.999?d.cross3Vec3(r,zo,Jo):Xo,c=d.cross3Vec3(r,l,Jo);d.normalizeVec3(c,c);const h=d.subVec3(n,s,n);A.push(d.dotVec3(h,d.normalizeVec3(d.cross3Vec3(c,r,Yo))),d.dotVec3(h,c))}return A}destroy(){this._deletePreviousModels(),this._resourcesAllocated&&(this.scene.off(this._onModelLoaded),this.scene.off(this._onModelUnloaded),this.scene.off(this._onSectionPlaneCreated),this.scene.off(this._onTick))}}function ta(e,t){const i={};let s,r;for(let n=0,A=t.length;n<A;n++)s=t[n],r=e.components[s],r?r.isEntity?i[s]=!0:e.warn("pick(): Component is not an Entity: "+s):e.warn("pick(): Component not found: "+s);return i}class ia extends D{get type(){return"Scene"}constructor(e,t={}){super(null,t);const i=t.canvasElement||document.querySelector(`#${t.canvasId}`);if(!(i instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";this._tickifiedFunctions={};const s=!!t.transparent,r=!!t.alphaDepthMask;this._aabbDirty=!0,this._readableGeometry=!!t.readableGeometryEnabled,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.bitmaps={},this.lineSets={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new IA(this,{dontClear:!0,canvas:i,spinnerElementId:t.spinnerElementId,transparent:s,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha});const n=e=>this.viewer.destroy();i.addEventListener("webglcontextlost",n,!1),this._removeWebglcontextlostListener=()=>i.removeEventListener("webglcontextlost",n,!1),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new NA(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1,this._numCachedSectionPlanes=0;let e=null;this.getHash=function(){if(e)return e;const t=this.getNumAllocatedSectionPlanes();if(this.sectionPlanes,0===t)return this.hash=";";const i=[];for(let e=0,s=t;e<s;e++)i.push("cp");return i.push(";"),e=i.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let i=0,s=this.sectionPlanes.length;i<s;i++)if(this.sectionPlanes[i].id===t.id)return this.sectionPlanes.splice(i,1),void(e=null)},this.setNumCachedSectionPlanes=function(t){this._numCachedSectionPlanes=t,e=null},this.getNumCachedSectionPlanes=function(){return this._numCachedSectionPlanes},this.getNumAllocatedSectionPlanes=function(){const e=this.sectionPlanes.length;return e>this._numCachedSectionPlanes?e:this._numCachedSectionPlanes}},this._sectionPlanesState.setNumCachedSectionPlanes(t.numCachedSectionPlanes||0),this._lightsState=new function(){const e=d.vec4([0,0,0,0]),t=d.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i<r;i++)s=t[i],e.push("/"),e.push(s.type),e.push("world"===s.space?"w":"v"),s.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t<r;t++){if(this.lights[t].id===e.id)return this.lights.splice(t,1),s&&s.id===e.id&&(s=null),void(i=null)}},this.addReflectionMap=function(e){this.reflectionMaps.push(e),i=null},this.removeReflectionMap=function(e){for(let t=0,s=this.reflectionMaps.length;t<s;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(i=null)},this.addLightMap=function(e){this.lightMaps.push(e),i=null},this.removeLightMap=function(e){for(let t=0,s=this.lightMaps.length;t<s;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(i=null)},this.getAmbientColorAndIntensity=function(){if(!s)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){s=t;break}}if(s){const e=s.color,i=s.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=i,t}return e}},this.input=new GA(this,{dontClear:!0,element:this.canvas.canvas,keyboardEventsElement:t.keyboardEventsElement}),this.metrics=new uo(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new fo(this,{enabled:t.saoEnabled}),this.crossSections=new po(this,{}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._dtxEnabled=!1!==t.dtxEnabled,this._pbrEnabled=!!t.pbrEnabled,this._colorTextureEnabled=!1!==t.colorTextureEnabled,this._dtxEnabled=!!t.dtxEnabled,this._markerZOffset=t.markerZOffset,I._addScene(this),this._initDefaults(),this._viewport=new jA(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new co(this,{id:"default.camera",dontClear:!0}),this._sectionCaps=new ea(this),new Kn(this,{color:[1,1,1],intensity:.7}),new Jn(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new Jn(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()}))}_initDefaults(){}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+w.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=d.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],w.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_capMaterialUpdated(e,t){this._sectionCaps._onCapMaterialUpdated(e,t)}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_bitmapCreated(e){this.bitmaps[e.id]=e,this.scene.fire("bitmapCreated",e,!0)}_lineSetCreated(e){this.lineSets[e.id]=e,this.scene.fire("lineSetCreated",e,!0)}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_bitmapDestroyed(e){delete this.bitmaps[e.id],this.scene.fire("bitmapDestroyed",e,!0)}_lineSetDestroyed(e){delete this.lineSets[e.id],this.scene.fire("lineSetDestroyed",e,!0)}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){const t=e.id;delete this.models[t],this._modelIds=null,this.fire("modelUnloaded",t)}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_deRegisterVisibleObject(e){delete this.visibleObjects[e.id],this._numVisibleObjects--,this._visibleObjectIds=null}_objectXRayedUpdated(e,t=!0){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null,t&&this.fire("objectXRayed",e,!0)}_deRegisterXRayedObject(e){delete this.xrayedObjects[e.id],this._numXRayedObjects--,this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_deRegisterHighlightedObject(e){delete this.highlightedObjects[e.id],this._numHighlightedObjects--,this._highlightedObjectIds=null}_objectSelectedUpdated(e,t=!0){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null,t&&this.fire("objectSelected",e,!0)}_deRegisterSelectedObject(e){delete this.selectedObjects[e.id],this._numSelectedObjects--,this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_deRegisterColorizedObject(e){delete this.colorizedObjects[e.id],this._numColorizedObjects--,this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_deRegisterOpacityObject(e){delete this.opacityObjects[e.id],this._numOpacityObjects--,this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_deRegisterOffsetObject(e){delete this.offsetObjects[e.id],this._numOffsetObjects--,this._offsetObjectIds=null}get capabilities(){return this._renderer.capabilities}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get readableGeometryEnabled(){return this._readableGeometry}get pickSurfacePrecisionEnabled(){return this._readableGeometry}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set numCachedSectionPlanes(e){e=e||0,this._sectionPlanesState.getNumCachedSectionPlanes()!==e&&(this._sectionPlanesState.setNumCachedSectionPlanes(e),this._needRecompile=!0,this.glRedraw())}get numCachedSectionPlanes(){return this._sectionPlanesState.getNumCachedSectionPlanes()}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}set dtxEnabled(e){e=!!e,this._dtxEnabled!==e&&(this._dtxEnabled=e)}get dtxEnabled(){return this._dtxEnabled}set colorTextureEnabled(e){this._colorTextureEnabled=!!e,this.glRedraw()}get colorTextureEnabled(){return this._colorTextureEnabled}get markerZOffset(){return null==this._markerZOffset?-.001:this._markerZOffset}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&I.runTasks();const t={sceneId:null,pass:0};if(this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),e||this._renderer.needsRender()){t.sceneId=this.id;for(let i=0;i<this._passes;i++)t.pass=i,this.fire("rendering",t,!0),e&&this._renderer.imageDirty(),this._renderer.render(i,this._clearEachPass||0===i),this.fire("rendered",t,!0);this._saveAmbientColor()}}compile(){this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1)}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=d.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!w.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!w.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!w.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||Ee(be)}get material(){return this.components["default.material"]||new Ni(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new us(this,{id:"default.xrayMaterial",fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new us(this,{id:"default.highlightMaterial",fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new us(this,{id:"default.selectedMaterial",fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[1,1,1],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new fs(this,{id:"default.edgeMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new mo(this,{id:"default.pointsMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new bo(this,{id:"default.linesMaterial",fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1,dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){const e=this.aabb;this._center||(this._center=d.vec3()),this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=d.AABB3());let e,t=d.MAX_DOUBLE,i=d.MAX_DOUBLE,s=d.MAX_DOUBLE,r=d.MIN_DOUBLE,n=d.MIN_DOUBLE,A=d.MIN_DOUBLE;const o=this._collidables;let a,l=!1;for(const c in o)if(o.hasOwnProperty(c)){if(a=o[c],!1===a.collidable)continue;e=a.aabb,e[0]<t&&(t=e[0]),e[1]<i&&(i=e[1]),e[2]<s&&(s=e[2]),e[3]>r&&(r=e[3]),e[4]>n&&(n=e[4]),e[5]>A&&(A=e[5]),l=!0}l||(t=-100,i=-100,s=-100,r=100,n=100,A=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=n,this._aabb[5]=A,this._aabbDirty=!1,this._center=null}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(!this.canvas)return this.error("Picking not allowed on a destroyed Scene"),null;if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=ta(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=ta(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=e.snapToEdge||e.snapToVertex?this._renderer.snapPick(e,t):this._renderer.pick(e,t))&&t.entity&&t.entity.fire&&t.entity.fire("picked",t),t}snapPick(e){return this.canvas?(void 0===this._warnSnapPickDeprecated&&(this._warnSnapPickDeprecated=!0,this.warn("Scene.snapPick() is deprecated since v2.4.2 - use Scene.pick() instead")),e.canvasPos?this._renderer.snapPick(e):void this.error("Scene.snapPick() canvasPos parameter expected")):(this.error("Picking not allowed on a destroyed Scene"),null)}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t<i;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,i=e.length;t<i;t++)this.sectionPlanes[e[t]].destroy()}clearBitmaps(){const e=Object.keys(this.bitmaps);for(let t=0,i=e.length;t<i;t++)this.bitmaps[e[t]].destroy()}clearLines(){const e=Object.keys(this.lineSets);for(let t=0,i=e.length;t<i;t++)this.lineSets[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(w.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,i=d.MAX_DOUBLE,s=d.MAX_DOUBLE,r=d.MAX_DOUBLE,n=d.MIN_DOUBLE,A=d.MIN_DOUBLE,o=d.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const a=e.aabb;a[0]<i&&(i=a[0]),a[1]<s&&(s=a[1]),a[2]<r&&(r=a[2]),a[3]>n&&(n=a[3]),a[4]>A&&(A=a[4]),a[5]>o&&(o=a[5]),t=!0}})),t){const e=d.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=n,e[4]=A,e[5]=o,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){w.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s<r;s++){const r=e[s];let n=this.objects[r];if(n)i=t(n)||i;else{const e=this.modelIds;for(let s=0,A=e.length;s<A;s++){const A=e[s],o=d.globalizeObjectId(A,r);n=this.objects[o],n&&(i=t(n)||i)}}}return i}tickify(e){const t=e.toString();if(t in this._tickifiedFunctions)return this._tickifiedFunctions[t].wrapperFunc;let i,s=0,r=0;const n=function(...e){i=e,r++},A=this.on("tick",(()=>{r>s&&(s=r,e(...i))}));return this._tickifiedFunctions[t]={tickSubId:A,wrapperFunc:n},n}destroy(){super.destroy(),this._removeWebglcontextlostListener();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this._sectionCaps.destroy(),this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._sectionCaps=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const sa=d.vec4(),ra=d.vec4(),na=d.vec3(),Aa=d.vec3(),oa=d.vec3(),aa=d.vec4(),la=d.vec4(),ca=d.vec4();class ha{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=d.subVec3(e,r.eye,na);s=d.lenVec3(t)<i}if("perspective"===r.projection){r.ortho.scale=r.ortho.scale-i;const s=this._unproject(t,aa),n=d.subVec3(s,r.eye,ca),A=d.mulVec3Scalar(d.normalizeVec3(n),-i,[]);if(r.eye=[r.eye[0]-A[0],r.eye[1]-A[1],r.eye[2]-A[2]],r.look=[r.look[0]-A[0],r.look[1]-A[1],r.look[2]-A[2]],e){const t=d.subVec3(e,r.eye,na),i=d.lenVec3(t),s=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(r.look,r.eye,Aa)),i);r.look=[r.eye[0]+s[0],r.eye[1]+s[1],r.eye[2]+s[2]]}}else if("ortho"===r.projection){const e=this._unproject(t,aa);r.ortho.scale=r.ortho.scale-i,r.ortho._update();const s=this._unproject(t,la),n=d.subVec3(s,e,ca),A=d.mulVec3Scalar(d.normalizeVec3(d.subVec3(r.look,r.eye,na)),-i,Aa),o=d.addVec3(n,A,oa);r.eye=[r.eye[0]-o[0],r.eye[1]-o[1],r.eye[2]-o[2]],r.look=[r.look[0]-o[0],r.look[1]-o[1],r.look[2]-o[2]]}return s}_unproject(e,t){const i=this._scene.camera,s=i.project.transposedMatrix,r=s.subarray(8,12),n=s.subarray(12),A=[0,0,-1,1],o=d.dotVec4(A,r)/d.dotVec4(A,n);return i.project.unproject(e,o,sa,ra,t),t}destroy(){}}const ua=d.vec3(),da=d.vec3(),fa=d.vec3(),pa=d.vec4(),ga=d.vec4(),ma=d.vec4(),_a=Math.PI-.001;class ba{constructor(e,t){this._scene=e,this._configs=t,this._pivotWorldPos=d.vec3(),this._cameraOffset=d.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotSphereEnabled=!1,this._pivotSphere=null,this._pivotSphereSize=1,this._pivotSphereGeometry=null,this._pivotSphereMaterial=null,this._rtcCenter=d.vec3(),this._rtcPos=d.vec3(),this._pivotViewPos=d.vec4(),this._pivotProjPos=d.vec4(),this._pivotCanvasPos=d.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(()=>{this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement(),this.updatePivotSphere()}))}createPivotSphere(){const e=this.getPivotPos(),t=d.vec3();d.decomposeMat4(d.inverseMat4(this._scene.viewer.camera.viewMatrix,d.mat4()),t,d.vec4(),d.vec3());const i=d.distVec3(t,e);let s=Math.tan(Math.PI/500)*i*this._pivotSphereSize;"ortho"==this._scene.camera.projection&&(s/=this._scene.camera.ortho.scale/2),Ye(e,this._rtcCenter,this._rtcPos),this._pivotSphereGeometry=new ve(this._scene,Pe({radius:s})),this._pivotSphere=new Qi(this._scene,{geometry:this._pivotSphereGeometry,material:this._pivotSphereMaterial,pickable:!1,position:this._rtcPos,rtcCenter:this._rtcCenter})}destroyPivotSphere(){this._pivotSphere&&(this._pivotSphere.destroy(),this._pivotSphere=null),this._pivotSphereGeometry&&(this._pivotSphereGeometry.destroy(),this._pivotSphereGeometry=null)}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){d.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,d.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);let n=t._lastBoundingClientRect;if(!n||t._canvasSizeChanged){const e=t.canvas;n=t._lastBoundingClientRect=e.getBoundingClientRect()}this._pivotElement&&(this._pivotElement.style.left=Math.floor(n.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(n.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}updatePivotSphere(){this._pivoting&&this._pivotSphere&&(Ye(this.getPivotPos(),this._rtcCenter,this._rtcPos),d.compareVec3(this._rtcPos,this._pivotSphere.position)||(this.destroyPivotSphere(),this.createPivotSphere()))}setPivotElement(e){this._pivotElement=e}enablePivotSphere(e={}){this.destroyPivotSphere(),this._pivotSphereEnabled=!0,e.size&&(this._pivotSphereSize=e.size);const t=e.color||[1,0,0];this._pivotSphereMaterial=new Ni(this._scene,{emissive:t,ambient:t,specular:[0,0,0],diffuse:[0,0,0]})}disablePivotSphere(){this.destroyPivotSphere(),this._pivotSphereEnabled=!1}startPivot(){const e=this._scene.camera;let t=d.lookAtMat4v(e.eye,e.look,e.up);d.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=d.distVec3(e.eye,i),t=d.inverseMat4(t);const s=d.transformVec3(t,this._cameraOffset),r=d.vec3();if(d.subVec3(e.eye,i,r),d.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=d.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=d.normalizeVec3(d.subVec3(e.look,e.eye,ua)),i=d.cross3Vec3(t,e.worldUp,da);return d.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(d.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),n=s.subarray(12),A=[0,0,-1,1],o=d.dotVec4(A,r)/d.dotVec4(A,n),a=pa;t.project.unproject(e,o,ga,ma,a);const l=d.normalizeVec3(d.subVec3(a,t.eye,ua)),c=d.addVec3(t.eye,d.mulVec3Scalar(l,i,da),fa);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s;const n=r<0,A=r>0,o=Math.abs(this._polar-.001)<.005,a=Math.abs(this._polar-_a)<.005;let l=this._polar+.01*r;l=o&&n?.001:a&&A?_a:d.clamp(l,.001,_a),this._polar=l;const c=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=c[1];c[1]=c[2],c[2]=e}const h=d.lenVec3(d.subVec3(i.look,i.eye,d.vec3())),u=this.getPivotPos();d.addVec3(c,u);let f=d.lookAtMat4v(c,u,i.worldUp);f=d.inverseMat4(f);const p=d.transformVec3(f,this._cameraOffset);f[12]-=p[0],f[13]-=p[1],f[14]-=p[2];const g=[f[8],f[9],f[10]];i.eye=[f[12],f[13],f[14]],d.subVec3(i.eye,d.mulVec3Scalar(g,h),i.look),i.up=[f[4],f[5],f[6]],this.showPivot()}showPivot(){this._shown||(this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible"),this._pivotSphereEnabled&&(this.destroyPivotSphere(),this.createPivotSphere()),this._shown=!0)}hidePivot(){this._shown&&(this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._pivotSphereEnabled&&this.destroyPivotSphere(),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this.destroyPivotSphere(),this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class ya{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick=!1,this.pickCursorPos=d.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._lastHash=null,this._needFireEvents=0}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;const e=`${~~this.pickCursorPos[0]}-${~~this.pickCursorPos[1]}-${this.scheduleSnapOrPick}-${this.schedulePickSurface}-${this.schedulePickEntity}`;if(this._lastHash===e)return;this.picked=!1,this.pickedSurface=!1,this.snappedOrPicked=!1,this.hoveredSnappedOrSurfaceOff=!1;const t=this._cameraControl.hasSubs("hoverSurface");if(this.scheduleSnapOrPick){const e=this._scene.pick({canvasPos:this.pickCursorPos,snapRadius:this._configs.snapRadius,snapToVertex:this._configs.snapToVertex,snapToEdge:this._configs.snapToEdge});e&&(e.snappedToEdge||e.snappedToVertex)?(this.snapPickResult=e,this.snappedOrPicked=!0,this._needFireEvents++):(this.schedulePickSurface=!0,this.snapPickResult=null)}if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents+=t?1:0,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.hoveredSnappedOrSurfaceOff=!0,void(this.scheduleSnapOrPick=!1)}if(this.schedulePickEntity&&this.pickResult&&(this.pickResult.canvasPos||this.pickResult.snappedCanvasPos)){const e=this.pickResult.canvasPos||this.pickResult.snappedCanvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface||this.scheduleSnapOrPick&&!this.snapPickResult?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult?(this.picked=!0,this.scheduleSnapOrPick?this.snappedOrPicked=!0:this.pickedSurface=!0,this._needFireEvents++):this.scheduleSnapOrPick&&(this.hoveredSnappedOrSurfaceOff=!0,this._needFireEvents++)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents++)),this.scheduleSnapOrPick=!1,this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(0!==this._needFireEvents){if(this.hoveredSnappedOrSurfaceOff&&this._cameraControl.fire("hoverSnapOrSurfaceOff",{canvasPos:this.pickCursorPos,pointerPos:this.pickCursorPos},!0),this.snappedOrPicked)if(this.snapPickResult){const e=new MA;e.entity=this.snapPickResult.entity,e.snappedToVertex=this.snapPickResult.snappedToVertex,e.snappedToEdge=this.snapPickResult.snappedToEdge,e.worldPos=this.snapPickResult.worldPos,e.canvasPos=this.pickCursorPos,e.snappedCanvasPos=this.snapPickResult.snappedCanvasPos,this._cameraControl.fire("hoverSnapOrSurface",e,!0),this.snapPickResult=null}else this._cameraControl.fire("hoverSnapOrSurface",this.pickResult,!0);if(this.picked&&this.pickResult&&(this.pickResult.entity||this.pickResult.worldPos)){if(this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e)}this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=0}}}const wa=d.vec2();class va{constructor(e,t,i,s,r){this._scene=e;const n=t.pickController,A=t.cameraControl;let o,a,l,c=0,h=0,u=0,f=0,p=!1;const g=d.vec3();let m=!0;const _=this._scene.canvas.canvas,b=[];function y(e=!0){c=s.pointerCanvasPos[0],h=s.pointerCanvasPos[1],u=s.pointerCanvasPos[0],f=s.pointerCanvasPos[1],e&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),n.picked&&n.pickedSurface&&n.pickResult&&n.pickResult.worldPos?(p=!0,g.set(n.pickResult.worldPos)):p=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;b[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;b[s]=!1}),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{b.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{b.splice(0)}),_.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:b[e.input.KEY_SHIFT]||i.planView?(o=!0,b[e.input.MOUSE_LEFT_BUTTON]=!0,y()):(o=!0,b[e.input.MOUSE_LEFT_BUTTON]=!0,y(!1));break;case 2:a=!0,b[e.input.MOUSE_MIDDLE_BUTTON]=!0,y();break;case 3:l=!0,b[e.input.MOUSE_RIGHT_BUTTON]=!0,i.panRightClick&&y()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(!o&&!a&&!l)return;const n=e.canvas.boundary,u=n[2],f=n[3],m=s.pointerCanvasPos[0],_=s.pointerCanvasPos[1],y=i.planView||A._isKeyDownForAction(A.MOUSE_PAN,b),w=A._isKeyDownForAction(A.MOUSE_ROTATE,b),v=document.pointerLockElement?t.movementX:m-c,B=document.pointerLockElement?t.movementY:_-h;if(y){const t=e.camera;if("perspective"===t.projection){const i=Math.abs(p?d.lenVec3(d.subVec3(g,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(t.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*v*i/f,r.panDeltaY+=1.5*B*i/f}else r.panDeltaX+=.5*t.ortho.scale*(v/f),r.panDeltaY+=.5*t.ortho.scale*(B/f)}else w&&(i.planView||(i.firstPerson?(r.rotateDeltaY-=v/u*i.dragRotationRate/2,r.rotateDeltaX+=B/f*(i.dragRotationRate/4)):(r.rotateDeltaY-=v/u*(1.5*i.dragRotationRate),r.rotateDeltaX+=B/f*(1.5*i.dragRotationRate))));c=m,h=_}),_.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(m=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:case 2:case 3:o=!1,a=!1,l=!1,b[e.input.MOUSE_LEFT_BUTTON]=!1,b[e.input.MOUSE_MIDDLE_BUTTON]=!1,b[e.input.MOUSE_RIGHT_BUTTON]=!1}}),_.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){if(3===e.which){!function(e,t){if(e){let i=e.target,s=0,r=0,n=0,A=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,n+=i.scrollLeft,A+=i.scrollTop,i=i.offsetParent;t[0]=e.pageX+n-s,t[1]=e.pageY+A-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,wa);const i=wa[0],s=wa[1];Math.abs(i-u)<3&&Math.abs(s-f)<3&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(e.pageX),Math.round(e.pageY)],canvasPos:wa,event:e},!0)}_.style.removeProperty("cursor")}}),_.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const w=1/60;let v=null;_.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!(i.active&&i.pointerEnabled&&i.zoomOnMouseWheel&&A._isKeyDownForAction(A.MOUSE_DOLLY,b)))return;const t=performance.now()/1e3;var n=null!==v?t-v:0;v=t,n>.05&&(n=.05),n<w&&(n=w);const o=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===o)return;const a=o/Math.abs(o);r.dollyDelta+=-a*n*i.mouseWheelDollyRate,m&&(s.followPointerDirty=!0,m=!1)},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const Ba=d.vec3(),Ca=d.vec3(),Ma=d.vec3(),Ea=d.vec3(),Fa=d.vec3(),Ua={eye:d.vec3(),look:d.vec3(),up:d.vec3()};class xa{constructor(e,t,i,s){this._scene=e;const r=t.cameraControl,n=e.camera;this._onSceneKeyDown=e.input.on("keydown",(()=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const A=r._isKeyDownForAction(r.AXIS_VIEW_RIGHT),o=r._isKeyDownForAction(r.AXIS_VIEW_BACK),a=r._isKeyDownForAction(r.AXIS_VIEW_LEFT),l=r._isKeyDownForAction(r.AXIS_VIEW_FRONT),c=r._isKeyDownForAction(r.AXIS_VIEW_TOP),h=r._isKeyDownForAction(r.AXIS_VIEW_BOTTOM);if(!(A||o||a||l||c||h))return;const u=e.aabb,f=d.getAABB3Diag(u);d.getAABB3Center(u,Ba);const p=Math.abs(f/Math.tan(t.cameraFlight.fitFOV*d.DEGTORAD)),g=1.1*f;Ua.orthoScale=g,A?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldRight,p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(n.worldUp)):o?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldForward,p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(n.worldUp)):a?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldRight,-p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(n.worldUp)):l?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldForward,-p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(n.worldUp)):c?(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldUp,p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(d.normalizeVec3(d.mulVec3Scalar(n.worldForward,1,Ma),Ea))):h&&(Ua.eye.set(d.addVec3(Ba,d.mulVec3Scalar(n.worldUp,-p,Ca),Fa)),Ua.look.set(Ba),Ua.up.set(d.normalizeVec3(d.mulVec3Scalar(n.worldForward,-1,Ma)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(Ba),t.cameraFlight.duration>0?t.cameraFlight.flyTo(Ua,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(Ua),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())}))}reset(){}destroy(){this._scene.input.off(this._onSceneKeyDown)}}class Ia{constructor(e,t,i,s,r){this._scene=e;const n=t.pickController,A=t.pivotController,o=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null,this._lastClickedWorldPos=null;let a=!1,l=!1;const c=this._scene.canvas.canvas,h=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})},u=e.tickify(this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(a||l)return;if(o.hasSubs("rayMove")){const t=d.vec3(),i=d.vec3();d.canvasPosToWorldRay(e.canvas.canvas,e.camera.viewMatrix,e.camera.projMatrix,e.camera.projection,s.pointerCanvasPos,t,i),o.fire("rayMove",{canvasPos:s.pointerCanvasPos,ray:{origin:t,direction:i,canvasPos:s.pointerCanvasPos}},!0)}const r=o.hasSubs("hover"),A=o.hasSubs("hoverEnter"),c=o.hasSubs("hoverOut"),h=o.hasSubs("hoverOff"),u=o.hasSubs("hoverSurface"),f=o.hasSubs("hoverSnapOrSurface");if(r||A||c||h||u||f)if(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickEntity=!0,n.schedulePickSurface=u,n.scheduleSnapOrPick=f,n.update(),n.pickResult){if(n.pickResult.entity){const t=n.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&o.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),o.fire("hoverEnter",n.pickResult,!0),this._lastPickedEntityId=t)}o.fire("hover",n.pickResult,!0),(n.pickResult.worldPos||n.pickResult.snappedWorldPos)&&o.fire("hoverSurface",n.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(o.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),o.fire("hoverOff",{canvasPos:n.pickCursorPos},!0)});c.addEventListener("mousemove",u),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{1===t.which&&(a=!0),3===t.which&&(l=!0);if(1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickSurface=!0,n.update(),1===t.which))){const t=n.pickResult;t&&t.worldPos?(A.setPivotPos(t.worldPos),A.startPivot(),this._lastClickedWorldPos=t.worldPos.slice()):(i.smartPivot?A.setCanvasPivotPos(s.pointerCanvasPos):this._lastClickedWorldPos?A.setPivotPos(this._lastClickedWorldPos):A.setPivotPos(e.camera.look),A.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(a=!1),3===e.which&&(l=!1),A.getPivoting()&&A.endPivot()}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(!(1===r.which))return;if(A.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const a=o.hasSubs("picked"),l=o.hasSubs("pickedNothing"),c=o.hasSubs("pickedSurface"),u=o.hasSubs("doublePicked"),f=o.hasSubs("doublePickedSurface"),p=o.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||u||f||p))return(a||l||c)&&(n.pickCursorPos=s.pointerCanvasPos,n.schedulePickEntity=!0,n.schedulePickSurface=c,n.update(),n.pickResult?(o.fire("picked",n.pickResult,!0),n.pickedSurface&&o.fire("pickedSurface",n.pickResult,!0)):o.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks){n.pickCursorPos=s.pointerCanvasPos,n.schedulePickEntity=i.doublePickFlyTo,n.schedulePickSurface=c,n.update();const e=n.pickResult,r=n.pickedSurface;this._timeout=setTimeout((()=>{e?(o.fire("picked",e,!0),r&&(o.fire("pickedSurface",e,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(e.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):o.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),i.doubleClickTimeFrame)}else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),n.pickCursorPos=s.pointerCanvasPos,n.schedulePickEntity=i.doublePickFlyTo||u||f,n.schedulePickSurface=n.schedulePickEntity&&f,n.update(),n.pickResult){if(o.fire("doublePicked",n.pickResult,!0),n.pickedSurface&&o.fire("doublePickedSurface",n.pickResult,!0),i.doublePickFlyTo&&(h(n.pickResult),!i.firstPerson&&i.followPointer)){const e=n.pickResult.entity.aabb,i=d.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(o.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(h(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=d.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class Ta{constructor(e,t,i,s,r){this._scene=e;const n=e.input,A=[];e.canvas.canvas;let o=!0;this._onSceneMouseMove=n.on("mousemove",(()=>{o=!0})),this._onSceneKeyDown=n.on("keydown",(t=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover||(A[t]=!0))})),this._onSceneKeyUp=n.on("keyup",(s=>{i.active&&i.pointerEnabled&&e.input.keyboardEnabled&&(A[s]=!1,t.pivotController.getPivoting()&&t.pivotController.endPivot())})),document.addEventListener("visibilitychange",this._onVisibilityChange=()=>{A.splice(0)}),window.addEventListener("blur",this._onBlur=()=>{A.splice(0)}),this._onTick=e.on("tick",(a=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(i.keyboardEnabledOnlyIfMouseover&&!s.mouseover)return;const l=t.cameraControl,c=a.deltaTime/1e3;if(!i.planView){const e=l._isKeyDownForAction(l.ROTATE_Y_POS,A),s=l._isKeyDownForAction(l.ROTATE_Y_NEG,A),n=l._isKeyDownForAction(l.ROTATE_X_POS,A),o=l._isKeyDownForAction(l.ROTATE_X_NEG,A),a=c*i.keyboardRotationRate;(e||s||n||o)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=a:s&&(r.rotateDeltaY-=a),n?r.rotateDeltaX+=a:o&&(r.rotateDeltaX-=a),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!A[n.KEY_CTRL]&&!A[n.KEY_ALT]){const e=l._isKeyDownForAction(l.DOLLY_BACKWARDS,A),n=l._isKeyDownForAction(l.DOLLY_FORWARDS,A);if(e||n){const A=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),n?r.dollyDelta-=A:e&&(r.dollyDelta+=A),o&&(s.followPointerDirty=!0,o=!1)}}const h=l._isKeyDownForAction(l.PAN_FORWARDS,A),u=l._isKeyDownForAction(l.PAN_BACKWARDS,A),d=l._isKeyDownForAction(l.PAN_LEFT,A),f=l._isKeyDownForAction(l.PAN_RIGHT,A),p=l._isKeyDownForAction(l.PAN_UP,A),g=l._isKeyDownForAction(l.PAN_DOWN,A),m=(A[n.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(h||u||d||f||p||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:p&&(r.panDeltaY+=-m),f?r.panDeltaX+=-m:d&&(r.panDeltaX+=m),u?r.panDeltaZ+=m:h&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),this._scene.input.off(this._onSceneMouseMove),this._scene.input.off(this._onSceneKeyDown),document.removeEventListener("visibilitychange",this._onVisibilityChange),window.removeEventListener("blur",this._onBlur),this._scene.input.off(this._onSceneKeyUp)}}const Pa=d.vec3();class Sa{constructor(e,t,i,s,r){this._scene=e;const n=e.camera,A=t.pickController,o=t.pivotController,a=t.panController,l=t.cameraControl;let c=1,h=1,u=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer){if(--c<=0&&(c=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(A.pickCursorPos=s.pointerCanvasPos,A.schedulePickSurface=!0,A.update(),A.pickResult&&A.pickResult.worldPos?u=A.pickResult.worldPos:(h=1,u=null),s.followPointerDirty=!1),u){const t=Math.abs(d.lenVec3(d.subVec3(u,e.camera.eye,Pa)));h=t/i.dollyProximityThreshold}h<i.dollyMinSpeed&&(h=i.dollyMinSpeed)}}else h=1,u=null;const f=r.dollyDelta*h;if(0===r.rotateDeltaY&&0===r.rotateDeltaX||(!i.firstPerson&&i.followPointer&&o.getPivoting()?(o.continuePivot(r.rotateDeltaY,r.rotateDeltaX),o.showPivot()):(0!==r.rotateDeltaX&&(i.firstPerson?n.pitch(-r.rotateDeltaX):n.orbitPitch(r.rotateDeltaX)),0!==r.rotateDeltaY&&(i.firstPerson?n.yaw(r.rotateDeltaY):n.orbitYaw(r.rotateDeltaY))),r.rotateDeltaX*=i.rotationInertia,r.rotateDeltaY*=i.rotationInertia,t=l._cursors.rotate),Math.abs(r.panDeltaX)<.001&&(r.panDeltaX=0),Math.abs(r.panDeltaY)<.001&&(r.panDeltaY=0),Math.abs(r.panDeltaZ)<.001&&(r.panDeltaZ=0),0!==r.panDeltaX||0!==r.panDeltaY||0!==r.panDeltaZ){const e=d.vec3();let s,A;if(e[0]=r.panDeltaX,e[1]=r.panDeltaY,e[2]=r.panDeltaZ,i.constrainVertical){n.xUp?(s=n.eye[0],A=n.look[0]):n.yUp?(s=n.eye[1],A=n.look[1]):n.zUp&&(s=n.eye[2],A=n.look[2]),n.pan(e);const t=n.eye,i=n.look;n.xUp?(t[0]=s,i[0]=A):n.yUp?(t[1]=s,i[1]=A):n.zUp&&(t[2]=s,i[2]=A),n.eye=t,n.look=i}else n.pan(e);t=l._cursors.pan}if(r.panDeltaX*=i.panInertia,r.panDeltaY*=i.panInertia,r.panDeltaZ*=i.panInertia,0!==f){if(t=f<0?l._cursors.dollyForward:l._cursors.dollyBackward,i.firstPerson){let e,t;if(i.constrainVertical&&(n.xUp?(e=n.eye[0],t=n.look[0]):n.yUp?(e=n.eye[1],t=n.look[1]):n.zUp&&(e=n.eye[2],t=n.look[2])),i.followPointer){a.dollyToCanvasPos(u,s.pointerCanvasPos,-f)&&(s.followPointerDirty=!0)}else n.pan([0,0,f]),n.ortho.scale=n.ortho.scale-f;if(i.constrainVertical){const i=n.eye,s=n.look;n.xUp?(i[0]=e,s[0]=t):n.yUp?(i[1]=e,s[1]=t):n.zUp&&(i[2]=e,s[2]=t),n.eye=i,n.look=s}}else if(i.planView)if(i.followPointer){a.dollyToCanvasPos(u,s.pointerCanvasPos,-f)&&(s.followPointerDirty=!0)}else n.ortho.scale=n.ortho.scale+f,n.zoom(f);else if(i.followPointer){a.dollyToCanvasPos(u,s.pointerCanvasPos,-f)&&(s.followPointerDirty=!0)}else n.ortho.scale=n.ortho.scale+f,n.zoom(f);r.dollyDelta*=i.dollyInertia}A.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class Da{constructor(e,t,i,s,r){this._scene=e;const n=this._scene.canvas.canvas;n.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.mouseover=!0}),n.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,n.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{ka(e,n,s.pointerCanvasPos)}),n.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(ka(e,n,s.pointerCanvasPos),s.mouseover=!0)}),n.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function ka(e,t,i){if(e){const{left:s,top:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const Qa=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Ra{constructor(e,t,i,s,r){this._scene=e;const n=t.pickController,A=t.pivotController,o=d.vec2(),a=d.vec2(),l=d.vec2(),c=d.vec2(),h=[],u=this._scene.canvas.canvas;let f=0,p=!1;this._onTick=e.on("tick",(()=>{p=!1})),u.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.preventDefault();const r=t.touches,a=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===a.length&&(Qa(r[0],o),i.followPointer&&(n.pickCursorPos=o,n.schedulePickSurface=!0,n.update(),i.planView||(n.picked&&n.pickedSurface&&n.pickResult&&n.pickResult.worldPos?(A.setPivotPos(n.pickResult.worldPos),!i.firstPerson&&A.startPivot()&&A.showPivot()):(i.smartPivot?A.setCanvasPivotPos(s.pointerCanvasPos):A.setPivotPos(e.camera.look),!i.firstPerson&&A.startPivot()&&A.showPivot()))));h.length<r.length;)h.push(d.vec2());for(let e=0,t=r.length;e<t;++e)Qa(r[e],h[e]);f=r.length}),u.addEventListener("touchend",this._canvasTouchEndHandler=()=>{A.getPivoting()&&(A.endPivot(),A.hidePivot())}),u.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),p)return;p=!0;const A=e.canvas.boundary,o=A[2],u=A[3],g=t.touches;if(t.touches.length===f){if(1===f){Qa(g[0],a),d.subVec2(a,h[0],c);const t=c[0],n=c[1];if(null!==s.longTouchTimeout&&(Math.abs(t)>i.longTapRadius||Math.abs(n)>i.longTapRadius)&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),i.planView){const s=e.camera;if("perspective"===s.projection){const A=Math.abs(e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*A/u*i.touchPanRate,r.panDeltaY+=n*A/u*i.touchPanRate}else r.panDeltaX+=.5*s.ortho.scale*(t/u)*i.touchPanRate,r.panDeltaY+=.5*s.ortho.scale*(n/u)*i.touchPanRate}else r.rotateDeltaY-=t/o*(1*i.dragRotationRate),r.rotateDeltaX+=n/u*(1.5*i.dragRotationRate)}else if(2===f){const t=g[0],A=g[1];Qa(t,a),Qa(A,l);const o=d.geometricMeanVec2(h[0],h[1]),c=d.geometricMeanVec2(a,l),f=d.vec2();d.subVec2(o,c,f);const p=f[0],m=f[1],_=e.camera,b=d.distVec2([t.pageX,t.pageY],[A.pageX,A.pageY]),y=(d.distVec2(h[0],h[1])-b)*i.touchDollyRate;if(r.dollyDelta=y,Math.abs(y)<1)if("perspective"===_.projection){const t=n.pickResult?n.pickResult.worldPos:e.center,s=Math.abs(d.lenVec3(d.subVec3(t,e.camera.eye,[])))*Math.tan(_.perspective.fov/2*Math.PI/180);r.panDeltaX-=p*s/u*i.touchPanRate,r.panDeltaY-=m*s/u*i.touchPanRate}else r.panDeltaX-=.5*_.ortho.scale*(p/u)*i.touchPanRate,r.panDeltaY-=.5*_.ortho.scale*(m/u)*i.touchPanRate;s.pointerCanvasPos=c}for(let e=0;e<f;++e)Qa(g[e],h[e])}})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}const Oa=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Va{constructor(e,t,i,s,r){this._scene=e;const n=t.pickController,A=t.cameraControl;let o;const a=[],l=new Float32Array(2);let c=-1,h=-1;const u=this._scene.canvas.canvas,f=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;d.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};u.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null);const r=e.touches,n=e.changedTouches;if(o=Date.now(),1===r.length&&1===n.length){c=o,Oa(r[0],l);const n=l[0],A=l[1],a=r[0].pageX,h=r[0].pageY;s.longTouchTimeout=setTimeout((()=>{i.active&&i.pointerEnabled&&t.cameraControl.fire("rightClick",{pagePos:[Math.round(a),Math.round(h)],canvasPos:[Math.round(n),Math.round(A)],event:e},!0),s.longTouchTimeout=null}),i.longTapTimeout)}else c=-1;for(;a.length<r.length;)a.push(new Float32Array(2));for(let e=0,t=r.length;e<t;++e)Oa(r[e],a[e]);a.length=r.length},{passive:!0}),u.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),r=e.touches,o=e.changedTouches,u=A.hasSubs("pickedSurface");null!==s.longTouchTimeout&&(clearTimeout(s.longTouchTimeout),s.longTouchTimeout=null),0===r.length&&1===o.length&&c>-1&&t-c<150&&(h>-1&&c-h<325?(Oa(o[0],n.pickCursorPos),n.schedulePickEntity=!0,n.schedulePickSurface=u,n.update(),n.pickResult?(n.pickResult.touchInput=!0,A.fire("doublePicked",n.pickResult),n.pickedSurface&&A.fire("doublePickedSurface",n.pickResult),i.doublePickFlyTo&&f(n.pickResult)):(A.fire("doublePickedNothing"),i.doublePickFlyTo&&f()),h=-1):d.distVec2(a[0],l)<4&&(Oa(o[0],n.pickCursorPos),n.schedulePickEntity=!0,n.schedulePickSurface=u,n.update(),n.pickResult?(n.pickResult.touchInput=!0,A.fire("picked",n.pickResult),n.pickedSurface&&A.fire("pickedSurface",n.pickResult)):A.fire("pickedNothing"),h=t),c=-1),a.length=r.length;for(let e=0,t=r.length;e<t;++e)a[e][0]=r[e].pageX,a[e][1]=r[e].pageY},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}class La extends D{constructor(e,t={}){super(e,t),this.PAN_LEFT=0,this.PAN_RIGHT=1,this.PAN_UP=2,this.PAN_DOWN=3,this.PAN_FORWARDS=4,this.PAN_BACKWARDS=5,this.ROTATE_X_POS=6,this.ROTATE_X_NEG=7,this.ROTATE_Y_POS=8,this.ROTATE_Y_NEG=9,this.DOLLY_FORWARDS=10,this.DOLLY_BACKWARDS=11,this.AXIS_VIEW_RIGHT=12,this.AXIS_VIEW_BACK=13,this.AXIS_VIEW_LEFT=14,this.AXIS_VIEW_FRONT=15,this.AXIS_VIEW_TOP=16,this.AXIS_VIEW_BOTTOM=17,this.MOUSE_PAN=18,this.MOUSE_ROTATE=19,this.MOUSE_DOLLY=20,this._keyMap={},this.scene.canvas.canvas.oncontextmenu=e=>{e.preventDefault()},this._configs={longTapTimeout:600,longTapRadius:5,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,doubleClickTimeFrame:250,zoomOnMouseWheel:!0,snapToVertex:true,snapToEdge:true,snapRadius:30,keyboardEnabledOnlyIfMouseover:!0,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:d.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:d.vec2(),tapStartTime:-1,lastTapTime:-1,longTouchTimeout:null},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new ya(this,this._configs),pivotController:new ba(i,this._configs),panController:new ha(i),cameraFlight:new se(this,{duration:.5})},this._handlers=[new Da(this.scene,this._controllers,this._configs,this._states,this._updates),new Ra(this.scene,this._controllers,this._configs,this._states,this._updates),new va(this.scene,this._controllers,this._configs,this._states,this._updates),new xa(this.scene,this._controllers,this._configs,this._states,this._updates),new Ia(this.scene,this._controllers,this._configs,this._states,this._updates),new Va(this.scene,this._controllers,this._configs,this._states,this._updates),new Ta(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cursors={dollyForward:"zoom-in",dollyBackward:"zoom-out",rotate:"grabbing",pan:"move"},this._cameraUpdater=new Sa(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",w.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6],i[this.MOUSE_PAN]=[[t.MOUSE_LEFT_BUTTON,t.KEY_SHIFT],this._configs.panRightClick?t.MOUSE_RIGHT_BUTTON:t.MOUSE_MIDDLE_BUTTON],i[this.MOUSE_ROTATE]=[t.MOUSE_LEFT_BUTTON],i[this.MOUSE_DOLLY]=[]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_areAllKeysDown(e,t){if(!t||t.length<=0)return!0;if(!e)return!1;for(let i=0,s=t.length;i<s;i++){if(!e[t[i]])return!1}return!0}_isAnyOtherKeyDown(e,t){for(let i=0,s=e.length;i<s;i++)if(e[i])if(Array.isArray(t)){if(t.indexOf(i)<0)return!0}else if(i!==t)return!0;return!1}_isMouseAction(e){switch(e){case this.MOUSE_ROTATE:case this.MOUSE_DOLLY:case this.MOUSE_PAN:return!0;default:return!1}}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;if(0===i.length&&this._isMouseAction(e))return!0;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e<s;e++){const s=i[e];if(Array.isArray(s)){if(this._areAllKeysDown(t,s)&&!this._isAnyOtherKeyDown(t,s))return!0}else if(t[s]&&!this._isAnyOtherKeyDown(t,s))return!0}return!1}set pivotElement(e){this._controllers.pivotController.setPivotElement(e)}set active(e){e=!1!==e,this._configs.active=e,this._handlers[1]._active=e,this._handlers[5]._active=e}get active(){return this._configs.active}set snapToVertex(e){this._configs.snapToVertex=!!e}get snapToVertex(){return this._configs.snapToVertex}set snapToEdge(e){this._configs.snapToEdge=!!e}get snapToEdge(){return this._configs.snapToEdge}set snapRadius(e){e=e||30,this._configs.snapRadius=e}get snapRadius(){return this._configs.snapRadius}set keyboardEnabledOnlyIfMouseover(e){this._configs.keyboardEnabledOnlyIfMouseover=!!e}get keyboardEnabledOnlyIfMouseover(){return this._configs.keyboardEnabledOnlyIfMouseover}set navMode(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}get navMode(){return this._configs.navMode}set pointerEnabled(e){this._reset(),this._configs.pointerEnabled=!!e}setCursorStyle(e,t){Object.prototype.hasOwnProperty.call(this._cursors,e)?this._cursors={...this._cursors,[e]:t}:console.warn(`Action '${e}' is not valid for cursor styles.`)}getCursorStyle(e){return this._cursors[e]||null}_reset(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.reset&&t.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}get pointerEnabled(){return this._configs.pointerEnabled}set followPointer(e){this._configs.followPointer=!1!==e}get followPointer(){return this._configs.followPointer}set pivotPos(e){this._controllers.pivotController.setPivotPos(e)}get pivotPos(){return this._controllers.pivotController.getPivotPos()}set dollyToPointer(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}get dollyToPointer(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer}set panToPointer(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}get panToPointer(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1}set planView(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}get planView(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView}set firstPerson(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}get firstPerson(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson}set constrainVertical(e){this._configs.constrainVertical=!!e}get constrainVertical(){return this._configs.constrainVertical}set doublePickFlyTo(e){this._configs.doublePickFlyTo=!1!==e}get doublePickFlyTo(){return this._configs.doublePickFlyTo}set panRightClick(e){this._configs.panRightClick=!1!==e;const t=this._keyMap[this.MOUSE_PAN];if(t&&t.length>0){const e=this.scene.input;for(let i=0,s=t.length;i<s;i++)this._configs.panRightClick&&t[i]===e.MOUSE_MIDDLE_BUTTON?this._keyMap[this.MOUSE_PAN][i]=e.MOUSE_RIGHT_BUTTON:this._configs.panRightClick||t[i]!==e.MOUSE_RIGHT_BUTTON||(this._keyMap[this.MOUSE_PAN][i]=e.MOUSE_MIDDLE_BUTTON)}}get panRightClick(){return this._configs.panRightClick}set rotationInertia(e){this._configs.rotationInertia=null!=e?e:0}get rotationInertia(){return this._configs.rotationInertia}set keyboardPanRate(e){this._configs.keyboardPanRate=null!=e?e:5}set touchPanRate(e){this._configs.touchPanRate=null!=e?e:1}get touchPanRate(){return this._configs.touchPanRate}get keyboardPanRate(){return this._configs.keyboardPanRate}set keyboardRotationRate(e){this._configs.keyboardRotationRate=null!=e?e:90}get keyboardRotationRate(){return this._configs.keyboardRotationRate}set dragRotationRate(e){this._configs.dragRotationRate=null!=e?e:360}get dragRotationRate(){return this._configs.dragRotationRate}set keyboardDollyRate(e){this._configs.keyboardDollyRate=null!=e?e:15}get keyboardDollyRate(){return this._configs.keyboardDollyRate}set touchDollyRate(e){this._configs.touchDollyRate=null!=e?e:.2}get touchDollyRate(){return this._configs.touchDollyRate}set mouseWheelDollyRate(e){this._configs.mouseWheelDollyRate=null!=e?e:100}get mouseWheelDollyRate(){return this._configs.mouseWheelDollyRate}set dollyInertia(e){this._configs.dollyInertia=null!=e?e:0}get dollyInertia(){return this._configs.dollyInertia}set dollyProximityThreshold(e){this._configs.dollyProximityThreshold=null!=e?e:35}get dollyProximityThreshold(){return this._configs.dollyProximityThreshold}set dollyMinSpeed(e){this._configs.dollyMinSpeed=null!=e?e:.04}get dollyMinSpeed(){return this._configs.dollyMinSpeed}set panInertia(e){this._configs.panInertia=null!=e?e:.5}get panInertia(){return this._configs.panInertia}set keyboardLayout(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}get keyboardLayout(){return this._configs.keyboardLayout}enablePivotSphere(e={}){this._controllers.pivotController.enablePivotSphere(e)}disablePivotSphere(){this._controllers.pivotController.disablePivotSphere()}set smartPivot(e){this._configs.smartPivot=!1!==e}get smartPivot(){return this._configs.smartPivot}set doubleClickTimeFrame(e){this._configs.doubleClickTimeFrame=null!=e?e:250}get doubleClickTimeFrame(){return this._configs.doubleClickTimeFrame}set zoomOnMouseWheel(e){this._configs.zoomOnMouseWheel=!!e}get zoomOnMouseWheel(){return this._configs.zoomOnMouseWheel}destroy(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),super.destroy()}_destroyHandlers(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.destroy&&t.destroy()}}_destroyControllers(){for(let e=0,t=this._controllers.length;e<t;e++){const t=this._controllers[e];t.destroy&&t.destroy()}}}class Ha{constructor(e,t,i,s,r){this.name=e,this.type=i,this.value=t,this.valueType=s,this.description=r}}class Na{constructor(e){if(this.id=e.id,this.originalSystemId=e.originalSystemId,this.metaModels=[],this.name=e.name,this.type=e.type,this.properties=[],e.properties){const t=e.properties;for(let e=0,i=t.length;e<i;e++){const i=t[e];Number.isInteger(i)?this.properties.push(i):this.properties.push(new Ha(i.name,i.value,i.type,i.valueType,i.description))}}}}class Ga{constructor(e){this.metaModels=[],this.id=e.id,this.parentId=e.parentId,this.parent=null,this.originalSystemId=e.originalSystemId,this.name=e.name,this.type=e.type,this.propertySetIds=e.propertySetIds,this.propertySets=[],this.attributes=e.attributes||{},void 0!==e.external&&null!==e.external&&(this.external=e.external)}get metaModel(){return 1==this.metaModels.length?this.metaModels[0]:null}getObjectIDsInSubtree(){const e=[];return function t(i){if(!i)return;e.push(i.id);const s=i.children;if(s)for(var r=0,n=s.length;r<n;r++)t(s[r])}(this),e}withMetaObjectsInSubtree(e){!function t(i){if(!i)return;e(i);const s=i.children;if(s)for(var r=0,n=s.length;r<n;r++)t(s[r])}(this)}getObjectIDsInSubtreeByType(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=e[i];const r=[];return function e(i){if(!i)return;t[i.type]&&r.push(i.id);const s=i.children;if(s)for(var n=0,A=s.length;n<A;n++)e(s[n])}(this),r}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class ja{constructor(e){this.id=e.id,this.projectId=e.projectId,this.revisionId=e.revisionId,this.author=e.author,this.createdAt=e.createdAt,this.creatingApplication=e.creatingApplication,this.schema=e.schema,this.metaScene=e.metaScene,this.propertySets=[],this.rootMetaObjects=[],this.metaObjects={},this.graph=e.graph||{},this.metaScene.metaModels[this.id]=this,this._propertyLookup=[],this.finalized=!1}get rootMetaObject(){return 1===this.rootMetaObjects.length?this.rootMetaObjects[0]:null}loadData(e,t={}){if(this.finalized)throw"MetaScene already finalized - can't add more data";this._globalizeIDs(e,t);const i=this.metaScene,s=e.properties;if(s)for(let e=0,t=s.length;e<t;e++)this._propertyLookup.push(s[e]);if(e.propertySets)for(let t=0,s=e.propertySets.length;t<s;t++){const s=e.propertySets[t];s.properties||(s.properties=[]);let r=i.propertySets[s.id];r||(r=new Na({id:s.id,originalSystemId:s.originalSystemId||s.id,type:s.type,name:s.name,properties:s.properties}),i.propertySets[r.id]=r),r.metaModels.push(this),this.propertySets.push(r)}if(e.metaObjects)for(let t=0,s=e.metaObjects.length;t<s;t++){const s=e.metaObjects[t],r=s.id;let n=i.metaObjects[r];if(!n){const e=s.type,t=s.originalSystemId,i=s.propertySets||s.propertySetIds;n=new Ga({id:r,originalSystemId:t,parentId:s.parent,type:e,name:s.name,attributes:s.attributes,propertySetIds:i,external:s.external}),this.metaScene.metaObjects[r]=n,n.metaModels=[]}this.metaObjects[r]=n,s.parent||(this.rootMetaObjects.push(n),i.rootMetaObjects[r]=n),n.metaModels.push(this)}}_decompressProperties(e,t){const i=[];for(let s=0,r=t.length;s<r;s++){const r=t[s];if(Number.isInteger(r)){const n=e[r];n?t[s]=n:i.push(r)}}i.length>0&&console.error(`[MetaModel._decompressProperties] Properties not found: ${i}`)}finalize(){if(this.finalized)throw"MetaScene already finalized - can't re-finalize";const e=this.metaScene;for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.children&&(i.children=[]),i.propertySets&&(i.propertySets=[]),i.propertySetIds)for(let t=0,s=i.propertySetIds.length;t<s;t++){const s=i.propertySetIds[t],r=e.propertySets[s];i.propertySets.push(r)}}for(let t in e.metaObjects){const i=e.metaObjects[t];if(i.parentId){const t=e.metaObjects[i.parentId];t&&(i.parent=t,(t.children||(t.children=[])).push(i))}}for(let t in e.metaObjects){e.metaObjects[t].metaModels=[]}for(let t in e.metaModels){const i=e.metaModels[t];for(let e in i.metaObjects){i.metaObjects[e].metaModels.push(i)}}e.metaObjectsByType={};for(let t in e.metaObjects){const i=e.metaObjects[t],s=i.type;(e.metaObjectsByType[s]||(e.metaObjectsByType[s]={}))[t]=i}if(this.propertySets)for(let e=0,t=this.propertySets.length;e<t;e++){const t=this.propertySets[e];this._decompressProperties(this._propertyLookup,t.properties)}this._propertyLookup=[],this.finalized=!0,this.metaScene.fire("metaModelCreated",this.id)}getJSON(){const e={id:this.id,projectId:this.projectId,author:this.author,createdAt:this.createdAt,schema:this.schema,creatingApplication:this.creatingApplication,metaObjects:[],propertySets:[]},t=Object.values(this.metaObjects);for(let i=0,s=t.length;i<s;i++){const s=t[i],r={id:s.id,originalSystemId:s.originalSystemId,extId:s.extId,type:s.type,name:s.name};s.parent&&(r.parent=s.parent.id),s.attributes&&(r.attributes=s.attributes),s.propertySetIds&&(r.propertySetIds=s.propertySetIds),e.metaObjects.push(r)}for(let t=0,i=this.propertySets.length;t<i;t++){const i=this.propertySets[t],s={id:i.id,originalSystemId:i.originalSystemId,extId:i.extId,type:i.type,name:i.name,propertyies:[]};for(let e=0,t=i.properties.length;e<t;e++){const t=i.properties[e],r={id:t.id,description:t.description,type:t.type,name:t.name,value:t.value,valueType:t.valueType};s.properties.push(r)}e.propertySets.push(s)}return e}_globalizeIDs(e,t){const i=!!t.globalizeObjectIds;if(e.metaObjects)for(let t=0,s=e.metaObjects.length;t<s;t++){const s=e.metaObjects[t];if(s.originalSystemId=s.id,s.parent&&(s.originalParentSystemId=s.parent),i&&(s.id=d.globalizeObjectId(this.id,s.id),s.parent&&(s.parent=d.globalizeObjectId(this.id,s.parent))),i){const e=s.propertySetIds;if(e){const t=[];for(let i=0,s=e.length;i<s;i++)t.push(d.globalizeObjectId(this.id,e[i]));s.propertySetIds=t,s.originalSystemPropertySetIds=e}}else s.originalSystemPropertySetIds=s.propertySetIds}if(e.propertySets)for(let t=0,s=e.propertySets.length;t<s;t++){const s=e.propertySets[t];s.originalSystemId=s.id,i&&(s.id=d.globalizeObjectId(this.id,s.id))}}}class Wa{constructor(e,t){this.viewer=e,this.scene=t,this.metaModels={},this.propertySets={},this.metaObjects={},this.metaObjectsByType={},this.rootMetaObjects={},this._eventSubs={}}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}off(e){}createMetaModel(e,t,i={}){const s=new ja({metaScene:this,id:e,projectId:t.projectId||"none",revisionId:t.revisionId||"none",author:t.author||"none",createdAt:t.createdAt||"none",creatingApplication:t.creatingApplication||"none",schema:t.schema||"none",propertySets:[]});return s.loadData(t),s.finalize(),s}destroyMetaModel(e){const t=this.metaModels[e];if(t){if(t.propertySets)for(let i=0,s=t.propertySets.length;i<s;i++){const s=t.propertySets[i];if(1===s.metaModels.length&&s.metaModels[0].id===e)delete this.propertySets[s.id];else{const t=[];for(let i=0,r=s.metaModels.length;i<r;i++)s.metaModels[i].id!==e&&t.push(s.metaModels[i]);s.metaModels=t}}if(t.metaObjects)for(let i in t.metaObjects){const s=t.metaObjects[i];1===s.metaModels.length&&s.metaModels[0].id===e?(delete this.metaObjects[i],s.parent||delete this.rootMetaObjects[i]):s.metaModels=s.metaModels.filter((t=>t.id!==e))}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.children&&(t.children=[]),t.propertySets&&(t.propertySets=[]),t.propertySetIds)for(let e=0,i=t.propertySetIds.length;e<i;e++){const i=t.propertySetIds[e],s=this.propertySets[i];t.propertySets.push(s)}}this.metaObjectsByType={};for(let e in this.metaObjects){const t=this.metaObjects[e],i=t.type;t.children&&(t.children=null),(this.metaObjectsByType[i]||(this.metaObjectsByType[i]={}))[e]=t}for(let e in this.metaObjects){const t=this.metaObjects[e];if(t.parentId){const e=this.metaObjects[t.parentId];e&&(t.parent=e,(e.children||(e.children=[])).push(t))}}delete this.metaModels[e];for(let e in this.metaObjects){this.metaObjects[e].metaModels=[]}for(let e in this.metaModels){const t=this.metaModels[e];for(let e in t.metaObjects){t.metaObjects[e].metaModels.push(t)}}this.fire("metaModelDestroyed",e)}}getObjectIDsByType(e){const t=this.metaObjectsByType[e];return t?Object.keys(t):[]}getObjectIDsInSubtree(e,t,i){const s=[],r=this.metaObjects[e],n=t&&t.length>0?za(t):null,A=i&&i.length>0?za(i):null,o=e=>{if(!e)return;var t=!0;(A&&A[e.type]||n&&!n[e.type])&&(t=!1),t&&s.push(e.id);const i=e.children;if(i)for(var r=0,a=i.length;r<a;r++)o(i[r])};return o(r),s}withMetaObjectsInSubtree(e,t){const i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}function za(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=!0;return t}
|
|
24
24
|
/*!
|
|
25
25
|
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
|
|
26
26
|
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
|